|
@@ -5,30 +5,22 @@
|
5
|
5
|
Each line of the maze is represented as a list of booleans, with True for safe spaces and False for traps.
|
6
|
6
|
|
7
|
7
|
The four separate trap rules can be simplified to just "left is different to right", which is handled in the line
|
8
|
|
-method (with some annoying fudging to handle the first and last elements whose parents are 'walls').
|
|
8
|
+lambda (with some annoying fudging to handle the first and last elements whose parents are 'walls').
|
9
|
9
|
|
10
|
10
|
The solution is obtained by repeatedly generating lines and summing them (Python booleans are a subclass of ints,
|
11
|
11
|
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
|
12
|
|
-recent line is kept, everything else is discarded once counted.
|
|
12
|
+recent line is kept, everything else is discarded once counted. This is implemented using a call to functools.reduce,
|
|
13
|
+passing along a tuple of (line, sum). In each round, the line is mutated to its new form, and the sum of safe spaces
|
|
14
|
+is added to the running total.
|
13
|
15
|
"""
|
14
|
16
|
|
|
17
|
+import functools
|
|
18
|
+
|
15
|
19
|
seed = [x == '.' for x in
|
16
|
20
|
'^^.^..^.....^..^..^^...^^.^....^^^.^.^^....^.^^^...^^^^.^^^^.^..^^^^.^^.^.^.^.^.^^...^^..^^^..^.^^^^']
|
17
|
21
|
|
|
22
|
+line = lambda p: [(i == 0 or p[i - 1]) == (i == len(p) - 1 or p[i + 1]) for i in range(len(p))]
|
|
23
|
+calc = lambda n: functools.reduce(lambda x, y: (line(x[0]), x[1] + sum(line(x[0]))), range(n - 1), (seed, sum(seed)))[1]
|
18
|
24
|
|
19
|
|
-def line(previous):
|
20
|
|
- return [(i == 0 or previous[i - 1]) == (i == len(previous) - 1 or previous[i + 1]) for i in range(len(previous))]
|
21
|
|
-
|
22
|
|
-
|
23
|
|
-def calculate(num):
|
24
|
|
- last_line = seed
|
25
|
|
- safe_spaces = sum(last_line)
|
26
|
|
- lines = 1
|
27
|
|
- while lines < num:
|
28
|
|
- last_line = line(last_line)
|
29
|
|
- safe_spaces += sum(last_line)
|
30
|
|
- lines += 1
|
31
|
|
- return safe_spaces
|
32
|
|
-
|
33
|
|
-print('Part one: %s' % calculate(40))
|
34
|
|
-print('Part two: %s' % calculate(400000))
|
|
25
|
+print('Part one: %s' % calc(40))
|
|
26
|
+print('Part two: %s' % calc(400000))
|