Jack Logan
Jack Logan

Reputation: 95

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

Upvotes: 1

Views: 47

Answers (1)

Ruslan
Ruslan

Reputation: 6290

/ 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;
}

Upvotes: 4

Related Questions