简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM