Advent of Code 2022 day 9
I thought I could get away with not properly implementing the algorithm and also not properly reading the question. Apparently not. It also took me far too long to even just parse the input, which I realise now could have just been:
instructions = [line.split(" ") for line in lines]
Maybe I do need a break after all.
with open("9.txt") as f: lines = f.read().splitlines() instructions = [ [line.split(" ")[0], int(line.split(" ")[1])] for line in lines ] state = {(0, 0)} now = (0, 0) H = (0, 0) T = (0, 0) def move(T): if abs(H[0] - T[0]) < 2 and abs(H[1] - T[1]) < 2: return T elif abs(H[0] - T[0]) == 2 and H[1] == T[1]: return (int((H[0] + T[0])/2), T[1]) elif abs(H[1] - T[1]) == 2 and H[0] == T[0]: return (T[0], int((H[1] + T[1])/2)) elif H[0] < T[0] and H[1] < T[1]: return (T[0]-1, T[1]-1) elif H[0] > T[0] and H[1] < T[1]: return (T[0]+1, T[1]-1) elif H[0] < T[0] and H[1] > T[1]: return (T[0]-1, T[1]+1) elif H[0] > T[0] and H[1] > T[1]: return (T[0]+1, T[1]+1) for [d, n] in instructions: if d == "R": for x in range(H[0]+1, H[0]+1+n): H = (x, H[1]) T = move(T) state.add(T) elif d == "L": for x in range(H[0]-1, H[0]-1-n, -1): H = (x, H[1]) T = move(T) state.add(T) elif d == "D": for y in range(H[1]+1, H[1]+1+n): H = (H[0], y) T = move(T) state.add(T) elif d == "U": for y in range(H[1]-1, H[1]-1-n, -1): H = (H[0], y) T = move(T) state.add(T) print(len(state)) # part 2 states = {i: (0,0) for i in range(10)} tails = {(0,0)} def move(H, T): if abs(H[0] - T[0]) < 2 and abs(H[1] - T[1]) < 2: return T elif abs(H[0] - T[0]) == 2 and H[1] == T[1]: return (int((H[0] + T[0])/2), T[1]) elif abs(H[1] - T[1]) == 2 and H[0] == T[0]: return (T[0], int((H[1] + T[1])/2)) elif H[0] < T[0] and H[1] < T[1]: return (T[0]-1, T[1]-1) elif H[0] > T[0] and H[1] < T[1]: return (T[0]+1, T[1]-1) elif H[0] < T[0] and H[1] > T[1]: return (T[0]-1, T[1]+1) elif H[0] > T[0] and H[1] > T[1]: return (T[0]+1, T[1]+1) for [d, n] in instructions: if d == "R": for x in range(states[0][0]+1, states[0][0]+1+n): states[0] = (x, states[0][1]) for i in range(1, 10): states[i] = move(states[i-1], states[i]) tails.add(states[9]) elif d == "L": for x in range(states[0][0]-1, states[0][0]-1-n, -1): states[0] = (x, states[0][1]) for i in range(1, 10): states[i] = move(states[i-1], states[i]) tails.add(states[9]) elif d == "D": for y in range(states[0][1]+1, states[0][1]+1+n): states[0] = (states[0][0], y) for i in range(1, 10): states[i] = move(states[i-1], states[i]) tails.add(states[9]) elif d == "U": for y in range(states[0][1]-1, states[0][1]-1-n, -1): states[0] = (states[0][0], y) for i in range(1, 10): states[i] = move(states[i-1], states[i]) tails.add(states[9]) print(len(tails))