I'm currently working on project of where 2d terrain maps are saved into a one-dimensional array. Each block in the map is indexed by xy coordinates. So, to save the map into a one-dimensional array, I used the row-major order method (http://en.wikipedia.org/wiki/Row-major_order) to convert the xy coordinates into a single index value (Which let me put the block into an array).
Now, my problem is how do I convert it back? I have a unique number which I have to convert back into xy coordinates. Any help would be appreciated. ^^
By Row Major Order If array is declared by a[m][n] where m is the number of rows while n is the number of columns, then address of an element a[i][j] of the array stored in row major order is calculated as, Address(a[i][j]) = B. A. + (i * n + j) * size.
In Row Major Order, elements of a multi-dimensional array are arranged sequentially row by row, which means filling all the index of first row and then moving on to the next row. Suppose we have some elements {1,2,3,4,5,6,7,8} to insert in array.
The elements of an array can be stored in column-major layout or row-major layout. For an array stored in column-major layout, the elements of the columns are contiguous in memory. In row-major layout, the elements of the rows are contiguous.
The difference is simply that in row-major order, consecutive elements of the rows of the array are contiguous in memory; in column-major order, consecutive elements of the columns are contiguous.
To calculate indices you should be using something like this:
index = X + Y * Width;
So, to reverse this you can take advantage of integer division truncation to get Y, and then X is just what's left over after what Y "used up":
Y = (int)(index / Width)
X = index - (Y * Width)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With