소스 검색

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

Loading…
취소
저장