Return index of an element on 2d array Java

I have a 3 x 3 array private int[][] board

I want to get the index [i][j] as a integer representing the position of the element

For example

[0][0] = 0
[1][1] = 4  -- (middle spot)
[2][0] = 6 -- (last line, first item)

Is there an easy way instead of manually doing it for each position? Thanks

Answer

/ and % operations can help you

int getByPosition(int[][] arr, int pos) {
    return arr[pos / arr.length][pos % arr.length];
}

Update: to get position by indexes:

int getPosByIndex(int[][] arr, int i, int j) {
    return arr.length * i + j;
}

Leave a Reply

Your email address will not be published. Required fields are marked *