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.

22.py 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import operator
  2. from collections import defaultdict
  3. from enum import Enum
  4. class State(Enum):
  5. clean = 0,
  6. weakened = 1,
  7. infected = 2,
  8. flagged = 3
  9. def clean_cells():
  10. cells = defaultdict(lambda: State.clean)
  11. for y, line in enumerate(lines):
  12. for x, c in enumerate(line):
  13. cells[(x, y)] = State.infected if c == '#' else State.clean
  14. return cells
  15. def execute(runs, transitions):
  16. cells, location, direction, infected = clean_cells(), start, (0, -1), 0
  17. for _ in range(runs):
  18. direction = directions[cells[location]][direction]
  19. cells[location] = transitions[cells[location]]
  20. if cells[location] == State.infected:
  21. infected += 1
  22. location = tuple(map(operator.add, location, direction))
  23. return infected
  24. with open('data/22.txt') as file:
  25. lines = file.readlines()
  26. start = ((len(lines[0]) - 1) // 2, (len(lines) - 1) // 2)
  27. right = {(0, -1): (1, 0), (1, 0): (0, 1), (0, 1): (-1, 0), (-1, 0): (0, -1)}
  28. left = {v: k for k, v in right.items()}
  29. identity = {v: v for v in right.values()}
  30. reverse = {v: (-1 * v[0], -1 * v[1]) for v in right.values()}
  31. directions = {
  32. State.clean: left,
  33. State.infected: right,
  34. State.weakened: identity,
  35. State.flagged: reverse
  36. }
  37. transitions = [
  38. {
  39. # part one
  40. State.clean: State.infected,
  41. State.infected: State.clean,
  42. },
  43. {
  44. # part two
  45. State.clean: State.weakened,
  46. State.weakened: State.infected,
  47. State.infected: State.flagged,
  48. State.flagged: State.clean,
  49. }
  50. ]
  51. print(f'Part one: {execute(10000, transitions[0])}')
  52. print(f'Part two: {execute(10000000, transitions[1])}')