In [1]:
get_ipython().ast_node_interactivity = 'all' import matplotlib.pyplot as plt import numpy as np
In [2]:
def rot(n, x, y, rx, ry): if ry == 0: if rx == 1: x = (n - 1) - x y = (n - 1) - y t = x x = y y = t return x, y
In [3]:
def xy2d(n, x, y): rx = 0 ry = 0 s = int(n / 2) d = 0 while s > 0: rx = int((x & s) > 0) ry = int((y & s) > 0) d += s * s * ((3 * rx) ^ ry) x, y = rot(n, x, y, rx, ry) s //= 2 return d
In [4]:
for x in range(10): for y in range(10): print(xy2d(50, x, y))
Out:
0 635 45 754 488 815 488 815 769 799 1905 1270 2364 1367 2373 1450 2364 1450 1404 1414 128 682 90 718 524 860 524 860 897 887 2076 1306 2256 1342 2256 1486 2256 1486 1523 1511 180 1103 245 1148 360 995 389 995 1041 1031 2085 1718 2265 1783 2265 1630 2265 1630 1676 1646 189 1103 234 1148 369 1004 378 1004 1041 1031 2076 1727 2256 1772 2256 1630 2256 1630 1667 1655 2039 1712 2280 1800 2271 1584 2280 1584 1538 1568 2029 1682 2292 1810 2301 1594 2292 1594 1548 1558
In [5]:
""" //convert (x,y) to d int xy2d (int n, int x, int y) { int rx, ry, s, d=0; for (s=n/2; s>0; s/=2) { rx = (x & s) > 0; ry = (y & s) > 0; d += s * s * ((3 * rx) ^ ry); rot(n, &x, &y, rx, ry); } return d; } //convert d to (x,y) void d2xy(int n, int d, int *x, int *y) { int rx, ry, s, t=d; *x = *y = 0; for (s=1; s<n; s*=2) { rx = 1 & (t/2); ry = 1 & (t ^ rx); rot(s, x, y, rx, ry); *x += s * rx; *y += s * ry; t /= 4; } } //rotate/flip a quadrant appropriately void rot(int n, int *x, int *y, int rx, int ry) { if (ry == 0) { if (rx == 1) { *x = n-1 - *x; *y = n-1 - *y; } //Swap x and y int t = *x; *x = *y; *y = t; } } """
Out [5]:
'\n//convert (x,y) to d\nint xy2d (int n, int x, int y) {\n int rx, ry, s, d=0;\n for (s=n/2; s>0; s/=2) {\n rx = (x & s) > 0;\n ry = (y & s) > 0;\n d += s * s * ((3 * rx) ^ ry);\n rot(n, &x, &y, rx, ry);\n }\n return d;\n}\n\n//convert d to (x,y)\nvoid d2xy(int n, int d, int *x, int *y) {\n int rx, ry, s, t=d;\n *x = *y = 0;\n for (s=1; s