Skip to content

Instantly share code, notes, and snippets.

@HaraldKorneliussen
Created May 10, 2019 14:04
Show Gist options
  • Save HaraldKorneliussen/21a246e72c3fcce39e3b8eb209b1492e to your computer and use it in GitHub Desktop.
Save HaraldKorneliussen/21a246e72c3fcce39e3b8eb209b1492e to your computer and use it in GitHub Desktop.
A quick and dirty implementation of Hilbert curves.
#!/usr/bin/python
from itertools import chain
hilbert = {
'A': list("-BF+AFA+FB-"),
'B': list("+AF-BFB-FA+"),
'-': ['-'],
'+': ['+'],
'F': ['F']
}
def iter(n):
l = ['A']
i = 0
while i < n:
l = chain.from_iterable([hilbert[e] for e in l])
i = i + 1
return ''.join(filter(lambda e: e not in ['A', 'B'], l)).replace('+-', '').replace('-+', '')
def perm(n):
s = iter(n)
current = 0
direction = 0
addends = [1, -2**n, -1, (2**n)]
ret = [0]
for c in s:
if c == 'F':
current += addends[direction]
ret.append(current)
elif c == '+':
direction = (direction + 1) % 4
elif c == '-':
direction = (direction - 1) % 4
else:
pass
return ret
def invert(p):
ret = [0] * len(p)
for i,n in enumerate(p):
ret[n] = i
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment