Day 11 - Advent of Code 2023

Working solutions for the day 11 puzzles.

Part One

""" day_11_01.py """

# usage: python3 day_11_01.py < input

import sys
from itertools import combinations


image = []
width, height = 0, 0
for i in sys.stdin:
    image.extend(i.rstrip())
    height += 1

width = height

rows = [i for i in range(height)
        if image[i * width:(i + 1) * width] == width * ['.']]

cols = [i for i in range(width)
        if [image[i + j * width] for j in range(height)] == width * ['.']]

new_image = []
for i in range(height):
    new_image.extend(image[i * width: (i + 1) * width])
    if i in rows:
        new_image.extend(width * '.')
height += len(rows)
image = new_image

new_image = []
for i, j in enumerate(image):
    new_image.append(j)
    if i % width in cols:
        new_image.append('.')
width += len(cols)
image = new_image

galaxies = [divmod(i, width) for i, j in enumerate(image) if j == '#']

answer = 0
for x, y in combinations(galaxies, 2):
    answer += abs(x[0] - y[0]) + abs(x[1] - y[1])

print(answer)

Part Two

""" day_11_02.py """

# usage: python3 day_11_02.py < input

import sys
from itertools import combinations

scale = 1000000

image = []
width, height = 0, 0
for i in sys.stdin:
    image.extend(i.rstrip())
    height += 1

width = height

galaxies = [divmod(i, width) for i, j in enumerate(image) if j == '#']

rows = [i for i in range(height)
        if image[i * width:(i + 1) * width] == width * ['.']]

cols = [i for i in range(width)
        if [image[i + j * width] for j in range(height)] == width * ['.']]

for i in reversed(rows):
    galaxies = [(x, y) if x < i else (scale - 1 + x, y) for x, y in galaxies]

for i in reversed(cols):
    galaxies = [(x, y) if y < i else (x, scale - 1 + y) for x, y in galaxies]

answer = 0
for x, y in combinations(galaxies, 2):
    answer += abs(x[0] - y[0]) + abs(x[1] - y[1])

print(answer)