### Simulating 2D array with 1D array?

Hi,

I'm trying to simulate a 2D array using a 1D array. The array looks like the following:

 ``12345678910111213141516`` ``````const int MAP_WIDTH = 20; const int MAP_HEIGHT = 10; const unsigned char MAP[MAP_WIDTH * MAP_HEIGHT + 1] = { "00000000000000000000" "11111111111111111110" "01111111101111111110" "01111111101111111110" "01111110000011111110" "01111111101111111110" "01111111101111111110" "01111111101111111110" "01111111111111111111" "00000000000000000000" };``````

If I wan't the index of a certain coordinate, say {10,5}, I would simply do:

`int index = MAP_WIDTH * 5 + 10`

What I wonder is, how would I go the other way around? If I have an index, how would I get the {X,Y} coordinate matching that index?

Kind Regards,

Robin
Last edited on
 ``1234567`` ``````index = MAP_WIDTH * row + column; row = index / MAP_WIDTH; //Integer division column = index % MAP_WIDTH; {5; 10} = 110; 110 = {110 / 20; 110 % 20} = {5; 10}``````
Thanks a lot!
I noticed that the above is incorrect. You say that the row (Y coordinate) is division (/) but in the example you use division on the X coordinate. I guess the example should be:

 ``12`` ``````{10; 5} = 110; 110 = {110 % 20; 110 / 20} = {10; 5}``````
Last edited on
2D matrix coordinates are in format {row, column}, where the row number is always first.
So my answer was correct for mathematical standpoint. C++ uses same notation for its multi dimensional arrays. Using another notation will be misleading for others reading your code, because everyone will expect it to be consistent with standard behavior.
http://en.wikipedia.org/wiki/Matrix_%28mathematics%29#Notation
Topic archived. No new replies allowed.