Skip to main content
6 of 11
Editing the explanation
Sherlock9
  • 12.4k
  • 1
  • 32
  • 68

Python 3, 327 289 275 271 239 bytes

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

Edit: Changed how g is incremented and decremented. Now using eval() and str.translate. No longer using l=len(s).

def h(s): t=[s[0][0]];x=y=g=0;b="A" for j in range(len(bin(len(s)))-3):b=b.translate({65:"-BF+AFA+FB-",66:"+AF-BFB-FA+"}) for c in b:g+=(c=="+")-(c=="-");a=c=="F";x,y=[[x+1-g%4,y],[x,y+g%4-2]][g%2]if a else(x,y);t+=[s[x][y]]*a return t 

Ungolfed:

# the following function is implemented in the code with b=b.translate 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 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 += -1 elif char == "+": heading += 1 elif char == "F": if heading % 4 == 3: y += 1 elif heading % 4 == 2: x -= 1 elif heading % 4 == 1: y -= 1 else: x += 1 output.append(mat[x][y]) return output 
Sherlock9
  • 12.4k
  • 1
  • 32
  • 68