Browse Source

Tidy.

master
Chris Smith 6 years ago
parent
commit
dcf5a9d263
1 changed files with 17 additions and 16 deletions
  1. 17
    16
      19.py

+ 17
- 16
19.py View File

@@ -1,35 +1,36 @@
1 1
 import operator
2 2
 
3 3
 
4
-def junction_routes(maze, pos):
5
-    dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
6
-    for dir in dirs:
7
-        new_pos = tuple(map(operator.add, pos, dir))
4
+def junction_route(maze, pos, ignore_heading):
5
+    headings = [(-1, 0), (1, 0), (0, -1), (0, 1)]
6
+    headings.remove(ignore_heading)
7
+    for heading in headings:
8
+        new_pos = tuple(map(operator.add, pos, heading))
8 9
         try:
9
-            cell = maze[new_pos[1]][new_pos[0]]
10
+            cell = maze[new_pos]
10 11
             if cell.isalpha() or cell in ['|', '-', '+']:
11
-                yield dir
12
-        except:
13
-            # Out of bounds
12
+                return heading
13
+        except (IndexError, KeyError):  # Out of bounds
14 14
             pass
15 15
 
16 16
 
17
-with open('data/19.txt', 'r') as file:
18
-    maze = file.readlines()
19
-    p, d, h, cell = (maze[0].index('|'), 0), (0, 1), [], '|'
17
+with open('data/19.txt') as file:
18
+    lines = file.readlines()
19
+    pos, heading, letters, cell = (lines[0].index('|'), 0), (0, 1), '', '|'
20
+    maze = dict(((x, y), v) for y, line in enumerate(lines) for x, v in enumerate(line))
20 21
 
21 22
     # Steps doesn't include the starting step, but does include an extra step at the end
22 23
     # where we step into whitespace, so balances out.
23 24
     steps = 0
24 25
 
25 26
     while cell != ' ':
26
-        p = tuple(map(operator.add, p, d))
27
-        cell = maze[p[1]][p[0]]
27
+        pos = tuple(map(operator.add, pos, heading))
28
+        cell = maze[pos]
28 29
         steps += 1
29 30
         if cell == '+':
30
-            d = next(o for o in junction_routes(maze, p) if o != (-d[0], -d[1]))
31
+            heading = junction_route(maze, pos, (-heading[0], -heading[1]))
31 32
         elif cell.isalpha():
32
-            h.append(cell)
33
+            letters += cell
33 34
 
34
-    print(f'Part one: {"".join(h)}')
35
+    print(f'Part one: {letters}')
35 36
     print(f'Part two: {steps}')

Loading…
Cancel
Save