Reputation: 3
I need to set all of the values in a 2D array to zeros except for three of the values. 42 is in the top left corner, 3rd row 3rd column is -2, and 4th row 6th column is -3. The size of the array is unknown, for example:
[0,0,0,0,0,0,0]
[0,0,0,0,0,0,0]
[0,0,0,0,0,0,0]
[0,0,0,0,0,0,0]
[0,0,0,0,0,0,0]
[42,0,0,0,0,0,0]
[0,0,0,0,0,0,0]
[0,0,-2,0,0,0,0]
[0,0,0,0,0,-3,0]
[0,0,0,0,0,0,0]
This is what I have so far:
public static void setThreeNumbers(int[][] arr)
{
int[][] arr1 = arr;
for (int r = 0; r < arr.length; r++)
{
for (int c = 0; c < arr[0].length; c++)
{
if (arr[r][c] == arr[0][0])
{
arr1[r][c] = 42;
}
if (arr[r][c] == arr[2][2])
{
arr1[2][2] = -2;
}
if (arr[r][c] == arr[3][5])
{
arr1[3][5] = -3;
}
}
}
}
I'm getting an ArrayIndexOutOfBounds for the -3 because on one of the tests because there isn't enough rows in the array for the value to be changed to -3 and my if statement isn't working for this value.
Upvotes: 0
Views: 46
Reputation: 358
If you know the positions in which to set each value you want, you don't need to iterate through the 2d array using a for loop. Just check if the 2d array is big enough for that position and if so, set that value to whatever you want. Also, since you're passing an array to the setThreeNumbers
method, you don't need to create another array inside that method, because arrays are passed by reference.
Replace the method below with the one you currently have and it should work.
public static void setThreeNumbers(int[][] arr) {
if (arr.length > 0 && arr[0].length > 0) {
arr[0][0] = 42;
if(arr.length > 2 && arr[0].length > 2) {
arr[2][2] = -2;
if(arr.length > 3 && arr[0].length > 5) {
arr[3][5] = -3;
}
}
}
}
Upvotes: 1