-2

I have code that multiplies 2 arrays together a 6x6 with a 3x3, but the output is in a 6x6 2D array when I need it to be in a 4x4 2D array.

The output looks like this:

[20, 0, 10, 10, 0, 20]
[20, 0, 10, 10, 0, 20]
[20, 0, 10, 10, 0, 20]
[20, 0, 10, 10, 0, 20]
[20, 0, 10, 10, 0, 20]
[20, 0, 10, 10, 0, 20]

When I need it to look like this

[0, 10, 10, 0]
[0, 10, 10, 0]
[0, 10, 10, 0]
[0, 10, 10, 0]

Will I have to redesign my looping code or could I make a new loop that populates an array with the middle parts of my current output

I cannot post code due to plagiarism rules, but the reason why I don't output a 4x4 is because I keep getting Out of Bounds error.

Thanks in advance

2 Answers2

0

Try this code sample, use this as an example
As you can't show your code, hopefully, this works for you

int firstarray[][] = {{20, 0, 10, 10, 0, 20}, {20, 0, 10, 10, 0, 20}, {20, 0, 10, 10, 0, 20}, {20, 0, 10, 10, 0, 20}, {20, 0, 10, 10, 0, 20}, {20, 0, 10, 10, 0, 20}};

int secondarray[][] = {{0, 10, 10, 0}, {0, 10, 10, 0}, {0, 10, 10, 0}, {0, 10, 10, 0}};

/* Create new 2d array to store the multiplication result using the original arrays' lengths on row and column respectively. */


int [][] resultArray = new int[firstarray.length][secondarray[0].length];


/* Loop through each and get the product, then sum up and store the value */

for (int i = 0; i < firstarray.length; i++) { 
for (int j = 0; j < secondarray[0].length; j++) { 
    for (int k = 0; k < firstarray[0].length; k++) { 
        resultArray[i][j] += firstarray[i][k] * secondarray[k][j];
    }
}
}

/* Show the result */
display(resultArray);
0

Create an array with two fewer rows, and copy the middle of each row using Arrays.copyOfRange:

public int[][] arrayMiddle(int[][] array) {
    int[][] out = new int[array.length - 2][];
    for (int i = 1; i < array.length - 1; ++i) {
        out[i-1] = Arrays.copyOfRange(array[i], 1, array[i].length - 1);
    }
    return out;
}
David Conrad
  • 15,432
  • 2
  • 42
  • 54