Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row-major order indices

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. ^^

like image 725
BizarreCake Avatar asked May 13 '11 12:05

BizarreCake


People also ask

What is the formula for row-major order?

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.

What is row-major order explain with example?

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.

What is row-major and column major arrangement?

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.

What is the difference between row-major order and column-major order?

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.


1 Answers

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)
like image 62
Martin Avatar answered Sep 29 '22 13:09

Martin