solution.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/python3
  2. import sys
  3. import re
  4. import math
  5. def part1():
  6. print('part 1')
  7. sequence = [0 if c == 'L' else 1 for c in sys.stdin.readline().strip()]
  8. sequence_position = 0
  9. sys.stdin.readline()
  10. instructions = {}
  11. for line in sys.stdin:
  12. instruction = re.findall(r'[A-Z]+', line.strip())
  13. instructions[instruction[0]] = (instruction[1], instruction[2])
  14. position = 'AAA'
  15. steps = 0
  16. while position != 'ZZZ':
  17. target = instructions[position][sequence[sequence_position]]
  18. print(position, 'goes to', target, sequence_position)
  19. position = target
  20. sequence_position = (sequence_position + 1) % len(sequence)
  21. steps += 1
  22. print(f'took {steps} steps')
  23. def part2():
  24. print('part 2')
  25. sequence = [0 if c == 'L' else 1 for c in sys.stdin.readline().strip()]
  26. sequence_position = 0
  27. sys.stdin.readline()
  28. instructions = {}
  29. positions = []
  30. for line in sys.stdin:
  31. instruction = re.findall(r'[0-9A-Z]+', line.strip())
  32. instructions[instruction[0]] = (instruction[1], instruction[2])
  33. if 'A' in instruction[0]:
  34. positions.append(instruction[0])
  35. steps = []
  36. lcm = 1
  37. for position in positions:
  38. local_steps = 0
  39. while position[-1] != 'Z':
  40. target = instructions[position][sequence[sequence_position]]
  41. print(position, 'goes to', target, sequence_position)
  42. position = target
  43. sequence_position = (sequence_position + 1) % len(sequence)
  44. local_steps += 1
  45. steps.append(local_steps)
  46. lcm = math.lcm(lcm, local_steps)
  47. print(f'took {steps} steps')
  48. print(f'first meeting point at {lcm} steps')
  49. if sys.argv[1] in '1':
  50. part1()
  51. else:
  52. part2()