#/usr/bin/env python from scanf import scanf # 0 is left, 1 is right def next_cursor_position(cursor, direction): left = 0 right = 1 next_cursor = cursor if direction==left: next_cursor -= 1 elif direction==right: next_cursor += 1 return next_cursor def read(cursor, tape): if cursor not in tape: tape[cursor] = 0 return tape[cursor] def write(cursor, tape, value): tape[cursor] = value def read_blueprint(file_path): states = {} total_steps = 0 current_state = None inside_state = None current_value = None value_to_write = None direction_to_move = None next_state = None with open(file_path) as f: for line in f: if line[:14] == "Begin in state": current_state, = scanf("Begin in state %s", line) current_state = current_state[:-1] # getting rid of fullstop elif line[:8] == "In state": inside_state, = scanf("In state %s", line) inside_state = inside_state[:-1] # getting rid of semicolon states[inside_state] = {} elif line[:1] == "\n": inside_state = None current_value = None value_to_write = None direction_to_move = None next_state = None elif line[2:25] == "If the current value is": current_value, = scanf(" If the current value is %d:\n", line) states[inside_state][current_value] = {} elif line[6:21] == "Write the value": value_to_write, = scanf(" - Write the value %d.\n", line) states[inside_state][current_value]["value_to_write"] = value_to_write elif line[6:26] == "Move one slot to the": direction_to_move, = scanf(" - Move one slot to the %s", line) direction_to_move = direction_to_move[:-1] # getting rid of fullstop states[inside_state][current_value]["direction_to_move"] = (lambda x: 0 if x=="left" else (1 if x=="right" else None))(direction_to_move) elif line[6:25] == "Continue with state": next_state, = scanf(" - Continue with state %s", line) next_state = next_state[:-1] # getting rid of the fullstop states[inside_state][current_value]["next_state"] = next_state elif line[:35] == "Perform a diagnostic checksum after": total_steps, = scanf("Perform a diagnostic checksum after %d steps.\n", line) return (states, current_state, total_steps) tape = {} cursor = 0 states, current_state, total_steps = read_blueprint("C:/Users/Dheeraj/Desktop/input25.txt") my_current_value = None my_value_to_write = None my_direction_to_move = None my_next_state = None for step in range(total_steps): my_current_value = read(cursor, tape) my_value_to_write = states[current_state][my_current_value]["value_to_write"] my_direction_to_move = states[current_state][my_current_value]["direction_to_move"] my_next_state = states[current_state][my_current_value]["next_state"] write(cursor, tape, my_value_to_write) cursor = next_cursor_position(cursor, my_direction_to_move) current_state = my_next_state num_of_ones = 0 for key,value in tape.items(): if value == 1: num_of_ones += 1 print("Part 1: " + str(num_of_ones))