def str_to_hilbert(string, cursor=None): p = ceil(log2(len(string)**.5)) d = defaultdict(lambda: defaultdict(lambda: ' ')) for i, c in enumerate(string): y, x = hilbert.coordinates_from_distance(i, p, N=2) if cursor is not None and i == cursor: d[x][y] = "∎" else: d[x][y] = c return "\n".join("".join(d[y][x] for x in range(2**p)) for y in reversed(range(2**p)))
def load_code_linear(fileobj): code_helper = defaultdict(lambda: defaultdict(str)) chars = ''.join(char for line in fileobj for char in line.strip()) p = (ceil(len(chars)**.5) - 1).bit_length() for step, char in enumerate(chars): y, x = hilbert.coordinates_from_distance( step, p, N=2, ) code_helper[x][y] = char return code_helper, p
def _jump(self, cmd) -> 'j': steps = self.pop() distance = hilbert.distance_from_coordinates( [self.y, self.x], self.p, N=2, ) y, x = hilbert.coordinates_from_distance( distance + self.dir * steps, self.p, N=2, ) self.x, self.y = x, y
def next_coord(self): """Return the next coordinate""" distance = hilbert.distance_from_coordinates( [self.y, self.x], self.p, N=2, ) y, x = hilbert.coordinates_from_distance( distance + self.dir, self.p, N=2, ) return x, y
def hilbert_to_str(filename): code = [] try: with open(filename) as f: for line in reversed(f.readlines()): code.append(list(line.rstrip("\n"))) p = ceil(log2(max([len(code), max(len(line) for line in code)]))) sling = [] for i in range((2**p)**2): y, x = hilbert.coordinates_from_distance(i, p, N=2) try: sling.append(code[x][y]) except IndexError: sling.append(" ") return list("".join(sling).rstrip()) except FileNotFoundError: return []
def _goto(self, cmd) -> '§': distance = self.pop() # TODO: should take the direction (self.dir) into account. y, x = hilbert.coordinates_from_distance(distance, self.p, N=2) self.x, self.y = x, y
def hilbert_xy(i): return hilbert.coordinates_from_distance(N=2, h=i, p=p)