Advent of Code 2016 solutions https://adventofcode.com/2016/
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.

12.py 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/python3
  2. """Solution for day 12 of Advent of Code 2016.
  3. Models a simple virtual machine. Each of the four operations is defined as a method, and called using reflection.
  4. The current line number is kept in a special 'pc' (for 'program counter') register, which means that each operation is
  5. a simple mutation of a register.
  6. All values are handled by first trying to parse the input as an integer; if that fails then it is treated as a register
  7. name and the value of the register is returned. This allows any argument to be numerical or a register, not just those
  8. shown int he question example.
  9. """
  10. with open('data/12.txt', 'r') as file:
  11. instr = list(map(str.split, map(str.strip, file.readlines())))
  12. def run(values):
  13. registers = values
  14. registers['pc'] = 0
  15. def value(x):
  16. try:
  17. return int(x)
  18. except ValueError:
  19. return registers[x]
  20. def cpy(args): registers[args[1]] = value(args[0])
  21. def inc(args): registers[args[0]] += 1
  22. def dec(args): registers[args[0]] -= 1
  23. def jnz(args): registers['pc'] += 0 if value(args[0]) == 0 else value(args[1]) - 1
  24. while registers['pc'] < len(instr):
  25. locals()[instr[registers['pc']][0]](instr[registers['pc']][1:])
  26. registers['pc'] += 1
  27. return registers['a']
  28. print("Stage 1: %s" % run({'a': 0, 'b': 0, 'c': 0, 'd': 0}))
  29. print("Stage 2: %s" % run({'a': 0, 'b': 0, 'c': 1, 'd': 0}))