10

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

stema
  • 90,351
  • 20
  • 107
  • 135
BizarreCake
  • 662
  • 5
  • 14

1 Answers1

11

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)
Martin
  • 12,469
  • 13
  • 64
  • 128
  • That doesn't seem to work. For example (0, 4) gives 20 and when reversed, 20 gives back (16, 4) – BizarreCake May 13 '11 at 12:46
  • 1
    He has the right idea, I think he just made a typo. X = index - (y* width); So X is what is left over after you remove the Rows used up by Y. – TurqMage May 13 '11 at 17:51
  • Oops, this is what comes of answering questions when you've just got out of bed! Thanks for correcting me. – Martin May 13 '11 at 19:00