Last active
December 15, 2023 17:26
-
-
Save vadim2404/cad16b583778464bc5265f02242f6d63 to your computer and use it in GitHub Desktop.
day11_part2.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
def build_map() -> list[list[str]]: | |
with open("input.txt") as f: | |
rows = [] | |
for line in f: | |
line = list(line.strip()) | |
elems = set(line) | |
if len(elems) == 1 and '.' in elems: | |
rows.append(['*'] * len(line)) | |
else: | |
rows.append(line) | |
for j in range(len(rows[0])): | |
only_dots = True | |
for i in range(len(rows)): | |
if not rows[i][j] in {'.', '*', }: | |
only_dots = False | |
if only_dots: | |
for i in range(len(rows)): | |
rows[i][j] = '*' | |
return rows | |
def find_galaxies(map: list[list[str]]) -> list[tuple[int, int]]: | |
return [(i, j) for i, row in enumerate(map) for j, ch in enumerate(row) if ch == '#'] | |
def sum_of_distances(galaxies: list[tuple[int, int]], map: list[list[str]]) -> int: | |
ans = 0 | |
for i, (x1, y1) in enumerate(galaxies[:-1]): | |
for j, (x2, y2) in enumerate(galaxies[i + 1:], start=i + 1): | |
current = 0 | |
for i in range(min(x1, x2), max(x1, x2)): | |
current += 1000000 if map[i][y1] == '*' else 1 | |
for j in range(min(y1, y2), max(y1, y2)): | |
current += 1000000 if map[x1][j] == '*' else 1 | |
ans += current | |
return ans | |
map = build_map() | |
galaxies = find_galaxies(map) | |
print(sum_of_distances(galaxies, map)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment