Free Version
Moderate

# Linear Algebra with Arrays: Dot Products and Other Calculations

ALGOR-VVIBWI

The array data structure is one of the most basic data structures available, but its simplicity does not prevent it from being widely useful. One area in which arrays are useful is in performing linear algebra calculations. An array can function as a vector, while a 2-dimensional array can function as a matrix.

As an example, consider the following function, dot, which calculates the dot product of two vectors (represented using arrays):

int dot(int[] A, int[] B) {
if(A.length != B.length)
throw new IllegalArgumentException("Input vectors have different lengths.");

int product = 0;
for(int i = 0; i < A.length; i++) {
product += A[i] * B[i];
}

return product;
}


Similar to the dot product, arrays can be used to implement other operations such as the vector cross product and matrix multiplication.

Now consider a newly invented operation, the doot product, which takes two equal-sized vectors as arguments. The doot product is implemented with the following method, doot:

int doot(int[] A, int[] B) {
if(A.length != B.length)
throw new IllegalArgumentException("Input vectors have different lengths.");

int product = 0;
for(int i = 0; i < A.length; i++) {
if(A[i] <= 0 || B[i] <= 0)
throw new IllegalArgumentException("Vector elements must all be positive.");

if(i % 2 == 0)
product += A[i] % B[i];
else
product += B[i] % A[i];
}

return product;
}


Study the doot method to understand how the doot product works. What is printed by the following code snippet?

int[] A = {3, 10, 7, 8, 9};
int[] B = {2, 2, 6, 1, 19};

int dootProduct = doot(A, B);