1

Lets say we have a 8 x 8 2d integer array named grid and trying to select the element 0 at [5][5]

int[][] grid = new int{{1,1,1,1,1,1,1,1},
                       {1,1,1,1,1,1,1,1},
                       {1,1,1,1,1,1,1,1},
                       {1,1,1,1,1,1,1,1},
                       {1,1,1,1,1,1,1,1},
                       {1,1,1,1,1,0,1,1},
                       {1,1,1,1,1,1,1,1},
                       {1,1,1,1,1,1,1,1}};

Now the question is, is it possible to access the index of element 0 without using coordinates and just use a single number?

example: access the element 0 with the number 45, like a 1d array

I tried approaching this problem with a for loop but it is giving me out of range errors.

int x = 0;
int y = 0;

for (int i = 0;i<45;i++) {

   x += 1;

   if (x > grid[y].length) {

     x = 0;
     y += 1;

}

The code above is supposed to add x and y until it reaches the target element.

Dijkgraaf
  • 11,049
  • 17
  • 42
  • 54
void00
  • 29
  • 1
  • 9

1 Answers1

1

Eventually you would have to use the two indexes.

You could calculate the x and y given just a single number.

public static int getAt(int[][] matrix, int position) {
    int columns = matrix[0].length; // column size, matrix has to be at least 1x1
    return matrix[position / columns][position % columns];
}

public static void setAt(int[][] matrix, int position, int value) {
    int columns = matrix[0].length; // column size, matrix has to be at least 1x1
    matrix[position / columns][position % columns] = value;
}

Also in your example:

1) You don't need to use a for loop (and again eventually to access or modify the matrix you would have to use both indexes).

2) When y is greater or equal than the row size (8 in this case) you will receive an out of bounds exception because you only have 8 columns.

Finally the only way to access it with one index is if you transform the matrix to a 1d array.

Here you can see how: how to convert 2d array into 1d?

Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34