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.

1
  • 1
    It should probably be if (x == grid[y].length) Commented Mar 11, 2018 at 22:26

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

5 Comments

could you transform the 1d array back into a 2d one again
Yeah sure, but that wouldn't make much sense. Is it a requirement?. Here you can see how: stackoverflow.com/questions/2706529/…
I will give each solution a try and see which one works best
Calculating the position using your modulus method was the most efficient solution for me
Great, if using just one index is not an absolute requirement, using mod div is easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.