javaarraysmultiplicationdimensional

Multiplying two one-dimensional arrays


A quick question that bugs me (both from a mathematical perspective and implementation-wise). How do you multiply two one-dimensional arrays?

If we have:

int[] a = {1,2,3};
int[] b = {4,5,6};

And we wanna put the result into a variable c, how do you do the math and the implementation? Should c also be one-dimensional or two-dimensional?

Thank you in advance!

EDIT: To everyone asking what I want. I'm trying to solve a math problem that literally tells me:

a = {1,2,3};
b = {4,5,6};

c = a * b; //what is c?

I found nothing on the internet on how to do it mathematically and I am equally puzzled on how to do it in a programming language.


Solution

  • I'm not sure if you are trying to find the sum if everything, or trying to create a matrix with the multiplication.

    For sum refer to duffymo's answer.

    For a new array, the end product will be:

    int[][] c= {{4, 8, 12}, {5, 10, 15}, {6, 12, 18}};

    Idea: You can just loop through both of them and multiply each index. Then store the products in int[][] c. You can also just have them in a list depending on your implementation like so: c = {4, 8, 12, 5, 10, 15, 6, 12, 18}.

    int[][] c = new int[a.length][b.length];
    // int[] c = new int[a.length * b.length];
    for(int i = 0; i < a.length; i++){
        for(int j = 0; j < b.length; b++){
            c[i][j] = a[i] * b[j];
            // c[i * a.length + j] = a[i] * b[j]; if you want to store it in a 1D array
            // Try a few examples to see why this will work for 1D array
        }
    }