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.

15.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/python3
  2. """Solution for day 15 of Advent of Code 2016.
  3. To simplify a lot of the logic in this solution, disc positions are offset according to their position. So if we have
  4. discs that start at positions [0, 1, 2] at t=0, when calculating positions the entry for t=0 will read [1, 3, 5]
  5. because the first disc will have moved one position before the capsule reaches it, the second disc two positions,
  6. and so on.
  7. Offsetting the positions means that a successful solution is represented as [0, 0, 0] instead of [n, n-1, n-2] etc.
  8. The latter case becomes particularly ugly when you consider that the discs may wrap around at different places.
  9. """
  10. import itertools
  11. import re
  12. input_matcher = re.compile(r'^Disc #(.*?) has (.*?) positions; at time=0, it is at position (.*?)\.$')
  13. # Returns a generator for positions that this disc will be at when the capsule arrives. e.g. if disc 3 starts at
  14. # position 0 at time 0, the first returned position will be 3 (because the disc will have ticked around three times
  15. # before a capsule released at t=0 arrives).
  16. positions = lambda disc: ((disc[0] + disc[2] + i) % disc[1] for i in itertools.count())
  17. def run(lines):
  18. # Pull the information out from the text line, making sure we treat numbers as ints.
  19. discs = map(lambda line: tuple(map(int, input_matcher.match(line).groups())), map(str.strip, lines))
  20. # Zip together the positions of each disc. That means the first element in combos will show the positions each
  21. # disc will be at when the capsule arrives if it's released at t=0; the second element will be the positions for
  22. # a capsule released at t=1, etc.
  23. combos = zip(*map(positions, discs))
  24. # Find a time when all discs will be at position 0 for the arrival of the capsule.
  25. times = (i for i, c in enumerate(combos) if not(sum(c)))
  26. return next(times)
  27. with open('data/15.txt', 'r') as file:
  28. lines = file.readlines()
  29. print("Step 1: %s" % run(lines))
  30. print("Step 2: %s" % run(lines + ['Disc #7 has 11 positions; at time=0, it is at position 0.']))