I'm writing a program for visualizing crystals. As a part of the program, I have to generate all different basic points in a lattice structure. For those that aren't familiar with crystallography, you can find the most general cases of these structures here: https://en.wikipedia.org/wiki/Hermann%E2%80%93Mauguin_notation#Lattice_types
The problem was that I wanted to keep track of all these points. So I gave them a number. I was trying a bit with pen and paper, and found a nice algorithm to connect a coordinate (either in 2D or in 3D) with a number (and the other way around) by writing it out in binary form.
So if you want, for example, a simple cubic lattice in 2D, and you want to know the coordinates of point number 14. you can write this binary as 001110. You divide the number into 00|11|10, in which the most right part stands for (x,y)*1, the middle part part stands for (x,y)*2, the left part stands for (x,y)*4 (which is useless for number 14, just to make everything clear) and so on. So number 14 maps to the point (3, 2).
A simple C++ program to generate coordinates for the first 50 ints:
int x, y;
for (int n = 0; n < 50; n++)
{
x = 0;
y = 0;
bitset<16> nset(n);
for (int i = 0; i < 16/2; i++)
{
x+=(nset[2*i]*pow(2.,i));
y+=(nset[2*i+1]*pow(2.,i));
}
cout << n << "\t" << x << "\t" << y << endl;
}
I extended this algorithm to 3D by reserving an additional column for the z-value, and for the other Lattice types by reserving the first one or two columns with kind of x+1/2, y+1/2, z+1/2 properties, different for each Lattice type.
So here's my question: does this algorithm exists already? Has it a name? Or is this just an obvious application of binary math? I read some things about hashmaps, but this seems more efficient to me, at least if you are dealing with integer numbers.
This is my very first question at stackexchange, was doubting I had to post this here or at the physics forum. Or perhaps at the math forum, because this is kind of a R^2->R bijection. So please correct me if this question is not at the right place.
This mapping is called the Z-order curve or Morton code:
As shown in your example C++ code, the the x co-ordinate is stored in the even numbered bits and the y co-ordinate is stored in the odd numbered bits. The mapping can be easily extended to higher dimensions.
Some algorithms for fast interleaving of bits to encode these numbers using bit-manipulation operations can be found here.