浏览代码

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

正在加载...
取消
保存