JacobIRR JacobIRR -4 years ago 159
Java Question

Return integer index of 1D array for 2D array of coordinates pairs

After reading 10+ threads about converting an entire array from 2D to 1D and vice versa, I'm wondering if there is a mathematical formula, requiring no iteration to return the index position of a pair of integers for a sorted 2D array.

My "grid" is always square, can be any size (it's 3x3 in this example), and I've got a sorted block of human friendly values from which I need to retrieve what I'm calling "True 1D indices" like this:

"Human-friendly" coordinates| Java 2D Indices | True 1D indices
[1,1],[1,2],[1,3], ==> [0,0],[0,1],[0,2], ==> 0 , 1 , 2
[2,1],[2,2],[2,3], ==> [1,0],[1,1],[1,2], ==> 3 , 4 , 5
[3,1],[3,2],[3,3], ==> [2,0],[2,1],[2,2], ==> 6 , 7 , 8


So I need a method for my class to give me the following results:

I enter 1,1 and get back 0,
I enter 3,2 and get back 7,
I enter 2,3 and get back 5,
etc etc...

I've played around with half a dozen equations where I try things like adding the coordinates to the previous row index squared, and I can never get the right result for every cell in the grid. Is there some special operator or Math function I'm missing?

Thanks.

Answer Source

let the matrix be of 3*3 ,3 rows and 3 column and we have to find the indices of (i,j) then the formula will be. indices= 3*(i-1)+j;

Note :- here 3*3 and i,j are not it java 2d array format it is in human friendly coordinates.

Example (i,j)=(2,3) indices=3*(2-1)+3 =6 And since your indices starts from 0 you could simply subtract one from 6 i.e. 5.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download