Skip to content

Commit

Permalink
Day 11 and init day improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Ted Cassirer committed Jan 3, 2024
1 parent 5a42d03 commit 7c5efb3
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 1 deletion.
64 changes: 64 additions & 0 deletions aoc_cas/aoc2023/day11.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
Coordinate = tuple[int, int]


def get_galaxy_coords(data: str) -> list[Coordinate]:
coords = []
for y, row in enumerate(data.splitlines()):
for x, v in enumerate(row):
if v == "#":
coords.append((y, x))
return coords


def calculate_expanded_distance(coords: list[Coordinate]) -> int:
distance = 0
seen_galaxies = 0
remaining_galaxies = len(coords)
by_y = sorted(c[0] for c in coords)
prev = 0
for y in by_y:
if y - 1 > prev:
distance += (y - 1 - prev) * (seen_galaxies * remaining_galaxies)
seen_galaxies += 1
remaining_galaxies -= 1
prev = y

seen_galaxies = 0
remaining_galaxies = len(coords)
by_x = sorted(c[1] for c in coords)
prev = 0
for x in by_x:
if x - 1 > prev:
distance += (x - 1 - prev) * (seen_galaxies * remaining_galaxies)
seen_galaxies += 1
remaining_galaxies -= 1
prev = x

return distance


def total_distance(coords: list[Coordinate]) -> int:
total = 0
for i, c1 in enumerate(coords):
for c2 in coords[i + 1 :]:
total += abs(c2[0] - c1[0]) + abs(c2[1] - c1[1])

return total


def part_a(data: str) -> int:
coords = get_galaxy_coords(data)
distance = total_distance(coords)
return distance + calculate_expanded_distance(coords)


def part_b(data: str, expansion: int = 1000000) -> int:
coords = get_galaxy_coords(data)
distance = total_distance(coords)
return distance + calculate_expanded_distance(coords) * (expansion - 1)


if __name__ == "__main__":
from aoc_cas.util import solve_with_examples

solve_with_examples(year=2023, day=11)
11 changes: 10 additions & 1 deletion aoc_cas/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,13 @@ def init_challenge(year: int, day: int) -> None:

test_folder = Path.cwd() / f"tests/fixtures/{year}"
test_folder.mkdir(exist_ok=True)
test_folder.joinpath(f"{day}.txt").touch()

fixtures = []
puzzle = Puzzle(year, day)
for example in puzzle.examples:
data = example.input_data
ans_a = example.answer_a if example.answer_a is not None else "-"
ans_b = example.answer_b if example.answer_b is not None else "-"
fixtures.append(f"{data}\n{ans_a}\n{ans_b}")
with open(test_folder.joinpath(f"{day}.txt"), "w") as fixture:
fixture.write("\n===\n".join(fixtures))
12 changes: 12 additions & 0 deletions tests/fixtures/2023/11.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
...#......
.......#..
#.........
..........
......#...
.#........
.........#
..........
.......#..
#...#.....
374
82000210

0 comments on commit 7c5efb3

Please sign in to comment.