Solutions to Advent of Code 2017 https://adventofcode.com/2017/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

25.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import re
  2. from collections import defaultdict
  3. VALUE = 0
  4. MOVE = 1
  5. STATE = 2
  6. def parse():
  7. begin_state = re.compile(r'Begin in state (.*?)\.')
  8. checksum_steps = re.compile(r'Perform a diagnostic checksum after ([0-9]+) steps\.')
  9. state_header = re.compile(r'In state (.*?):')
  10. value_header = re.compile(r'If the current value is ([01]):')
  11. value_action = re.compile(r'- Write the value ([01])\.')
  12. move_action = re.compile(r'- Move one slot to the (right|left)\.')
  13. state_action = re.compile(r'- Continue with state (.*?)\.')
  14. initial_state = checksum = None
  15. transitions = defaultdict(lambda: [[None]*3, [None]*3])
  16. cur_state = None
  17. cur_value = None
  18. with open('data/25.txt') as file:
  19. for line in file.readlines():
  20. line = line.strip()
  21. if len(line) == 0:
  22. continue
  23. if initial_state is None:
  24. initial_state = begin_state.match(line).group(1)
  25. elif checksum is None:
  26. checksum = int(checksum_steps.match(line).group(1))
  27. elif cur_state is None:
  28. cur_state = state_header.match(line).group(1)
  29. elif cur_value is None:
  30. cur_value = int(value_header.match(line).group(1))
  31. elif transitions[cur_state][cur_value][VALUE] is None:
  32. transitions[cur_state][cur_value][VALUE] = int(value_action.match(line).group(1))
  33. elif transitions[cur_state][cur_value][MOVE] is None:
  34. transitions[cur_state][cur_value][MOVE] = move_action.match(line).group(1)
  35. elif transitions[cur_state][cur_value][STATE] is None:
  36. transitions[cur_state][cur_value][STATE] = state_action.match(line).group(1)
  37. if cur_value == 1:
  38. cur_state = None
  39. cur_value = None
  40. return initial_state, checksum, dict(transitions)
  41. def execute(state, rounds, transitions):
  42. tape = defaultdict(lambda: 0)
  43. head = 0
  44. for _ in range(rounds):
  45. instr = transitions[state][tape[head]]
  46. tape[head] = instr[VALUE]
  47. head += 1 if instr[MOVE] == 'right' else -1
  48. state = instr[STATE]
  49. return sum(v for v in tape.values() if v == 1)
  50. state, target, transitions = parse()
  51. print(execute(state, target, transitions))