Skip to content

Instantly share code, notes, and snippets.

@vadim2404
Last active December 15, 2023 17:26
Show Gist options
  • Save vadim2404/cad16b583778464bc5265f02242f6d63 to your computer and use it in GitHub Desktop.
Save vadim2404/cad16b583778464bc5265f02242f6d63 to your computer and use it in GitHub Desktop.
day11_part2.py
#!/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