-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11.py
More file actions
98 lines (79 loc) · 2.24 KB
/
Copy path11.py
File metadata and controls
98 lines (79 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import sys
import pytest
from pathlib import Path
import itertools
from textwrap import dedent
def get_expanded_indexes(galaxies: list[list[str]]) -> tuple[list[int], list[int]]:
vertical = []
for i in range(len(galaxies)):
for j in range(len(galaxies[i])):
if galaxies[i][j] == "#":
break
else:
vertical.append(i)
horizontal = []
for j in range(len(galaxies[0])):
for i in range(len(galaxies)):
if galaxies[i][j] == "#":
break
else:
horizontal.append(j)
return vertical, horizontal
def get_galaxies_index(galaxies: list[list[str]]) -> list[tuple[int, int]]:
galaxies_index = []
for i in range(len(galaxies)):
for j in range(len(galaxies[i])):
if galaxies[i][j] == "#":
galaxies_index.append((i, j))
return galaxies_index
def solve(text: str, expansion=2) -> int:
galaxies = [[c for c in line] for line in text.splitlines()]
vertical, horizontal = get_expanded_indexes(galaxies)
galaxies_index = get_galaxies_index(galaxies)
total = 0
for a, b in itertools.combinations(galaxies_index, 2):
# Cherk vertically
vplus = 0
for v in vertical:
if a[0] < v < b[0] or b[0] < v < a[0]:
vplus += 1
# Check horizontally
hplus = 0
for h in horizontal:
if a[1] < h < b[1] or b[1] < h < a[1]:
hplus += 1
subtotal = (
abs(a[0] - b[0])
+ abs(a[1] - b[1])
+ (vplus * expansion)
+ (hplus * expansion)
- hplus
- vplus
)
total += subtotal
return total
if __name__ == "__main__":
p = Path(sys.argv[1])
print(solve(p.read_text()))
def test():
text = dedent(
"""
...#......
.......#..
#.........
..........
......#...
.#........
.........#
..........
.......#..
#...#.....
"""
).strip()
assert solve(text) == 374
def test_input():
p = Path("11.txt")
if not p.exists():
pytest.skip(f"{p} does not exist")
text = p.read_text()
assert solve(text) == 9509330