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.

18.py 1.3KB

1234567891011121314151617181920212223242526
  1. #!/usr/bin/python3
  2. """Solution for day 18 of Advent of Code 2016.
  3. Each line of the maze is represented as a list of booleans, with True for safe spaces and False for traps.
  4. The four separate trap rules can be simplified to just "left is different to right", which is handled in the line
  5. lambda (with some annoying fudging to handle the first and last elements whose parents are 'walls').
  6. The solution is obtained by repeatedly generating lines and summing them (Python booleans are a subclass of ints,
  7. with True being equal to 1 and False to 0, so a simple call to sum counts the number of safe squares). Only the most
  8. recent line is kept, everything else is discarded once counted. This is implemented using a call to functools.reduce,
  9. passing along a tuple of (line, sum). In each round, the line is mutated to its new form, and the sum of safe spaces
  10. is added to the running total.
  11. """
  12. import functools
  13. seed = [x == '.' for x in
  14. '^^.^..^.....^..^..^^...^^.^....^^^.^.^^....^.^^^...^^^^.^^^^.^..^^^^.^^.^.^.^.^.^^...^^..^^^..^.^^^^']
  15. line = lambda p: [(i == 0 or p[i - 1]) == (i == len(p) - 1 or p[i + 1]) for i in range(len(p))]
  16. calc = lambda n: functools.reduce(lambda x, y: (line(x[0]), x[1] + sum(line(x[0]))), range(n - 1), (seed, sum(seed)))[1]
  17. print('Part one: %s' % calc(40))
  18. print('Part two: %s' % calc(400000))