Skip to content

Instantly share code, notes, and snippets.

@j2kun
Last active January 4, 2022 19:26
Show Gist options
  • Save j2kun/56d6283cfbce1161c8401027333e7024 to your computer and use it in GitHub Desktop.
Save j2kun/56d6283cfbce1161c8401027333e7024 to your computer and use it in GitHub Desktop.
# $ python3 --version
# Python 3.10.1
# $ python3 hilbert.py
# [(0, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4), (4, 5), (5, 5), (5, 6), (5, 7), (6, 7), (6, 8), (7, 8)]
import math
def hilbert_iter(n):
(i, j) = (0, 0)
size = n * n
h = 0
d = 3
while h < size:
yield (i, j)
h += 1
l = math.floor(0.5 * math.log2(h & -h))
a = math.floor(h / (4**l)) % 4
is_odd = bool(l & 1)
d ^= 3 * (is_odd != (a == 3))
j += (d - 1) % 2
i += (d - 2) % 2
d ^= is_odd != (a == 1)
print(list(hilbert_iter(4)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment