1

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

0

1 Answer 1

4

/ 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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's how to convert a pos value into i, j pair. You should also show how to convert i, j pair into a pos value.

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.