#!/bin/python3 moves = [] with open('day9.txt', 'r') as f: for line in f: [direc, count] = line.split(' ') count = int(count) for i in range(count): moves.append(direc) hlocs = [] hloc = (0, 0) for move in moves: if move == 'U': hloc = (hloc[0], hloc[1]-1) if move == 'D': hloc = (hloc[0], hloc[1]+1) if move == 'R': hloc = (hloc[0]+1, hloc[1]) if move == 'L': hloc = (hloc[0]-1, hloc[1]) hlocs.append(hloc) tlocs = set([(0, 0)]) tloc = (0, 0) for hloc in hlocs: if abs(hloc[0] - tloc[0]) > 1 or abs(hloc[1] - tloc[1]) > 1: if hloc[0] < tloc[0]: tloc = (tloc[0]-1, tloc[1]) elif hloc[0] > tloc[0]: tloc = (tloc[0]+1, tloc[1]) if hloc[1] < tloc[1]: tloc = (tloc[0], tloc[1]-1) elif hloc[1] > tloc[1]: tloc = (tloc[0], tloc[1]+1) else: if hloc[0] == tloc[0]+2: tloc = (tloc[0]+1, tloc[1]) elif hloc[0] == tloc[0]-2: tloc = (tloc[0]-1, tloc[1]) elif hloc[1] == tloc[1]+2: tloc = (tloc[0], tloc[1]+1) elif hloc[1] == tloc[1]-2: tloc = (tloc[0], tloc[1]-1) tlocs.add(tloc) print("part1", len(tlocs)) def print_state(n, parts): for y in range(-n, n): for x in range(-n, n): printed = False for i in range(10): if parts[i][0] == x and parts[i][1] == y: printed = True print(str(i), end='') break if not printed: print('#', end='') print('') print('') parts = [] visited = set([(0, 0)]) for i in range(10): parts.append((0, 0)) for move in moves: print(move) for i in range(10): if i == 0: if move == 'R': parts[0] = (parts[0][0]+1, parts[0][1]) if move == 'L': parts[0] = (parts[0][0]-1, parts[0][1]) if move == 'U': parts[0] = (parts[0][0], parts[0][1]-1) if move == 'D': parts[0] = (parts[0][0], parts[0][1]+1) else: (prevx, prevy) = parts[i-1] if abs(prevx - parts[i][0]) > 1 or abs(prevy - parts[i][1]) > 1: if prevx < parts[i][0]: parts[i] = (parts[i][0]-1, parts[i][1]) elif prevx > parts[i][0]: parts[i] = (parts[i][0]+1, parts[i][1]) if prevy < parts[i][1]: parts[i] = (parts[i][0], parts[i][1]-1) elif prevy > parts[i][1]: parts[i] = (parts[i][0], parts[i][1]+1) else: if prevx == parts[i][0]+2: parts[i] = (parts[i][0]+1, parts[i][1]) elif prevx == parts[i][0]-2: parts[i] = (parts[i][0]-1, parts[i][1]) elif prevy == parts[i][1]+2: parts[i] = (parts[i][0], parts[i][1]+1) elif prevy == parts[i][1]-2: parts[i] = (parts[i][0], parts[i][1]-1) if i == 9: visited.add(parts[-1]) print_state(5, parts) print('part2', len(visited))