Skip to main content
2 of 11
More golfing
Sherlock9
  • 12.4k
  • 1
  • 32
  • 68

Python 3, 327 289 279 bytes

This is a solution I modified from my answer for another Hilbert curve question here. Any golfing tips are appreciated.

def h(s): l=len(s);t=[s[0][0]];x=y=g=0;b="A" for j in range(len(bin(l))-3):b=''.join("-BF+AFA+FB-"*(c=="A")+"+AF-BFB-FA+"*(c=="B")+c*(ord(c)%32>2)for c in b) for c in b: if"-"==c:g=~-g%4 elif"+"==c:g=-~g%4 elif"F"==c:x,y=[[x+1-g,y],[x,y+g-2]][g%2];t+=[s[x][y]] return t 

Ungolfed:

def hilbert(it): s="A" n="" for i in range(it): for c in s: if c == "A": n += "-BF+AFA+FB-" elif c == "B": n += "+AF-BFB-FA+" else: n += c # (ord(c)%32 > 2) in the code is the same as (c not in "AB") # since we only examine -, +, A, B and F s=n;n="" return s def matrix_to_hilbert(mat): length = len(mat) # this returns the number of rows in the matrix if length < 2: return mat it = len(bin(length)) - 3 hil = hilbert(it) output = [mat[0][0]] # a list that starts with the first element of the matrix x = 0 y = 0 heading = 0 for char in hil: # navigating the Hilbert curve if char == "-": heading = (heading-1)%4 elif char == "+": heading = (heading+1)%4 elif char == "F": if heading == 3: y += 1 elif heading == 2: x -= 1 elif heading == 1: y -= 1 else: x += 1 output.append(mat[x][y]) return output 
Sherlock9
  • 12.4k
  • 1
  • 32
  • 68