8 static int inversenatcantor(int cantor, int *x, int *y) {
13 w = (int)floor((sqrt(8.0 * cantor + 1.0) - 1.0)/2.0);
25 static int inversecantor(int cantor, int *x, int *y) {
27 inversenatcantor(-cantor, x, y);
43 inversenatcantor(cantor, x, y);
49 * map non negative integer pairs to their cantor pairing function
50 * number, plus one. We add one so that the result is never zero,
51 * leaving zero to be "invalid" or "none" or what have you.
54 static int natcantor(int x, int y) {
55 return (x+y) * (x + y + 1) / 2 + y+1;
58 /* See http://en.wikipedia.org/wiki/Cantor_pairing_function */
59 /* see also http://szudzik.com/ElegantPairing.pdf */
61 * if either coordinate is negative, map the integers onto the
62 * whole numbers, and then return the negative of the adjusted
63 * cantor number. As for most grids negative coordinates will
64 * be invalid, this will allow for a <= 0 test for invalid
65 * or out of bounds (on the negative side anyway, you'll
66 * still have to test for out of range on the positive side).
68 * TODO figure out what the maximum supported coordinates are
69 * for given integer sizes.
71 int HL_cantor_xy(int x, int y) {
73 x = abs(2 * x) - (x < 0);
74 y = abs(2 * y) - (y < 0);
75 return -natcantor(x, y);
77 return natcantor(x,y);
80 int HL_cantor(struct HL_hex h) {
87 x = abs(2 * x) - (x < 0);
88 y = abs(2 * y) - (y < 0);
89 return -natcantor(x, y);
91 return natcantor(x,y);
94 struct HL_hex HL_uncantor(int cantor) {
97 inversecantor(cantor, &h.x, &h.y);