ソースを参照

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 6年前
コミット
f01f792a19
1個のファイルの変更7行の追加6行の削除
  1. 7
    6
      14.py

+ 7
- 6
14.py ファイルの表示

@@ -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)}')

読み込み中…
キャンセル
保存