from lib import str_to_int from collections import defaultdict def part_1(data): rules = {} steps = None start_state = None current_state = None current_value = None for line in data.splitlines(): if line.startswith("In state"): current_state = line[-2] rules[current_state] = {} elif "current value" in line: current_value = str_to_int(line) rules[current_state][current_value] = [] elif "- Write the value" in line: rules[current_state][current_value].append(str_to_int(line)) elif "- Move one slot to the right" in line: rules[current_state][current_value].append(1) elif "- Move one slot to the left" in line: rules[current_state][current_value].append(-1) elif "Continue with state" in line: rules[current_state][current_value].append(line[-2]) elif "Begin in state" in line: start_state = line[-2] elif "checksum after" in line: steps = str_to_int(line) elif line.strip() == "": pass else: print(line) assert False assert type(steps) is int assert start_state is not None current_state = start_state tape = defaultdict(int) pos = 0 for _ in range(steps): current_value = tape[pos] write_value, move, next_state = rules[current_state][current_value] tape[pos] = write_value pos += move current_state = next_state print(sum(tape.values())) def main(): with open("i25.txt") as f: data = f.read() part_1(data) if __name__ == "__main__": main()