Procházet zdrojové kódy

Further optimise day 14.

Flatten the grid into a single string (separated by line-feeds to
side-step wrap-around problems) and use the offset in the string
to identify cells instead of (x, y) tuples.

Don't calculate part one separately, just do it as we go.
master
Chris Smith před 6 roky
rodič
revize
f01f792a19
1 změnil soubory, kde provedl 7 přidání a 6 odebrání
  1. 7
    6
      14.py

+ 7
- 6
14.py Zobrazit soubor

@@ -2,12 +2,13 @@ from shared import knot_hash, add_connected_components
2 2
 
3 3
 with open('data/14.txt', 'r') as file:
4 4
     seed = file.readline().strip()
5
-    grid = [bin(int(knot_hash(f'{seed}-{i}'), 16))[2:].zfill(128) for i in range(128)]
6
-    print(f'Part one: {sum(row.count("1") for row in grid)}')
5
+    grid = '\n'.join([bin(int(knot_hash(f'{seed}-{i}'), 16))[2:].zfill(128) for i in range(128)])
7 6
 
7
+    count = 0
8 8
     regions = []
9
-    for y, row in enumerate(grid):
10
-        for x, cell in enumerate(row):
11
-            if cell == '1':
12
-                add_connected_components(regions, [(x-1, y), (x, y-1)], {(x, y)})
9
+    for offset, cell in enumerate(grid):
10
+        if cell == '1':
11
+            count += 1
12
+            add_connected_components(regions, [offset-1, offset-129], {offset})
13
+    print(f'Part one: {count}')
13 14
     print(f'Part two: {len(regions)}')

Načítá se…
Zrušit
Uložit