| 
View
 

CoordinateCompression

Page history last edited by Kenneth Finnegan 16 years, 8 months ago

I used this pair of macros when I was writing a program to solve Sudoku puzzles.  I was dealing with 9x9 two dimensional arrays and wanted an easy way to pass the coordinates between functions as one integer.

 

Code:

#define LOC_COMPRESS(x, y)   (x * 1000 + y)

#define LOC_UNCOMPRESS(a)    a/1000][a%1000

 

Usage:

int x=10, y=5, location, array[20][20];

 

location = LOC_COMPRESS(x, y);

array[LOC_UNCOMPRESS(location)];

 

Granted that this could just as well have been handled with a struct, but this was faster to code and all I needed at the time.  Remember that you can only store coordinates as large as the number in the macros, in this case 1000.  This number can easily be changed to anything you want to fit your needs.

 


Extensions:

I left the outside [ ] out of the LOC_UNCOMPRESS macro to make it more clear what is going on in the code, but they can be readded if you would like.

 

It would be easy to change this to handle three dimensional arrays as well.

#define LOC3_COMPRESS(x, y, z)   (x * 1000000 + y * 1000 + z)

#define LOC3_UNCOMPRESS(a)    a/1000000][a/1000][a%1000

 


Sources:

None.

Comments (0)

You don't have permission to comment on this page.