Compare commits
51 Commits
2023/day17
...
377e501d34
Author | SHA1 | Date | |
---|---|---|---|
|
377e501d34 | ||
|
d1f4f5bed0 | ||
|
03a950c485 | ||
|
22b1513271 | ||
|
1f5b21a13a | ||
|
8c707c00ba | ||
|
ae4f42517c | ||
|
17432f7ac6 | ||
|
664dcfe7ba | ||
|
a9bcf9ef8f | ||
|
1caf93b38b | ||
|
f9a3dee20b | ||
|
1a1ff0c64d | ||
|
d7621d09b5 | ||
|
b89d29e880 | ||
|
f1cd7e6c85 | ||
|
d16ee7f9ad | ||
0c46d3ed18 | |||
|
acb767184e | ||
|
cb0145baa2 | ||
|
a4ad0259a9 | ||
|
82452c0751 | ||
|
79cc208875 | ||
|
4dd2d5d9c9 | ||
|
def4305c1c | ||
|
3edaa249fc | ||
|
57fcb47fe9 | ||
|
cfa7718475 | ||
|
2d23e355b2 | ||
|
fab4899715 | ||
|
b6e20eefa3 | ||
|
872fd72dcd | ||
|
98f28e96f8 | ||
|
ed7aba80ad | ||
|
e507dad5e0 | ||
|
04172beb5a | ||
|
15ef67e757 | ||
|
cd0ada785c | ||
|
42bd8d6983 | ||
|
0567ab7440 | ||
|
7d2eb6b5ec | ||
|
3a9c7e728b | ||
|
d002e419c3 | ||
|
19d93e0c1d | ||
|
5c05ee5c85 | ||
|
103af21915 | ||
|
af2fbf2da1 | ||
|
c496ea25c9 | ||
|
5f8c74fd1c | ||
|
dda2be2505 | ||
|
12891194bb |
12
.drone.yml
Normal file
12
.drone.yml
Normal file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: default
|
||||
|
||||
steps:
|
||||
- name: tests
|
||||
image: python:3.10-slim
|
||||
commands:
|
||||
- pip install poetry
|
||||
- poetry install
|
||||
- poetry run poe lint
|
5
.gitignore
vendored
5
.gitignore
vendored
@@ -1 +1,6 @@
|
||||
# python / VS Code
|
||||
venv
|
||||
__pycache__
|
||||
.ruff_cache
|
||||
.vscode
|
||||
build
|
||||
|
21
2021/day7.py
21
2021/day7.py
@@ -1,21 +0,0 @@
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
positions = np.asarray([int(c) for c in sys.stdin.read().strip().split(",")])
|
||||
|
||||
min_position, max_position = positions.min(), positions.max()
|
||||
|
||||
# part 1
|
||||
answer_1 = min(
|
||||
np.sum(np.abs(positions - position))
|
||||
for position in range(min_position, max_position + 1)
|
||||
)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = min(
|
||||
np.sum(abs(positions - position) * (abs(positions - position) + 1) // 2)
|
||||
for position in range(min_position, max_position + 1)
|
||||
)
|
||||
print(f"answer 2 is {answer_2}")
|
13
2021/day9.py
13
2021/day9.py
@@ -1,13 +0,0 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# part 1
|
||||
answer_1 = ...
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = ...
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,87 +0,0 @@
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import parse
|
||||
|
||||
|
||||
def part1(sensor_to_beacon: dict[tuple[int, int], tuple[int, int]], row: int) -> int:
|
||||
no_beacons_row_l: list[np.ndarray] = []
|
||||
|
||||
for (sx, sy), (bx, by) in sensor_to_beacon.items():
|
||||
d = abs(sx - bx) + abs(sy - by) # closest
|
||||
|
||||
no_beacons_row_l.append(sx - np.arange(0, d - abs(sy - row) + 1))
|
||||
no_beacons_row_l.append(sx + np.arange(0, d - abs(sy - row) + 1))
|
||||
|
||||
beacons_at_row = set(bx for (bx, by) in sensor_to_beacon.values() if by == row)
|
||||
no_beacons_row = set(np.concatenate(no_beacons_row_l)).difference(beacons_at_row)
|
||||
|
||||
return len(no_beacons_row)
|
||||
|
||||
|
||||
def part2_intervals(
|
||||
sensor_to_beacon: dict[tuple[int, int], tuple[int, int]], xy_max: int
|
||||
) -> tuple[int, int, int]:
|
||||
from tqdm import trange
|
||||
|
||||
for y in trange(xy_max + 1):
|
||||
its: list[tuple[int, int]] = []
|
||||
for (sx, sy), (bx, by) in sensor_to_beacon.items():
|
||||
d = abs(sx - bx) + abs(sy - by)
|
||||
dx = d - abs(sy - y)
|
||||
|
||||
if dx >= 0:
|
||||
its.append((max(0, sx - dx), min(sx + dx, xy_max)))
|
||||
|
||||
its = sorted(its)
|
||||
_, e = its[0]
|
||||
|
||||
for si, ei in its[1:]:
|
||||
if si > e + 1:
|
||||
return si - 1, y, 4_000_000 * (si - 1) + y
|
||||
if ei > e:
|
||||
e = ei
|
||||
|
||||
return (0, 0, 0)
|
||||
|
||||
|
||||
def part2_cplex(
|
||||
sensor_to_beacon: dict[tuple[int, int], tuple[int, int]], xy_max: int
|
||||
) -> tuple[int, int, int]:
|
||||
from docplex.mp.model import Model
|
||||
|
||||
m = Model()
|
||||
|
||||
x, y = m.continuous_var_list(2, ub=xy_max, name=["x", "y"])
|
||||
|
||||
for (sx, sy), (bx, by) in sensor_to_beacon.items():
|
||||
d = abs(sx - bx) + abs(sy - by)
|
||||
m.add_constraint(m.abs(x - sx) + m.abs(y - sy) >= d + 1, ctname=f"ct_{sx}_{sy}")
|
||||
|
||||
m.set_objective("min", x + y)
|
||||
|
||||
s = m.solve()
|
||||
|
||||
vx = int(s.get_value(x))
|
||||
vy = int(s.get_value(y))
|
||||
return vx, vy, 4_000_000 * vx + vy
|
||||
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
sensor_to_beacon: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
|
||||
for line in lines:
|
||||
r = parse.parse(
|
||||
"Sensor at x={sx}, y={sy}: closest beacon is at x={bx}, y={by}", line
|
||||
)
|
||||
sensor_to_beacon[int(r["sx"]), int(r["sy"])] = (int(r["bx"]), int(r["by"]))
|
||||
|
||||
xy_max = 4_000_000 if max(sensor_to_beacon) > (1_000, 0) else 20
|
||||
row = 2_000_000 if max(sensor_to_beacon) > (1_000, 0) else 10
|
||||
|
||||
print(f"answer 1 is {part1(sensor_to_beacon, row)}")
|
||||
|
||||
# x, y, a2 = part2_cplex(sensor_to_beacon, xy_max)
|
||||
x, y, a2 = part2_intervals(sensor_to_beacon, xy_max)
|
||||
print(f"answer 2 is {a2} (x={x}, y={y})")
|
45
2023/day1.py
45
2023/day1.py
@@ -1,45 +0,0 @@
|
||||
import sys
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
lookups_1 = {str(d): d for d in range(1, 10)}
|
||||
lookups_2 = lookups_1 | {
|
||||
d: i + 1
|
||||
for i, d in enumerate(
|
||||
(
|
||||
"one",
|
||||
"two",
|
||||
"three",
|
||||
"four",
|
||||
"five",
|
||||
"six",
|
||||
"seven",
|
||||
"eight",
|
||||
"nine",
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def find_values(lookups: dict[str, int]) -> list[int]:
|
||||
values: list[int] = []
|
||||
|
||||
for line in filter(bool, lines):
|
||||
first_digit = min(
|
||||
lookups,
|
||||
key=lambda lookup: index
|
||||
if (index := line.find(lookup)) >= 0
|
||||
else len(line),
|
||||
)
|
||||
last_digit = max(
|
||||
lookups,
|
||||
key=lambda lookup: index if (index := line.rfind(lookup)) >= 0 else -1,
|
||||
)
|
||||
|
||||
values.append(10 * lookups[first_digit] + lookups[last_digit])
|
||||
|
||||
return values
|
||||
|
||||
|
||||
print(f"answer 1 is {sum(find_values(lookups_1))}")
|
||||
print(f"answer 2 is {sum(find_values(lookups_2))}")
|
100
2023/day10.py
100
2023/day10.py
@@ -1,100 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
from typing import Literal, cast
|
||||
|
||||
VERBOSE = os.getenv("AOC_VERBOSE") == "True"
|
||||
|
||||
Symbol = Literal["|", "-", "L", "J", "7", "F", ".", "S"]
|
||||
|
||||
lines: list[list[Symbol]] = [
|
||||
[cast(Symbol, symbol) for symbol in line] for line in sys.stdin.read().splitlines()
|
||||
]
|
||||
|
||||
# find starting point
|
||||
si, sj = next(
|
||||
(i, j)
|
||||
for i in range(len(lines))
|
||||
for j in range(len(lines[0]))
|
||||
if lines[i][j] == "S"
|
||||
)
|
||||
|
||||
# find one of the two outputs
|
||||
ni, nj = si, sj
|
||||
for ni, nj, chars in (
|
||||
(si - 1, sj, "|7F"),
|
||||
(si + 1, sj, "|LJ"),
|
||||
(si, sj - 1, "-LF"),
|
||||
(si, sj + 1, "-J7"),
|
||||
):
|
||||
if lines[ni][nj] in chars:
|
||||
break
|
||||
|
||||
# part 1 - find the loop (re-used in part 2)
|
||||
loop = [(si, sj), (ni, nj)]
|
||||
while True:
|
||||
pi, pj = loop[-2]
|
||||
i, j = loop[-1]
|
||||
|
||||
sym = lines[i][j]
|
||||
|
||||
if sym == "|" and pi > i or sym in "JL" and pi == i:
|
||||
i -= 1
|
||||
elif sym == "|" and pi < i or sym in "7F" and pi == i:
|
||||
i += 1
|
||||
elif sym == "-" and pj > j or sym in "J7" and pj == j:
|
||||
j -= 1
|
||||
elif sym == "-" and pj < j or sym in "LF" and pj == j:
|
||||
j += 1
|
||||
|
||||
if (i, j) == (si, sj):
|
||||
break
|
||||
|
||||
loop.append((i, j))
|
||||
|
||||
answer_1 = len(loop) // 2
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
|
||||
# replace S by an appropriate character for the loop below
|
||||
di1, dj1 = loop[1][0] - loop[0][0], loop[1][1] - loop[0][1]
|
||||
di2, dj2 = loop[0][0] - loop[-1][0], loop[0][1] - loop[-1][1]
|
||||
mapping: dict[tuple[int, int], dict[tuple[int, int], Symbol]] = {
|
||||
(0, 1): {(0, 1): "-", (-1, 0): "F", (1, 0): "L"},
|
||||
(0, -1): {(0, -1): "-", (-1, 0): "7", (1, 0): "J"},
|
||||
(1, 0): {(1, 0): "|", (0, 1): "7", (0, -1): "F"},
|
||||
(-1, 0): {(-1, 0): "|", (0, -1): "L", (0, 1): "J"},
|
||||
}
|
||||
lines[si][sj] = mapping[di1, dj1][di2, dj2]
|
||||
|
||||
# find the points inside the loop using an adaptation of ray casting for a discrete
|
||||
# grid (https://stackoverflow.com/a/218081/2666289)
|
||||
#
|
||||
# use a set for faster '... in loop' check
|
||||
#
|
||||
loop_s = set(loop)
|
||||
inside: set[tuple[int, int]] = set()
|
||||
for i in range(len(lines)):
|
||||
cnt = 0
|
||||
for j in range(len(lines[0])):
|
||||
if (i, j) not in loop_s and cnt % 2 == 1:
|
||||
inside.add((i, j))
|
||||
|
||||
if (i, j) in loop_s and lines[i][j] in "|LJ":
|
||||
cnt += 1
|
||||
|
||||
if VERBOSE:
|
||||
for i in range(len(lines)):
|
||||
for j in range(len(lines[0])):
|
||||
if (i, j) == (si, sj):
|
||||
print("\033[91mS\033[0m", end="")
|
||||
elif (i, j) in loop:
|
||||
print(lines[i][j], end="")
|
||||
elif (i, j) in inside:
|
||||
print("\033[92mI\033[0m", end="")
|
||||
else:
|
||||
print(".", end="")
|
||||
print()
|
||||
|
||||
answer_2 = len(inside)
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,41 +0,0 @@
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
data = np.array([[c == "#" for c in line] for line in lines])
|
||||
|
||||
rows = {c for c in range(data.shape[0]) if not data[c, :].any()}
|
||||
columns = {c for c in range(data.shape[1]) if not data[:, c].any()}
|
||||
|
||||
galaxies_y, galaxies_x = np.where(data) # type: ignore
|
||||
|
||||
|
||||
def compute_total_distance(expansion: int) -> int:
|
||||
distances: list[int] = []
|
||||
for g1 in range(len(galaxies_y)):
|
||||
x1, y1 = int(galaxies_x[g1]), int(galaxies_y[g1])
|
||||
for g2 in range(g1 + 1, len(galaxies_y)):
|
||||
x2, y2 = int(galaxies_x[g2]), int(galaxies_y[g2])
|
||||
|
||||
dx = sum(
|
||||
1 + (expansion - 1) * (x in columns)
|
||||
for x in range(min(x1, x2), max(x1, x2))
|
||||
)
|
||||
dy = sum(
|
||||
1 + (expansion - 1) * (y in rows)
|
||||
for y in range(min(y1, y2), max(y1, y2))
|
||||
)
|
||||
|
||||
distances.append(dx + dy)
|
||||
return sum(distances)
|
||||
|
||||
|
||||
# part 1
|
||||
answer_1 = compute_total_distance(2)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = compute_total_distance(1000000)
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,68 +0,0 @@
|
||||
import sys
|
||||
from typing import TypeAlias
|
||||
|
||||
RockGrid: TypeAlias = list[list[str]]
|
||||
|
||||
rocks0 = [list(line) for line in sys.stdin.read().splitlines()]
|
||||
|
||||
|
||||
def slide_rocks_top(rocks: RockGrid) -> RockGrid:
|
||||
top = [0 if c == "." else 1 for c in rocks[0]]
|
||||
for row in range(1, len(rocks)):
|
||||
for col in range(len(rocks[0])):
|
||||
match rocks[row][col]:
|
||||
case "O":
|
||||
if top[col] != row:
|
||||
rocks[top[col]][col] = "O"
|
||||
rocks[row][col] = "."
|
||||
top[col] = top[col] + 1
|
||||
case "#":
|
||||
top[col] = row + 1
|
||||
case _:
|
||||
pass
|
||||
return rocks
|
||||
|
||||
|
||||
def cycle(rocks: RockGrid) -> RockGrid:
|
||||
for _ in range(4):
|
||||
rocks = slide_rocks_top(rocks)
|
||||
rocks = [
|
||||
[rocks[len(rocks) - j - 1][i] for j in range(len(rocks))]
|
||||
for i in range(len(rocks[0]))
|
||||
]
|
||||
|
||||
return rocks
|
||||
|
||||
|
||||
rocks = slide_rocks_top([[c for c in r] for r in rocks0])
|
||||
|
||||
# part 1
|
||||
answer_1 = sum(
|
||||
(len(rocks) - i) * sum(1 for c in row if c == "O") for i, row in enumerate(rocks)
|
||||
)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
rocks = rocks0
|
||||
|
||||
N = 1000000000
|
||||
cycles: list[RockGrid] = []
|
||||
i_cycle: int = -1
|
||||
for i_cycle in range(N):
|
||||
rocks = cycle(rocks)
|
||||
|
||||
if any(rocks == c for c in cycles):
|
||||
break
|
||||
|
||||
cycles.append([[c for c in r] for r in rocks])
|
||||
|
||||
cycle_start = next(i for i in range(len(cycles)) if (rocks == cycles[i]))
|
||||
cycle_length = i_cycle - cycle_start
|
||||
|
||||
ci = cycle_start + (N - cycle_start) % cycle_length - 1
|
||||
|
||||
answer_2 = sum(
|
||||
(len(rocks) - i) * sum(1 for c in row if c == "O")
|
||||
for i, row in enumerate(cycles[ci])
|
||||
)
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,31 +0,0 @@
|
||||
import sys
|
||||
from functools import reduce
|
||||
|
||||
steps = sys.stdin.read().strip().split(",")
|
||||
|
||||
|
||||
def _hash(s: str) -> int:
|
||||
return reduce(lambda v, u: ((v + ord(u)) * 17) % 256, s, 0)
|
||||
|
||||
|
||||
# part 1
|
||||
answer_1 = sum(map(_hash, steps))
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
boxes: list[dict[str, int]] = [{} for _ in range(256)]
|
||||
|
||||
for step in steps:
|
||||
if (i := step.find("=")) >= 0:
|
||||
label, length = step[:i], int(step[i + 1 :])
|
||||
boxes[_hash(label)][label] = length
|
||||
else:
|
||||
label = step[:-1]
|
||||
boxes[_hash(label)].pop(label, None)
|
||||
|
||||
answer_2 = sum(
|
||||
i_box * i_lens * length
|
||||
for i_box, box in enumerate(boxes, start=1)
|
||||
for i_lens, length in enumerate(box.values(), start=1)
|
||||
)
|
||||
print(f"answer 2 is {answer_2}")
|
214
2023/day17.py
214
2023/day17.py
@@ -1,214 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal, TypeAlias
|
||||
|
||||
VERBOSE = os.getenv("AOC_VERBOSE") == "True"
|
||||
|
||||
Direction: TypeAlias = Literal[">", "<", "^", "v"]
|
||||
|
||||
|
||||
@dataclass(frozen=True, order=True)
|
||||
class Label:
|
||||
row: int
|
||||
col: int
|
||||
|
||||
direction: Direction
|
||||
|
||||
parent: Label | None = None
|
||||
|
||||
|
||||
# mappings from direction to row shift / col shift / opposite direction
|
||||
MAPPINGS: dict[Direction, tuple[int, int, Direction]] = {
|
||||
">": (0, +1, "<"),
|
||||
"<": (0, -1, ">"),
|
||||
"v": (+1, 0, "^"),
|
||||
"^": (-1, 0, "v"),
|
||||
}
|
||||
|
||||
|
||||
def print_shortest_path(
|
||||
grid: list[list[int]],
|
||||
target: tuple[int, int],
|
||||
per_cell: dict[tuple[int, int], list[tuple[Label, int]]],
|
||||
):
|
||||
assert len(per_cell[target]) == 1
|
||||
label = per_cell[target][0][0]
|
||||
|
||||
path: list[Label] = []
|
||||
while True:
|
||||
path.insert(0, label)
|
||||
if label.parent is None:
|
||||
break
|
||||
label = label.parent
|
||||
|
||||
p_grid = [[str(c) for c in r] for r in grid]
|
||||
|
||||
for i in range(len(grid)):
|
||||
for j in range(len(grid[0])):
|
||||
if per_cell[i, j]:
|
||||
p_grid[i][j] = f"\033[94m{grid[i][j]}\033[0m"
|
||||
|
||||
prev_label = path[0]
|
||||
for label in path[1:]:
|
||||
for r in range(
|
||||
min(prev_label.row, label.row), max(prev_label.row, label.row) + 1
|
||||
):
|
||||
for c in range(
|
||||
min(prev_label.col, label.col),
|
||||
max(prev_label.col, label.col) + 1,
|
||||
):
|
||||
if (r, c) != (prev_label.row, prev_label.col):
|
||||
p_grid[r][c] = f"\033[93m{grid[r][c]}\033[0m"
|
||||
|
||||
p_grid[label.row][label.col] = f"\033[91m{grid[label.row][label.col]}\033[0m"
|
||||
|
||||
prev_label = label
|
||||
|
||||
p_grid[0][0] = f"\033[92m{grid[0][0]}\033[0m"
|
||||
|
||||
print("\n".join("".join(row) for row in p_grid))
|
||||
|
||||
|
||||
def shortest_many_paths(grid: list[list[int]]) -> dict[tuple[int, int], int]:
|
||||
n_rows, n_cols = len(grid), len(grid[0])
|
||||
|
||||
visited: dict[tuple[int, int], tuple[Label, int]] = {}
|
||||
|
||||
queue: list[tuple[int, Label]] = [
|
||||
(0, Label(row=n_rows - 1, col=n_cols - 1, direction="^"))
|
||||
]
|
||||
|
||||
while queue and len(visited) != n_rows * n_cols:
|
||||
distance, label = heapq.heappop(queue)
|
||||
|
||||
if (label.row, label.col) in visited:
|
||||
continue
|
||||
|
||||
visited[label.row, label.col] = (label, distance)
|
||||
|
||||
for direction, (c_row, c_col, i_direction) in MAPPINGS.items():
|
||||
if label.direction == i_direction:
|
||||
continue
|
||||
else:
|
||||
row, col = (label.row + c_row, label.col + c_col)
|
||||
|
||||
# exclude labels outside the grid or with too many moves in the same
|
||||
# direction
|
||||
if row not in range(0, n_rows) or col not in range(0, n_cols):
|
||||
continue
|
||||
|
||||
heapq.heappush(
|
||||
queue,
|
||||
(
|
||||
distance
|
||||
+ sum(
|
||||
grid[r][c]
|
||||
for r in range(min(row, label.row), max(row, label.row) + 1)
|
||||
for c in range(min(col, label.col), max(col, label.col) + 1)
|
||||
)
|
||||
- grid[row][col],
|
||||
Label(
|
||||
row=row,
|
||||
col=col,
|
||||
direction=direction,
|
||||
parent=label,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
return {(r, c): visited[r, c][1] for r in range(n_rows) for c in range(n_cols)}
|
||||
|
||||
|
||||
def shortest_path(
|
||||
grid: list[list[int]],
|
||||
min_straight: int,
|
||||
max_straight: int,
|
||||
lower_bounds: dict[tuple[int, int], int],
|
||||
) -> int:
|
||||
n_rows, n_cols = len(grid), len(grid[0])
|
||||
|
||||
target = (len(grid) - 1, len(grid[0]) - 1)
|
||||
|
||||
# for each tuple (row, col, direction, count), the associated label when visited
|
||||
visited: dict[tuple[int, int, Direction], Label] = {}
|
||||
|
||||
# list of all visited labels for a cell (with associated distance)
|
||||
per_cell: dict[tuple[int, int], list[tuple[Label, int]]] = defaultdict(list)
|
||||
|
||||
# need to add two start labels, otherwise one of the two possible direction will
|
||||
# not be possible
|
||||
queue: list[tuple[int, int, Label]] = [
|
||||
(lower_bounds[0, 0], 0, Label(row=0, col=0, direction="^")),
|
||||
(lower_bounds[0, 0], 0, Label(row=0, col=0, direction="<")),
|
||||
]
|
||||
|
||||
while queue:
|
||||
_, distance, label = heapq.heappop(queue)
|
||||
|
||||
if (label.row, label.col, label.direction) in visited:
|
||||
continue
|
||||
|
||||
visited[label.row, label.col, label.direction] = label
|
||||
per_cell[label.row, label.col].append((label, distance))
|
||||
|
||||
if (label.row, label.col) == target:
|
||||
break
|
||||
|
||||
for direction, (c_row, c_col, i_direction) in MAPPINGS.items():
|
||||
# cannot move in the opposite direction
|
||||
if label.direction == i_direction or label.direction == direction:
|
||||
continue
|
||||
|
||||
distance_to = distance
|
||||
|
||||
for amount in range(1, max_straight + 1):
|
||||
row, col = (
|
||||
label.row + amount * c_row,
|
||||
label.col + amount * c_col,
|
||||
)
|
||||
|
||||
# exclude labels outside the grid or with too many moves in the same
|
||||
# direction
|
||||
if not (0 <= row < n_rows and 0 <= col < n_cols):
|
||||
break
|
||||
|
||||
distance_to += grid[row][col]
|
||||
|
||||
if amount < min_straight:
|
||||
continue
|
||||
|
||||
heapq.heappush(
|
||||
queue,
|
||||
(
|
||||
distance_to + lower_bounds[row, col],
|
||||
distance_to,
|
||||
Label(
|
||||
row=row,
|
||||
col=col,
|
||||
direction=direction,
|
||||
parent=label,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
if VERBOSE:
|
||||
print_shortest_path(grid, target, per_cell)
|
||||
|
||||
return per_cell[target][0][1]
|
||||
|
||||
|
||||
data = [[int(c) for c in r] for r in sys.stdin.read().splitlines()]
|
||||
estimates = shortest_many_paths(data)
|
||||
|
||||
# part 1
|
||||
answer_1 = shortest_path(data, 1, 3, lower_bounds=estimates)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = shortest_path(data, 4, 10, lower_bounds=estimates)
|
||||
print(f"answer 2 is {answer_2}")
|
132
2023/day19.py
132
2023/day19.py
@@ -1,132 +0,0 @@
|
||||
import logging
|
||||
import operator
|
||||
import os
|
||||
import sys
|
||||
from math import prod
|
||||
from typing import Literal, TypeAlias, cast
|
||||
|
||||
VERBOSE = os.getenv("AOC_VERBOSE") == "True"
|
||||
|
||||
logging.basicConfig(level=logging.INFO if VERBOSE else logging.WARNING)
|
||||
|
||||
Category: TypeAlias = Literal["x", "m", "a", "s"]
|
||||
Part: TypeAlias = dict[Category, int]
|
||||
PartWithBounds: TypeAlias = dict[Category, tuple[int, int]]
|
||||
|
||||
OPERATORS = {"<": operator.lt, ">": operator.gt}
|
||||
|
||||
# None if there is no check (last entry), otherwise (category, sense, value)
|
||||
Check: TypeAlias = tuple[Category, Literal["<", ">"], int] | None
|
||||
|
||||
# workflow as a list of check, in specified order, with target
|
||||
Workflow: TypeAlias = list[tuple[Check, str]]
|
||||
|
||||
|
||||
def accept(workflows: dict[str, Workflow], part: Part) -> bool:
|
||||
workflow = "in"
|
||||
decision: bool | None = None
|
||||
|
||||
while decision is None:
|
||||
for check, target in workflows[workflow]:
|
||||
ok = check is None
|
||||
if check is not None:
|
||||
category, sense, value = check
|
||||
ok = OPERATORS[sense](part[category], value)
|
||||
|
||||
if ok:
|
||||
if target in workflows:
|
||||
workflow = target
|
||||
else:
|
||||
decision = target == "A"
|
||||
break
|
||||
|
||||
return decision
|
||||
|
||||
|
||||
def propagate(workflows: dict[str, Workflow], start: PartWithBounds) -> int:
|
||||
def transfer_or_accept(
|
||||
target: str, meta: PartWithBounds, queue: list[tuple[PartWithBounds, str]]
|
||||
) -> int:
|
||||
if target in workflows:
|
||||
logging.info(f" transfer to {target}")
|
||||
queue.append((meta, target))
|
||||
return 0
|
||||
elif target == "A":
|
||||
logging.info(" accepted")
|
||||
return prod((high - low + 1) for low, high in meta.values())
|
||||
else:
|
||||
logging.info(" rejected")
|
||||
return 0
|
||||
|
||||
accepted = 0
|
||||
queue: list[tuple[PartWithBounds, str]] = [(start, "in")]
|
||||
|
||||
while queue:
|
||||
meta, workflow = queue.pop()
|
||||
logging.info(f"{workflow}: {meta}")
|
||||
for check, target in workflows[workflow]:
|
||||
if check is None:
|
||||
accepted += transfer_or_accept(target, meta, queue)
|
||||
continue
|
||||
|
||||
category, sense, value = check
|
||||
bounds, op = meta[category], OPERATORS[sense]
|
||||
|
||||
logging.info(f" splitting {meta} into {category} {sense} {value}")
|
||||
|
||||
if not op(bounds[0], value) and not op(bounds[1], value):
|
||||
logging.info(" reject, always false")
|
||||
continue
|
||||
|
||||
if op(meta[category][0], value) and op(meta[category][1], value):
|
||||
logging.info(" accept, always true")
|
||||
accepted += transfer_or_accept(target, meta, queue)
|
||||
break
|
||||
|
||||
meta2 = meta.copy()
|
||||
if sense == "<":
|
||||
meta2[category] = (meta[category][0], value - 1)
|
||||
meta[category] = (value, meta[category][1])
|
||||
else:
|
||||
meta2[category] = (value + 1, meta[category][1])
|
||||
meta[category] = (meta[category][0], value)
|
||||
logging.info(f" split {meta2} ({target}), {meta}")
|
||||
|
||||
accepted += transfer_or_accept(target, meta2, queue)
|
||||
|
||||
return accepted
|
||||
|
||||
|
||||
workflows_s, parts_s = sys.stdin.read().strip().split("\n\n")
|
||||
|
||||
workflows: dict[str, Workflow] = {}
|
||||
for workflow_s in workflows_s.split("\n"):
|
||||
name, block_s = workflow_s.split("{")
|
||||
workflows[name] = []
|
||||
|
||||
for block in block_s[:-1].split(","):
|
||||
check: Check
|
||||
if (i := block.find(":")) >= 0:
|
||||
check, target = (
|
||||
cast(Category, block[0]),
|
||||
cast(Literal["<", ">"], block[1]),
|
||||
int(block[2:i]),
|
||||
), block[i + 1 :]
|
||||
else:
|
||||
check, target = None, block
|
||||
workflows[name].append((check, target))
|
||||
|
||||
# part 1
|
||||
parts: list[Part] = [
|
||||
{cast(Category, s[0]): int(s[2:]) for s in part_s[1:-1].split(",")}
|
||||
for part_s in parts_s.split("\n")
|
||||
]
|
||||
answer_1 = sum(sum(part.values()) for part in parts if accept(workflows, part))
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
|
||||
# part 2
|
||||
answer_2 = propagate(
|
||||
workflows, {cast(Category, c): (1, 4000) for c in ["x", "m", "a", "s"]}
|
||||
)
|
||||
print(f"answer 2 is {answer_2}")
|
43
2023/day2.py
43
2023/day2.py
@@ -1,43 +0,0 @@
|
||||
import math
|
||||
import sys
|
||||
from typing import Literal, TypeAlias, cast
|
||||
|
||||
CubeType: TypeAlias = Literal["red", "blue", "green"]
|
||||
|
||||
MAX_CUBES: dict[CubeType, int] = {"red": 12, "green": 13, "blue": 14}
|
||||
|
||||
# parse games
|
||||
lines = sys.stdin.read().splitlines()
|
||||
games: dict[int, list[dict[CubeType, int]]] = {}
|
||||
for line in filter(bool, lines):
|
||||
id_part, sets_part = line.split(":")
|
||||
|
||||
games[int(id_part.split(" ")[-1])] = [
|
||||
{
|
||||
cast(CubeType, s[1]): int(s[0])
|
||||
for cube_draw in cube_set_s.strip().split(", ")
|
||||
if (s := cube_draw.split(" "))
|
||||
}
|
||||
for cube_set_s in sets_part.strip().split(";")
|
||||
]
|
||||
|
||||
# part 1
|
||||
answer_1 = sum(
|
||||
id
|
||||
for id, set_of_cubes in games.items()
|
||||
if all(
|
||||
n_cubes <= MAX_CUBES[cube]
|
||||
for cube_set in set_of_cubes
|
||||
for cube, n_cubes in cube_set.items()
|
||||
)
|
||||
)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = sum(
|
||||
math.prod(
|
||||
max(cube_set.get(cube, 0) for cube_set in set_of_cubes) for cube in MAX_CUBES
|
||||
)
|
||||
for set_of_cubes in games.values()
|
||||
)
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,13 +0,0 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# part 1
|
||||
answer_1 = ...
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = ...
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,13 +0,0 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# part 1
|
||||
answer_1 = ...
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = ...
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,13 +0,0 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# part 1
|
||||
answer_1 = ...
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = ...
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,13 +0,0 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# part 1
|
||||
answer_1 = ...
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = ...
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,13 +0,0 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# part 1
|
||||
answer_1 = ...
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = ...
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -1,13 +0,0 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# part 1
|
||||
answer_1 = ...
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = ...
|
||||
print(f"answer 2 is {answer_2}")
|
53
2023/day3.py
53
2023/day3.py
@@ -1,53 +0,0 @@
|
||||
import string
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
NOT_A_SYMBOL = "." + string.digits
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
values: list[int] = []
|
||||
gears: dict[tuple[int, int], list[int]] = defaultdict(list)
|
||||
|
||||
for i, line in enumerate(lines):
|
||||
j = 0
|
||||
while j < len(line):
|
||||
# skip everything until a digit is found (start of a number)
|
||||
if line[j] not in string.digits:
|
||||
j += 1
|
||||
continue
|
||||
|
||||
# extract the range of the number and its value
|
||||
k = j + 1
|
||||
while k < len(line) and line[k] in string.digits:
|
||||
k += 1
|
||||
|
||||
value = int(line[j:k])
|
||||
|
||||
# lookup around the number if there is a symbol - we go through the number
|
||||
# itself but that should not matter since it only contains digits
|
||||
found = False
|
||||
for i2 in range(max(0, i - 1), min(i + 1, len(lines) - 1) + 1):
|
||||
for j2 in range(max(0, j - 1), min(k, len(line) - 1) + 1):
|
||||
assert i2 >= 0 and i2 < len(lines)
|
||||
assert j2 >= 0 and j2 < len(line)
|
||||
|
||||
if lines[i2][j2] not in NOT_A_SYMBOL:
|
||||
found = True
|
||||
|
||||
if lines[i2][j2] == "*":
|
||||
gears[i2, j2].append(value)
|
||||
|
||||
if found:
|
||||
values.append(value)
|
||||
|
||||
# continue starting from the end of the number
|
||||
j = k
|
||||
|
||||
# part 1
|
||||
answer_1 = sum(values)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = sum(v1 * v2 for v1, v2 in filter(lambda vs: len(vs) == 2, gears.values()))
|
||||
print(f"answer 2 is {answer_2}")
|
41
2023/day4.py
41
2023/day4.py
@@ -1,41 +0,0 @@
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Card:
|
||||
id: int
|
||||
numbers: list[int]
|
||||
values: list[int]
|
||||
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
cards: list[Card] = []
|
||||
for line in lines:
|
||||
id_part, e_part = line.split(":")
|
||||
numbers_s, values_s = e_part.split("|")
|
||||
cards.append(
|
||||
Card(
|
||||
id=int(id_part.split()[1]),
|
||||
numbers=[int(v.strip()) for v in numbers_s.strip().split()],
|
||||
values=[int(v.strip()) for v in values_s.strip().split()],
|
||||
)
|
||||
)
|
||||
|
||||
winnings = [sum(1 for n in card.values if n in card.numbers) for card in cards]
|
||||
|
||||
# part 1
|
||||
answer_1 = sum(2 ** (winning - 1) for winning in winnings if winning > 0)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
card2cards = {i: list(range(i + 1, i + w + 1)) for i, w in enumerate(winnings)}
|
||||
card2values = {i: 0 for i in range(len(cards))}
|
||||
|
||||
for i in range(len(cards)):
|
||||
card2values[i] += 1
|
||||
for j in card2cards[i]:
|
||||
card2values[j] += card2values[i]
|
||||
|
||||
print(f"answer 2 is {sum(card2values.values())}")
|
129
2023/day5.py
129
2023/day5.py
@@ -1,129 +0,0 @@
|
||||
import sys
|
||||
from typing import Sequence
|
||||
|
||||
MAP_ORDER = [
|
||||
"seed",
|
||||
"soil",
|
||||
"fertilizer",
|
||||
"water",
|
||||
"light",
|
||||
"temperature",
|
||||
"humidity",
|
||||
"location",
|
||||
]
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# mappings from one category to another, each list contains
|
||||
# ranges stored as (source, target, length), ordered by start and
|
||||
# completed to have no "hole"
|
||||
maps: dict[tuple[str, str], list[tuple[int, int, int]]] = {}
|
||||
|
||||
# parsing
|
||||
index = 2
|
||||
while index < len(lines):
|
||||
p1, _, p2 = lines[index].split()[0].split("-")
|
||||
|
||||
# extract the existing ranges from the file - we store as (source, target, length)
|
||||
# whereas the file is in order (target, source, length)
|
||||
index += 1
|
||||
values: list[tuple[int, int, int]] = []
|
||||
while index < len(lines) and lines[index]:
|
||||
n1, n2, n3 = lines[index].split()
|
||||
values.append((int(n2), int(n1), int(n3)))
|
||||
index += 1
|
||||
|
||||
# sort by source value
|
||||
values.sort()
|
||||
|
||||
# add a 'fake' interval starting at 0 if missing
|
||||
if values[0][0] != 0:
|
||||
values.insert(0, (0, 0, values[0][0]))
|
||||
|
||||
# fill gaps between intervals
|
||||
for i in range(len(values) - 1):
|
||||
next_start = values[i + 1][0]
|
||||
end = values[i][0] + values[i][2]
|
||||
if next_start != end:
|
||||
values.insert(
|
||||
i + 1,
|
||||
(end, end, next_start - end),
|
||||
)
|
||||
|
||||
# add an interval covering values up to at least 2**32 at the end
|
||||
last_start, _, last_length = values[-1]
|
||||
values.append((last_start + last_length, last_start + last_length, 2**32))
|
||||
|
||||
assert all(v1[0] + v1[2] == v2[0] for v1, v2 in zip(values[:-1], values[1:]))
|
||||
assert values[0][0] == 0
|
||||
assert values[-1][0] + values[-1][-1] >= 2**32
|
||||
|
||||
maps[p1, p2] = values
|
||||
index += 1
|
||||
|
||||
|
||||
def find_range(
|
||||
values: tuple[int, int], map: list[tuple[int, int, int]]
|
||||
) -> list[tuple[int, int]]:
|
||||
"""
|
||||
Given an input range, use the given mapping to find the corresponding list of
|
||||
ranges in the target domain.
|
||||
"""
|
||||
r_start, r_length = values
|
||||
ranges: list[tuple[int, int]] = []
|
||||
|
||||
# find index of the first and last intervals in map that overlaps the input
|
||||
# interval
|
||||
index_start, index_end = -1, -1
|
||||
|
||||
for index_start, (start, _, length) in enumerate(map):
|
||||
if start <= r_start and start + length > r_start:
|
||||
break
|
||||
|
||||
for index_end, (start, _, length) in enumerate(
|
||||
map[index_start:], start=index_start
|
||||
):
|
||||
if r_start + r_length >= start and r_start + r_length < start + length:
|
||||
break
|
||||
|
||||
assert index_start >= 0 and index_end >= 0
|
||||
|
||||
# special case if one interval contains everything
|
||||
if index_start == index_end:
|
||||
start, target, length = map[index_start]
|
||||
ranges.append((target + r_start - start, r_length))
|
||||
else:
|
||||
# add the start interval part
|
||||
start, target, length = map[index_start]
|
||||
ranges.append((target + r_start - start, start + length - r_start))
|
||||
|
||||
# add all intervals between the first and last (excluding both)
|
||||
index = index_start + 1
|
||||
while index < index_end:
|
||||
start, target, length = map[index]
|
||||
ranges.append((target, length))
|
||||
index += 1
|
||||
|
||||
# add the last interval
|
||||
start, target, length = map[index_end]
|
||||
ranges.append((target, r_start + r_length - start))
|
||||
|
||||
return ranges
|
||||
|
||||
|
||||
def find_location_ranges(seeds: Sequence[tuple[int, int]]) -> Sequence[tuple[int, int]]:
|
||||
for map1, map2 in zip(MAP_ORDER[:-1], MAP_ORDER[1:]):
|
||||
seeds = [s2 for s1 in seeds for s2 in find_range(s1, maps[map1, map2])]
|
||||
return seeds
|
||||
|
||||
|
||||
# part 1 - use find_range() with range of length 1
|
||||
seeds_p1 = [(int(s), 1) for s in lines[0].split(":")[1].strip().split()]
|
||||
answer_1 = min(start for start, _ in find_location_ranges(seeds_p1))
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# # part 2
|
||||
parts = lines[0].split(":")[1].strip().split()
|
||||
seeds_p2 = [(int(s), int(e)) for s, e in zip(parts[::2], parts[1::2])]
|
||||
answer_2 = min(start for start, _ in find_location_ranges(seeds_p2))
|
||||
print(f"answer 2 is {answer_2}")
|
47
2023/day6.py
47
2023/day6.py
@@ -1,47 +0,0 @@
|
||||
import math
|
||||
import sys
|
||||
|
||||
|
||||
def extreme_times_to_beat(time: int, distance: int) -> tuple[int, int]:
|
||||
# formula (T = total time, D = target distance)
|
||||
# - speed(t) = t,
|
||||
# - distance(t) = (T - t) * speed(t)
|
||||
# - distance(t) > D
|
||||
# <=> (T - t) * t > D
|
||||
# <=> -t^2 + T * t - D >= 0
|
||||
|
||||
a, b, c = -1, time, -distance
|
||||
d = b * b - 4 * a * c
|
||||
|
||||
t1 = math.ceil(-(b - math.sqrt(d)) / (2 * a))
|
||||
t2 = math.floor(-(b + math.sqrt(d)) / (2 * a))
|
||||
|
||||
if (time - t1) * t1 == distance:
|
||||
t1 += 1
|
||||
|
||||
if (time - t2) * t2 == distance:
|
||||
t2 -= 1
|
||||
|
||||
return t1, t2
|
||||
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
# part 1
|
||||
times = list(map(int, lines[0].split()[1:]))
|
||||
distances = list(map(int, lines[1].split()[1:]))
|
||||
answer_1 = math.prod(
|
||||
t2 - t1 + 1
|
||||
for t1, t2 in (
|
||||
extreme_times_to_beat(time, distance)
|
||||
for time, distance in zip(times, distances)
|
||||
)
|
||||
)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
time = int(lines[0].split(":")[1].strip().replace(" ", ""))
|
||||
distance = int(lines[1].split(":")[1].strip().replace(" ", ""))
|
||||
t1, t2 = extreme_times_to_beat(time, distance)
|
||||
answer_2 = t2 - t1 + 1
|
||||
print(f"answer 2 is {answer_2}")
|
29
2023/day8.py
29
2023/day8.py
@@ -1,29 +0,0 @@
|
||||
import itertools
|
||||
import math
|
||||
import sys
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
sequence = lines[0]
|
||||
nodes = {
|
||||
p[0]: {d: n for d, n in zip("LR", p[1].strip("()").split(", "))}
|
||||
for line in lines[2:]
|
||||
if (p := line.split(" = "))
|
||||
}
|
||||
|
||||
|
||||
def path(start: str):
|
||||
path = [start]
|
||||
it_seq = iter(itertools.cycle(sequence))
|
||||
while not path[-1].endswith("Z"):
|
||||
path.append(nodes[path[-1]][next(it_seq)])
|
||||
return path
|
||||
|
||||
|
||||
# part 1
|
||||
answer_1 = len(path(next(node for node in nodes if node.endswith("A")))) - 1
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = math.lcm(*(len(path(node)) - 1 for node in nodes if node.endswith("A")))
|
||||
print(f"answer 2 is {answer_2}")
|
29
2023/day9.py
29
2023/day9.py
@@ -1,29 +0,0 @@
|
||||
import sys
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
data = [[int(c) for c in line.split()] for line in lines]
|
||||
|
||||
right_values: list[int] = []
|
||||
left_values: list[int] = []
|
||||
for values in data:
|
||||
diffs = [values]
|
||||
while any(d != 0 for d in diffs[-1]):
|
||||
diffs.append([rhs - lhs for lhs, rhs in zip(diffs[-1][:-1], diffs[-1][1:])])
|
||||
|
||||
rhs: list[int] = [0]
|
||||
lhs: list[int] = [0]
|
||||
for cx in range(len(diffs) - 1):
|
||||
rhs.append(diffs[-cx - 2][-1] + rhs[cx])
|
||||
lhs.append(diffs[-cx - 2][0] - lhs[cx])
|
||||
|
||||
right_values.append(rhs[-1])
|
||||
left_values.append(lhs[-1])
|
||||
|
||||
# part 1
|
||||
answer_1 = sum(right_values)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = sum(left_values)
|
||||
print(f"answer 2 is {answer_2}")
|
35
README.md
35
README.md
@@ -1,7 +1,36 @@
|
||||
# Advent Of Code
|
||||
# Holt59 - Advent Of Code
|
||||
|
||||
To run any script, you need to pipe the input:
|
||||
Installation (with [`poetry`](https://python-poetry.org/)):
|
||||
|
||||
```bash
|
||||
cat 2022/inputs/day2.txt | python 2022/day2.py
|
||||
poetry install
|
||||
```
|
||||
|
||||
To run any day:
|
||||
|
||||
```bash
|
||||
holt59-aoc $day
|
||||
```
|
||||
|
||||
You can use `-v` / `--verbose` for extra outputs in some case, `-t` / `--test` to run
|
||||
the code on the test data (one of the test data if multiple are present) or even
|
||||
`-u XXX` / `--user XXX` to run the code on a specific input after putting the input
|
||||
file under `src/holt59/aoc/inputs/XXX/$year/$day`.
|
||||
|
||||
Full usage:
|
||||
|
||||
```bash
|
||||
usage: Holt59 Advent-Of-Code Runner [-h] [-v] [-t] [-u USER] [-i INPUT] [-y YEAR] day
|
||||
|
||||
positional arguments:
|
||||
day day to run
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
-v, --verbose verbose mode
|
||||
-t, --test test mode
|
||||
-u USER, --user USER user input to use
|
||||
-i INPUT, --input INPUT
|
||||
input to use (override user and test)
|
||||
-y YEAR, --year YEAR year to run
|
||||
```
|
||||
|
1298
poetry.lock
generated
Normal file
1298
poetry.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
43
pyproject.toml
Normal file
43
pyproject.toml
Normal file
@@ -0,0 +1,43 @@
|
||||
[tool.poetry]
|
||||
name = "holt59-advent-of-code"
|
||||
version = "0.1.0"
|
||||
description = ""
|
||||
authors = ["Mikael CAPELLE <capelle.mikael@gmail.com>"]
|
||||
license = "MIT"
|
||||
readme = "README.md"
|
||||
packages = [{ include = "holt59", from = "src" }]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.10"
|
||||
numpy = "^2.1.3"
|
||||
tqdm = "^4.67.1"
|
||||
parse = "^1.20.2"
|
||||
scipy = "^1.14.1"
|
||||
sympy = "^1.13.3"
|
||||
networkx = "^3.4.2"
|
||||
pandas = "^2.2.3"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
pyright = "^1.1.389"
|
||||
ruff = "^0.8.1"
|
||||
poethepoet = "^0.31.1"
|
||||
ipykernel = "^6.29.5"
|
||||
networkx-stubs = "^0.0.1"
|
||||
types-networkx = "^3.4.2.20241115"
|
||||
|
||||
[tool.poetry.scripts]
|
||||
holt59-aoc = "holt59.aoc.__main__:main"
|
||||
|
||||
[tool.poe.tasks]
|
||||
format-imports = "ruff check --select I src --fix"
|
||||
format-ruff = "ruff format src"
|
||||
format.sequence = ["format-imports", "format-ruff"]
|
||||
lint-ruff = "ruff check src"
|
||||
lint-ruff-format = "ruff format --check src"
|
||||
lint-pyright = "pyright src"
|
||||
lint.sequence = ["lint-ruff", "lint-ruff-format", "lint-pyright"]
|
||||
lint.ignore_fail = "return_non_zero"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
12
run.ps1
12
run.ps1
@@ -1,12 +0,0 @@
|
||||
param(
|
||||
[switch]$Test,
|
||||
[PSDefaultValue()]
|
||||
[Parameter(Mandatory = $false)]
|
||||
$Year = 2023,
|
||||
[Parameter(Mandatory = $true, Position = 0)]
|
||||
$Day)
|
||||
|
||||
$folder = $Test ? "tests" : "inputs"
|
||||
|
||||
$env:AOC_VERBOSE = $VerbosePreference -eq "Continue"
|
||||
Get-Content ".\$Year\$folder\day$Day.txt" | python ".\$Year\day$Day.py"
|
12
src/holt59/aoc/2015/day1.py
Normal file
12
src/holt59/aoc/2015/day1.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
floor = 0
|
||||
floors = [(floor := floor + (1 if c == "(" else -1)) for c in input]
|
||||
|
||||
yield floors[-1]
|
||||
yield floors.index(-1)
|
147
src/holt59/aoc/2015/day10.py
Normal file
147
src/holt59/aoc/2015/day10.py
Normal file
@@ -0,0 +1,147 @@
|
||||
import itertools
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
# see http://www.se16.info/js/lands2.htm for the explanation of 'atoms' (or elements)
|
||||
#
|
||||
# see also https://www.youtube.com/watch?v=ea7lJkEhytA (video link from AOC) and this
|
||||
# CodeGolf answer https://codegolf.stackexchange.com/a/8479/42148
|
||||
|
||||
# fmt: off
|
||||
ATOMS: list[tuple[str, tuple[int, ...]]] = [
|
||||
("22", (0, )), # 0
|
||||
("13112221133211322112211213322112", (71, 90, 0, 19, 2, )), # 1
|
||||
("312211322212221121123222112", (1, )), # 2
|
||||
("111312211312113221133211322112211213322112", (31, 19, 2, )), # 3
|
||||
("1321132122211322212221121123222112", (3, )), # 4
|
||||
("3113112211322112211213322112", (4, )), # 5
|
||||
("111312212221121123222112", (5, )), # 6
|
||||
("132112211213322112", (6, )), # 7
|
||||
("31121123222112", (7, )), # 8
|
||||
("111213322112", (8, )), # 9
|
||||
("123222112", (9, )), # 10
|
||||
("3113322112", (60, 10, )), # 11
|
||||
("1113222112", (11, )), # 12
|
||||
("1322112", (12, )), # 13
|
||||
("311311222112", (66, 13, )), # 14
|
||||
("1113122112", (14, )), # 15
|
||||
("132112", (15, )), # 16
|
||||
("3112", (16, )), # 17
|
||||
("1112", (17, )), # 18
|
||||
("12", (18, )), # 19
|
||||
("3113112221133112", (66, 90, 0, 19, 26, )), # 20
|
||||
("11131221131112", (20, )), # 21
|
||||
("13211312", (21, )), # 22
|
||||
("31132", (22, )), # 23
|
||||
("111311222112", (23, 13, )), # 24
|
||||
("13122112", (24, )), # 25
|
||||
("32112", (25, )), # 26
|
||||
("11133112", (29, 26, )), # 27
|
||||
("131112", (27, )), # 28
|
||||
("312", (28, )), # 29
|
||||
("13221133122211332", (62, 19, 88, 0, 19, 29, )), # 30
|
||||
("31131122211311122113222", (66, 30, )), # 31
|
||||
("11131221131211322113322112", (31, 10, )), # 32
|
||||
("13211321222113222112", (32, )), # 33
|
||||
("3113112211322112", (33, )), # 34
|
||||
("11131221222112", (34, )), # 35
|
||||
("1321122112", (35, )), # 36
|
||||
("3112112", (36, )), # 37
|
||||
("1112133", (37, 91, )), # 38
|
||||
("12322211331222113112211", (38, 0, 19, 42, )), # 39
|
||||
("1113122113322113111221131221", (67, 39, )), # 40
|
||||
("13211322211312113211", (40, )), # 41
|
||||
("311322113212221", (41, )), # 42
|
||||
("132211331222113112211", (62, 19, 42, )), # 43
|
||||
("311311222113111221131221", (66, 43, )), # 44
|
||||
("111312211312113211", (44, )), # 45
|
||||
("132113212221", (45, )), # 46
|
||||
("3113112211", (46, )), # 47
|
||||
("11131221", (47, )), # 48
|
||||
("13211", (48, )), # 49
|
||||
("3112221", (60, 49, )), # 50
|
||||
("1322113312211", (62, 19, 50, )), # 51
|
||||
("311311222113111221", (66, 51, )), # 52
|
||||
("11131221131211", (52, )), # 53
|
||||
("13211321", (53, )), # 54
|
||||
("311311", (54, )), # 55
|
||||
("11131", (55, )), # 56
|
||||
("1321133112", (56, 0, 19, 26, )), # 57
|
||||
("31131112", (57, )), # 58
|
||||
("111312", (58, )), # 59
|
||||
("132", (59, )), # 60
|
||||
("311332", (60, 19, 29, )), # 61
|
||||
("1113222", (61, )), # 62
|
||||
("13221133112", (62, 19, 26, )), # 63
|
||||
("3113112221131112", (66, 63, )), # 64
|
||||
("111312211312", (64, )), # 65
|
||||
("1321132", (65, )), # 66
|
||||
("311311222", (66, 60, )), # 67
|
||||
("11131221133112", (67, 19, 26, )), # 68
|
||||
("1321131112", (68, )), # 69
|
||||
("311312", (69, )), # 70
|
||||
("11132", (70, )), # 71
|
||||
("13112221133211322112211213322113", (71, 90, 0, 19, 73, )), # 72
|
||||
("312211322212221121123222113", (72, )), # 73
|
||||
("111312211312113221133211322112211213322113", (31, 19, 73, )), # 74
|
||||
("1321132122211322212221121123222113", (74, )), # 75
|
||||
("3113112211322112211213322113", (75, )), # 76
|
||||
("111312212221121123222113", (76, )), # 77
|
||||
("132112211213322113", (77, )), # 78
|
||||
("31121123222113", (78, )), # 79
|
||||
("111213322113", (79, )), # 80
|
||||
("123222113", (80, )), # 81
|
||||
("3113322113", (60, 81, )), # 82
|
||||
("1113222113", (82, )), # 83
|
||||
("1322113", (83, )), # 84
|
||||
("311311222113", (66, 84, )), # 85
|
||||
("1113122113", (85, )), # 86
|
||||
("132113", (86, )), # 87
|
||||
("3113", (87, )), # 88
|
||||
("1113", (88, )), # 89
|
||||
("13", (89, )), # 90
|
||||
("3", (90, )), # 91
|
||||
]
|
||||
# fmt: on
|
||||
|
||||
STARTERS = [
|
||||
"1",
|
||||
"11",
|
||||
"21",
|
||||
"1211",
|
||||
"111221",
|
||||
"312211",
|
||||
"13112221",
|
||||
"1113213211",
|
||||
"31131211131221",
|
||||
]
|
||||
|
||||
|
||||
def look_and_say_length(s: str, n: int) -> int:
|
||||
if n == 0:
|
||||
return len(s)
|
||||
|
||||
if s in STARTERS:
|
||||
return look_and_say_length(
|
||||
"".join(f"{len(list(g))}{k}" for k, g in itertools.groupby(s)), n - 1
|
||||
)
|
||||
|
||||
counts = {i: 0 for i in range(len(ATOMS))}
|
||||
idx = next(i for i, (a, _) in enumerate(ATOMS) if s == a)
|
||||
counts[idx] = 1
|
||||
|
||||
for _ in range(n):
|
||||
c2 = {i: 0 for i in range(len(ATOMS))}
|
||||
for i in counts:
|
||||
for j in ATOMS[i][1]:
|
||||
c2[j] += counts[i]
|
||||
counts = c2
|
||||
|
||||
return sum(counts[i] * len(a[0]) for i, a in enumerate(ATOMS))
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any] | None:
|
||||
yield look_and_say_length(input, 40)
|
||||
yield look_and_say_length(input, 50)
|
49
src/holt59/aoc/2015/day11.py
Normal file
49
src/holt59/aoc/2015/day11.py
Normal file
@@ -0,0 +1,49 @@
|
||||
import itertools
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
def is_valid(p: str) -> bool:
|
||||
if any(c in "iol" for c in p):
|
||||
return False
|
||||
|
||||
if not any(
|
||||
ord(a) + 1 == ord(b) and ord(b) + 1 == ord(c)
|
||||
for a, b, c in zip(p, p[1:], p[2:])
|
||||
):
|
||||
return False
|
||||
|
||||
if sum(len(list(g)) >= 2 for _, g in itertools.groupby(p)) < 2:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
assert not is_valid("hijklmmn")
|
||||
assert not is_valid("abbceffg")
|
||||
assert not is_valid("abbcegjk")
|
||||
assert is_valid("abcdffaa")
|
||||
assert is_valid("ghjaabcc")
|
||||
|
||||
|
||||
def increment(p: str) -> str:
|
||||
if p[-1] == "z":
|
||||
return increment(p[:-1]) + "a"
|
||||
elif p[-1] in "iol":
|
||||
return p[:-1] + chr(ord(p[-1]) + 2)
|
||||
else:
|
||||
return p[:-1] + chr(ord(p[-1]) + 1)
|
||||
|
||||
|
||||
def find_next_password(p: str) -> str:
|
||||
while not is_valid(p):
|
||||
p = increment(p)
|
||||
return p
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
answer_1 = find_next_password(input)
|
||||
yield answer_1
|
||||
yield find_next_password(increment(answer_1))
|
27
src/holt59/aoc/2015/day12.py
Normal file
27
src/holt59/aoc/2015/day12.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import json
|
||||
from typing import Any, Iterator, TypeAlias
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
JsonObject: TypeAlias = dict[str, "JsonObject"] | list["JsonObject"] | int | str
|
||||
|
||||
|
||||
def json_sum(value: JsonObject, ignore: str | None = None) -> int:
|
||||
if isinstance(value, str):
|
||||
return 0
|
||||
elif isinstance(value, int):
|
||||
return value
|
||||
elif isinstance(value, list):
|
||||
return sum(json_sum(v, ignore=ignore) for v in value)
|
||||
elif ignore not in value.values():
|
||||
return sum(json_sum(v, ignore=ignore) for v in value.values())
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
data: JsonObject = json.loads(input)
|
||||
|
||||
yield json_sum(data)
|
||||
yield json_sum(data, "red")
|
40
src/holt59/aoc/2015/day13.py
Normal file
40
src/holt59/aoc/2015/day13.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import itertools
|
||||
from collections import defaultdict
|
||||
from typing import Any, Iterator, Literal, cast
|
||||
|
||||
import parse # type: ignore
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
def max_change_in_happiness(happiness: dict[str, dict[str, int]]) -> int:
|
||||
guests = list(happiness)
|
||||
return max(
|
||||
sum(
|
||||
happiness[o][d] + happiness[d][o]
|
||||
for o, d in zip((guests[0],) + order, order + (guests[0],))
|
||||
)
|
||||
for order in map(tuple, itertools.permutations(guests[1:]))
|
||||
)
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
happiness: dict[str, dict[str, int]] = defaultdict(dict)
|
||||
for line in lines:
|
||||
u1, gain_or_loose, hap, u2 = cast(
|
||||
tuple[str, Literal["gain", "lose"], int, str],
|
||||
parse.parse( # type: ignore
|
||||
"{} would {} {:d} happiness units by sitting next to {}.", line
|
||||
),
|
||||
)
|
||||
happiness[u1][u2] = hap if gain_or_loose == "gain" else -hap
|
||||
|
||||
yield max_change_in_happiness(happiness)
|
||||
for guest in list(happiness):
|
||||
happiness["me"][guest] = 0
|
||||
happiness[guest]["me"] = 0
|
||||
|
||||
yield max_change_in_happiness(happiness)
|
63
src/holt59/aoc/2015/day14.py
Normal file
63
src/holt59/aoc/2015/day14.py
Normal file
@@ -0,0 +1,63 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Iterator, Literal, cast
|
||||
|
||||
import parse # type: ignore
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Reindeer:
|
||||
name: str
|
||||
speed: int
|
||||
fly_time: int
|
||||
rest_time: int
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
reindeers: list[Reindeer] = []
|
||||
for line in lines:
|
||||
reindeer, speed, speed_time, rest_time = cast(
|
||||
tuple[str, int, int, int],
|
||||
parse.parse( # type: ignore
|
||||
"{} can fly {:d} km/s for {:d} seconds, "
|
||||
"but then must rest for {:d} seconds.",
|
||||
line,
|
||||
),
|
||||
)
|
||||
reindeers.append(
|
||||
Reindeer(
|
||||
name=reindeer, speed=speed, fly_time=speed_time, rest_time=rest_time
|
||||
)
|
||||
)
|
||||
|
||||
target = 1000 if len(reindeers) <= 2 else 2503
|
||||
|
||||
states: dict[Reindeer, tuple[Literal["resting", "flying"], int]] = {
|
||||
reindeer: ("resting", 0) for reindeer in reindeers
|
||||
}
|
||||
distances: dict[Reindeer, int] = {reindeer: 0 for reindeer in reindeers}
|
||||
points: dict[Reindeer, int] = {reindeer: 0 for reindeer in reindeers}
|
||||
|
||||
for time in self.progress.wrap(range(target)):
|
||||
for reindeer in reindeers:
|
||||
if states[reindeer][0] == "flying":
|
||||
distances[reindeer] += reindeer.speed
|
||||
|
||||
top_distance = max(distances.values())
|
||||
for reindeer in reindeers:
|
||||
if distances[reindeer] == top_distance:
|
||||
points[reindeer] += 1
|
||||
|
||||
for reindeer in reindeers:
|
||||
if states[reindeer][1] == time:
|
||||
if states[reindeer][0] == "resting":
|
||||
states[reindeer] = ("flying", time + reindeer.fly_time)
|
||||
else:
|
||||
states[reindeer] = ("resting", time + reindeer.rest_time)
|
||||
|
||||
yield max(distances.values())
|
||||
yield max(points.values()) - 1
|
56
src/holt59/aoc/2015/day15.py
Normal file
56
src/holt59/aoc/2015/day15.py
Normal file
@@ -0,0 +1,56 @@
|
||||
import math
|
||||
from typing import Any, Iterator, Sequence, cast
|
||||
|
||||
import parse # type: ignore
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
def score(ingredients: list[list[int]], teaspoons: Sequence[int]) -> int:
|
||||
return math.prod(
|
||||
max(
|
||||
0,
|
||||
sum(
|
||||
ingredient[prop] * teaspoon
|
||||
for ingredient, teaspoon in zip(ingredients, teaspoons)
|
||||
),
|
||||
)
|
||||
for prop in range(len(ingredients[0]) - 1)
|
||||
)
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
ingredients: list[list[int]] = []
|
||||
for line in lines:
|
||||
_, *scores = cast(
|
||||
tuple[str, int, int, int, int, int],
|
||||
parse.parse( # type: ignore
|
||||
"{}: capacity {:d}, durability {:d}, flavor {:d}, "
|
||||
"texture {:d}, calories {:d}",
|
||||
line,
|
||||
),
|
||||
)
|
||||
ingredients.append(scores)
|
||||
|
||||
total_teaspoons = 100
|
||||
calories: list[int] = []
|
||||
scores: list[int] = []
|
||||
|
||||
for a in range(total_teaspoons + 1):
|
||||
for b in range(total_teaspoons + 1 - a):
|
||||
for c in range(total_teaspoons + 1 - a - b):
|
||||
teaspoons = (a, b, c, total_teaspoons - a - b - c)
|
||||
|
||||
scores.append(score(ingredients, teaspoons))
|
||||
calories.append(
|
||||
sum(
|
||||
ingredient[-1] * teaspoon
|
||||
for ingredient, teaspoon in zip(ingredients, teaspoons)
|
||||
)
|
||||
)
|
||||
|
||||
yield max(scores)
|
||||
yield max(score for score, calory in zip(scores, calories) if calory == 500)
|
57
src/holt59/aoc/2015/day16.py
Normal file
57
src/holt59/aoc/2015/day16.py
Normal file
@@ -0,0 +1,57 @@
|
||||
import operator as op
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from typing import Any, Callable, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
MFCSAM: dict[str, int] = {
|
||||
"children": 3,
|
||||
"cats": 7,
|
||||
"samoyeds": 2,
|
||||
"pomeranians": 3,
|
||||
"akitas": 0,
|
||||
"vizslas": 0,
|
||||
"goldfish": 5,
|
||||
"trees": 3,
|
||||
"cars": 2,
|
||||
"perfumes": 1,
|
||||
}
|
||||
|
||||
|
||||
def match(
|
||||
aunts: list[dict[str, int]], operators: dict[str, Callable[[int, int], bool]]
|
||||
) -> int:
|
||||
return next(
|
||||
i
|
||||
for i, aunt in enumerate(aunts, start=1)
|
||||
if all(operators[k](aunt[k], MFCSAM[k]) for k in aunt)
|
||||
)
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
aunts: list[dict[str, int]] = [
|
||||
{
|
||||
match[1]: int(match[2])
|
||||
for match in re.findall(
|
||||
R"((?P<compound>[^:, ]+): (?P<quantity>\d+))", line
|
||||
)
|
||||
}
|
||||
for line in lines
|
||||
]
|
||||
|
||||
yield match(aunts, defaultdict(lambda: op.eq))
|
||||
|
||||
yield match(
|
||||
aunts,
|
||||
defaultdict(
|
||||
lambda: op.eq,
|
||||
trees=op.gt,
|
||||
cats=op.gt,
|
||||
pomeranians=op.lt,
|
||||
goldfish=op.lt,
|
||||
),
|
||||
)
|
34
src/holt59/aoc/2015/day17.py
Normal file
34
src/holt59/aoc/2015/day17.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
def iter_combinations(value: int, containers: list[int]) -> Iterator[tuple[int, ...]]:
|
||||
if value < 0:
|
||||
return
|
||||
|
||||
if value == 0:
|
||||
yield ()
|
||||
|
||||
for i in range(len(containers)):
|
||||
for combination in iter_combinations(
|
||||
value - containers[i], containers[i + 1 :]
|
||||
):
|
||||
yield (containers[i],) + combination
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
containers = [int(c) for c in input.split()]
|
||||
total = 25 if len(containers) <= 5 else 150
|
||||
|
||||
combinations = [
|
||||
combination for combination in iter_combinations(total, containers)
|
||||
]
|
||||
|
||||
yield len(combinations)
|
||||
|
||||
min_containers = min(len(combination) for combination in combinations)
|
||||
yield sum(
|
||||
1 for combination in combinations if len(combination) == min_containers
|
||||
)
|
66
src/holt59/aoc/2015/day18.py
Normal file
66
src/holt59/aoc/2015/day18.py
Normal file
@@ -0,0 +1,66 @@
|
||||
import itertools
|
||||
from typing import Any, Iterator
|
||||
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
grid0 = np.array([[c == "#" for c in line] for line in input.splitlines()])
|
||||
|
||||
# add an always off circle around
|
||||
grid0 = np.concatenate(
|
||||
[
|
||||
np.zeros((grid0.shape[0] + 2, 1), dtype=bool),
|
||||
np.concatenate(
|
||||
[
|
||||
np.zeros((1, grid0.shape[1]), dtype=bool),
|
||||
grid0,
|
||||
np.zeros((1, grid0.shape[1]), dtype=bool),
|
||||
]
|
||||
),
|
||||
np.zeros((grid0.shape[0] + 2, 1), dtype=bool),
|
||||
],
|
||||
axis=1,
|
||||
)
|
||||
|
||||
moves = list(itertools.product([-1, 0, 1], repeat=2))
|
||||
moves.remove((0, 0))
|
||||
|
||||
jjs, iis = np.meshgrid(
|
||||
np.arange(1, grid0.shape[0] - 1, dtype=int),
|
||||
np.arange(1, grid0.shape[1] - 1, dtype=int),
|
||||
)
|
||||
iis, jjs = iis.flatten(), jjs.flatten()
|
||||
|
||||
ins = iis[:, None] + np.array(moves)[:, 0]
|
||||
jns = jjs[:, None] + np.array(moves)[:, 1]
|
||||
|
||||
def game_of_life(grid: NDArray[np.bool_]) -> NDArray[np.bool_]:
|
||||
neighbors_on = grid[ins, jns].sum(axis=1)
|
||||
cells_on = grid[iis, jjs]
|
||||
|
||||
grid = np.zeros_like(grid)
|
||||
grid[iis, jjs] = (neighbors_on == 3) | (cells_on & (neighbors_on == 2))
|
||||
|
||||
return grid
|
||||
|
||||
grid = grid0
|
||||
n_steps = 4 if len(grid) < 10 else 100
|
||||
for _ in range(n_steps):
|
||||
grid = game_of_life(grid)
|
||||
|
||||
yield grid.sum()
|
||||
|
||||
n_steps = 5 if len(grid) < 10 else 100
|
||||
grid = grid0
|
||||
for _ in range(n_steps):
|
||||
grid[[1, 1, -2, -2], [1, -2, 1, -2]] = True
|
||||
grid = game_of_life(grid)
|
||||
|
||||
grid[[1, 1, -2, -2], [1, -2, 1, -2]] = True
|
||||
|
||||
yield sum(cell for line in grid for cell in line)
|
58
src/holt59/aoc/2015/day19.py
Normal file
58
src/holt59/aoc/2015/day19.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from collections import defaultdict
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
replacements_s, molecule = input.split("\n\n")
|
||||
|
||||
REPLACEMENTS: dict[str, list[str]] = defaultdict(list)
|
||||
for replacement_s in replacements_s.splitlines():
|
||||
p = replacement_s.split(" => ")
|
||||
REPLACEMENTS[p[0]].append(p[1])
|
||||
molecule = molecule.strip()
|
||||
|
||||
generated = [
|
||||
molecule[:i] + replacement + molecule[i + len(symbol) :]
|
||||
for symbol, replacements in REPLACEMENTS.items()
|
||||
for replacement in replacements
|
||||
for i in range(len(molecule))
|
||||
if molecule[i:].startswith(symbol)
|
||||
]
|
||||
|
||||
yield len(set(generated))
|
||||
|
||||
inversion: dict[str, str] = {
|
||||
replacement: symbol
|
||||
for symbol, replacements in REPLACEMENTS.items()
|
||||
for replacement in replacements
|
||||
}
|
||||
|
||||
# there is actually only one way to create the molecule, and we can greedily replace
|
||||
# tokens with their replacements, e.g., if H => OH then we can replace OH by H directly
|
||||
# without thinking
|
||||
|
||||
count = 0
|
||||
while molecule != "e":
|
||||
i = 0
|
||||
m2 = ""
|
||||
while i < len(molecule):
|
||||
found = False
|
||||
for replacement in inversion:
|
||||
if molecule[i:].startswith(replacement):
|
||||
m2 += inversion[replacement]
|
||||
i += len(replacement)
|
||||
count += 1
|
||||
found = True
|
||||
break
|
||||
|
||||
if not found:
|
||||
m2 += molecule[i]
|
||||
i += 1
|
||||
|
||||
# print(m2)
|
||||
molecule = m2
|
||||
|
||||
yield count
|
24
src/holt59/aoc/2015/day2.py
Normal file
24
src/holt59/aoc/2015/day2.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from typing import Any, Iterator
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
length, width, height = np.array(
|
||||
[[int(c) for c in line.split("x")] for line in input.splitlines()]
|
||||
).T
|
||||
|
||||
lw, wh, hl = (length * width, width * height, height * length)
|
||||
|
||||
yield np.sum(2 * (lw + wh + hl) + np.min(np.stack([lw, wh, hl]), axis=0))
|
||||
|
||||
yield np.sum(
|
||||
length * width * height
|
||||
+ 2
|
||||
* np.min(
|
||||
np.stack([length + width, length + height, height + width]), axis=0
|
||||
)
|
||||
)
|
29
src/holt59/aoc/2015/day20.py
Normal file
29
src/holt59/aoc/2015/day20.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import itertools
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
def presents(n: int, elf: int, max: int) -> int:
|
||||
count = 0
|
||||
k = 1
|
||||
while k * k < n:
|
||||
if n % k == 0:
|
||||
if n // k <= max:
|
||||
count += elf * k
|
||||
if k <= max:
|
||||
count += elf * (n // k)
|
||||
k += 1
|
||||
|
||||
if k * k == n and k <= max:
|
||||
count += elf * k
|
||||
|
||||
return count
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
target = int(input)
|
||||
|
||||
yield next(n for n in itertools.count(1) if presents(n, 10, target) >= target)
|
||||
yield next(n for n in itertools.count(1) if presents(n, 11, 50) >= target)
|
64
src/holt59/aoc/2015/day21.py
Normal file
64
src/holt59/aoc/2015/day21.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import itertools
|
||||
from math import ceil
|
||||
from typing import Any, Iterator, TypeAlias
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
Modifier: TypeAlias = tuple[str, int, int, int]
|
||||
|
||||
WEAPONS: list[Modifier] = [
|
||||
("Dagger", 8, 4, 0),
|
||||
("Shortsword", 10, 5, 0),
|
||||
("Warhammer", 25, 6, 0),
|
||||
("Longsword", 40, 7, 0),
|
||||
("Greataxe", 74, 8, 0),
|
||||
]
|
||||
|
||||
ARMORS: list[Modifier] = [
|
||||
("", 0, 0, 0),
|
||||
("Leather", 13, 0, 1),
|
||||
("Chainmail", 31, 0, 2),
|
||||
("Splintmail", 53, 0, 3),
|
||||
("Bandedmail", 75, 0, 4),
|
||||
("Platemail", 102, 0, 5),
|
||||
]
|
||||
|
||||
RINGS: list[Modifier] = [
|
||||
("", 0, 0, 0),
|
||||
("Damage +1", 25, 1, 0),
|
||||
("Damage +2", 50, 2, 0),
|
||||
("Damage +3", 100, 3, 0),
|
||||
("Defense +1", 20, 0, 1),
|
||||
("Defense +2", 40, 0, 2),
|
||||
("Defense +3", 80, 0, 3),
|
||||
]
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
player_hp = 100
|
||||
|
||||
boss_attack = int(lines[1].split(":")[1].strip())
|
||||
boss_armor = int(lines[2].split(":")[1].strip())
|
||||
boss_hp = int(lines[0].split(":")[1].strip())
|
||||
|
||||
min_cost, max_cost = 1_000_000, 0
|
||||
for equipments in itertools.product(WEAPONS, ARMORS, RINGS, RINGS):
|
||||
if equipments[-1][0] != "" and equipments[-2] == equipments[-1]:
|
||||
continue
|
||||
|
||||
cost, player_attack, player_armor = (
|
||||
sum(equipment[1:][k] for equipment in equipments) for k in range(3)
|
||||
)
|
||||
|
||||
if ceil(boss_hp / max(1, player_attack - boss_armor)) <= ceil(
|
||||
player_hp / max(1, boss_attack - player_armor)
|
||||
):
|
||||
min_cost = min(cost, min_cost)
|
||||
else:
|
||||
max_cost = max(cost, max_cost)
|
||||
|
||||
yield min_cost
|
||||
yield max_cost
|
182
src/holt59/aoc/2015/day22.py
Normal file
182
src/holt59/aoc/2015/day22.py
Normal file
@@ -0,0 +1,182 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
from typing import Any, Iterator, Literal, TypeAlias, cast
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
PlayerType: TypeAlias = Literal["player", "boss"]
|
||||
SpellType: TypeAlias = Literal["magic missile", "drain", "shield", "poison", "recharge"]
|
||||
BuffType: TypeAlias = Literal["shield", "poison", "recharge"]
|
||||
Node: TypeAlias = tuple[
|
||||
PlayerType,
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
tuple[tuple[BuffType, int], ...],
|
||||
tuple[tuple[SpellType, int], ...],
|
||||
]
|
||||
|
||||
ATTACK_SPELLS: list[tuple[SpellType, int, int, int]] = [
|
||||
("magic missile", 53, 4, 0),
|
||||
("drain", 73, 2, 2),
|
||||
]
|
||||
BUFF_SPELLS: list[tuple[BuffType, int, int]] = [
|
||||
("shield", 113, 6),
|
||||
("poison", 173, 6),
|
||||
("recharge", 229, 5),
|
||||
]
|
||||
|
||||
|
||||
def play(
|
||||
player_hp: int,
|
||||
player_mana: int,
|
||||
player_armor: int,
|
||||
boss_hp: int,
|
||||
boss_attack: int,
|
||||
hard_mode: bool,
|
||||
) -> tuple[tuple[SpellType, int], ...]:
|
||||
winning_node: tuple[tuple[SpellType, int], ...] | None = None
|
||||
|
||||
visited: set[
|
||||
tuple[PlayerType, int, int, int, int, tuple[tuple[BuffType, int], ...]]
|
||||
] = set()
|
||||
nodes: list[Node] = [
|
||||
("player", 0, player_hp, player_mana, player_armor, boss_hp, (), ())
|
||||
]
|
||||
|
||||
while winning_node is None:
|
||||
(
|
||||
player,
|
||||
mana,
|
||||
player_hp,
|
||||
player_mana,
|
||||
player_armor,
|
||||
boss_hp,
|
||||
buffs,
|
||||
spells,
|
||||
) = heapq.heappop(nodes)
|
||||
|
||||
if (player, player_hp, player_mana, player_armor, boss_hp, buffs) in visited:
|
||||
continue
|
||||
|
||||
visited.add((player, player_hp, player_mana, player_armor, boss_hp, buffs))
|
||||
new_buffs: list[tuple[BuffType, int]] = []
|
||||
for buff, length in buffs:
|
||||
length = length - 1
|
||||
match buff:
|
||||
case "poison":
|
||||
boss_hp = max(boss_hp - 3, 0)
|
||||
case "shield":
|
||||
if length == 0:
|
||||
player_armor -= 7
|
||||
case "recharge":
|
||||
player_mana += 101
|
||||
|
||||
if length > 0:
|
||||
new_buffs.append((buff, length))
|
||||
|
||||
if hard_mode and player == "player":
|
||||
player_hp = player_hp - 1
|
||||
|
||||
if player_hp <= 0:
|
||||
continue
|
||||
|
||||
if boss_hp <= 0:
|
||||
winning_node = spells
|
||||
continue
|
||||
|
||||
buffs = tuple(new_buffs)
|
||||
|
||||
if player == "boss":
|
||||
heapq.heappush(
|
||||
nodes,
|
||||
(
|
||||
"player",
|
||||
mana,
|
||||
max(0, player_hp - max(boss_attack - player_armor, 1)),
|
||||
player_mana,
|
||||
player_armor,
|
||||
boss_hp,
|
||||
buffs,
|
||||
spells,
|
||||
),
|
||||
)
|
||||
else:
|
||||
buff_types = {b for b, _ in buffs}
|
||||
|
||||
for spell, cost, damage, regeneration in ATTACK_SPELLS:
|
||||
if player_mana < cost:
|
||||
continue
|
||||
|
||||
heapq.heappush(
|
||||
nodes,
|
||||
(
|
||||
"boss",
|
||||
mana + cost,
|
||||
player_hp + regeneration,
|
||||
player_mana - cost,
|
||||
player_armor,
|
||||
max(0, boss_hp - damage),
|
||||
buffs,
|
||||
spells + cast("tuple[tuple[SpellType, int]]", ((spell, cost),)),
|
||||
),
|
||||
)
|
||||
|
||||
for buff_type, buff_cost, buff_length in BUFF_SPELLS:
|
||||
if buff_type in buff_types:
|
||||
continue
|
||||
|
||||
if player_mana < buff_cost:
|
||||
continue
|
||||
|
||||
heapq.heappush(
|
||||
nodes,
|
||||
(
|
||||
"boss",
|
||||
mana + buff_cost,
|
||||
player_hp,
|
||||
player_mana - buff_cost,
|
||||
player_armor + 7 * (buff_type == "shield"),
|
||||
boss_hp,
|
||||
buffs
|
||||
+ cast(
|
||||
"tuple[tuple[BuffType, int]]", ((buff_type, buff_length),)
|
||||
),
|
||||
spells
|
||||
+ cast(
|
||||
"tuple[tuple[SpellType, int]]", ((buff_type, buff_cost),)
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
return winning_node
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
player_hp = 50
|
||||
player_mana = 500
|
||||
player_armor = 0
|
||||
|
||||
boss_hp = int(lines[0].split(":")[1].strip())
|
||||
boss_attack = int(lines[1].split(":")[1].strip())
|
||||
|
||||
yield sum(
|
||||
c
|
||||
for _, c in play(
|
||||
player_hp, player_mana, player_armor, boss_hp, boss_attack, False
|
||||
)
|
||||
)
|
||||
|
||||
# 1242 (not working)
|
||||
yield sum(
|
||||
c
|
||||
for _, c in play(
|
||||
player_hp, player_mana, player_armor, boss_hp, boss_attack, True
|
||||
)
|
||||
)
|
33
src/holt59/aoc/2015/day3.py
Normal file
33
src/holt59/aoc/2015/day3.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from collections import defaultdict
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
def process(directions: str) -> dict[tuple[int, int], int]:
|
||||
counts: dict[tuple[int, int], int] = defaultdict(lambda: 0)
|
||||
counts[0, 0] = 1
|
||||
x, y = (0, 0)
|
||||
|
||||
for c in directions:
|
||||
match c:
|
||||
case ">":
|
||||
x += 1
|
||||
case "<":
|
||||
x -= 1
|
||||
case "^":
|
||||
y -= 1
|
||||
case "v":
|
||||
y += 1
|
||||
case _:
|
||||
raise ValueError()
|
||||
|
||||
counts[x, y] += 1
|
||||
|
||||
return counts
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
yield len(process(input))
|
||||
yield len(process(input[::2]) | process(input[1::2]))
|
20
src/holt59/aoc/2015/day4.py
Normal file
20
src/holt59/aoc/2015/day4.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import hashlib
|
||||
import itertools
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
it = iter(itertools.count(1))
|
||||
yield next(
|
||||
i
|
||||
for i in it
|
||||
if hashlib.md5(f"{input}{i}".encode()).hexdigest().startswith("00000")
|
||||
)
|
||||
yield next(
|
||||
i
|
||||
for i in it
|
||||
if hashlib.md5(f"{input}{i}".encode()).hexdigest().startswith("000000")
|
||||
)
|
36
src/holt59/aoc/2015/day5.py
Normal file
36
src/holt59/aoc/2015/day5.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
VOWELS = "aeiou"
|
||||
FORBIDDEN = {"ab", "cd", "pq", "xy"}
|
||||
|
||||
|
||||
def is_nice_1(s: str) -> bool:
|
||||
if sum(c in VOWELS for c in s) < 3:
|
||||
return False
|
||||
|
||||
if not any(a == b for a, b in zip(s[:-1:], s[1::])):
|
||||
return False
|
||||
|
||||
if any(s.find(f) >= 0 for f in FORBIDDEN):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def is_nice_2(s: str) -> bool:
|
||||
if not any(s.find(s[i : i + 2], i + 2) >= 0 for i in range(len(s))):
|
||||
return False
|
||||
|
||||
if not any(a == b for a, b in zip(s[:-1:], s[2::])):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
yield sum(map(is_nice_1, lines))
|
||||
yield sum(map(is_nice_2, lines))
|
32
src/holt59/aoc/2015/day6.py
Normal file
32
src/holt59/aoc/2015/day6.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from typing import Any, Iterator, Literal, cast
|
||||
|
||||
import numpy as np
|
||||
import parse # type: ignore
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lights_1 = np.zeros((1000, 1000), dtype=bool)
|
||||
lights_2 = np.zeros((1000, 1000), dtype=int)
|
||||
for line in input.splitlines():
|
||||
action, sx, sy, ex, ey = cast(
|
||||
tuple[Literal["turn on", "turn off", "toggle"], int, int, int, int],
|
||||
parse.parse("{} {:d},{:d} through {:d},{:d}", line), # type: ignore
|
||||
)
|
||||
ex, ey = ex + 1, ey + 1
|
||||
|
||||
match action:
|
||||
case "turn on":
|
||||
lights_1[sx:ex, sy:ey] = True
|
||||
lights_2[sx:ex, sy:ey] += 1
|
||||
case "turn off":
|
||||
lights_1[sx:ex, sy:ey] = False
|
||||
lights_2[sx:ex, sy:ey] = np.maximum(lights_2[sx:ex, sy:ey] - 1, 0)
|
||||
case "toggle":
|
||||
lights_1[sx:ex, sy:ey] = ~lights_1[sx:ex, sy:ey]
|
||||
lights_2[sx:ex, sy:ey] += 2
|
||||
|
||||
yield lights_1.sum()
|
||||
yield lights_2.sum()
|
96
src/holt59/aoc/2015/day7.py
Normal file
96
src/holt59/aoc/2015/day7.py
Normal file
@@ -0,0 +1,96 @@
|
||||
import operator
|
||||
from typing import Any, Callable, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
OPERATORS = {
|
||||
"AND": operator.and_,
|
||||
"OR": operator.or_,
|
||||
"LSHIFT": operator.lshift,
|
||||
"RSHIFT": operator.rshift,
|
||||
}
|
||||
|
||||
ValueGetter = Callable[[dict[str, int]], int]
|
||||
Signals = dict[
|
||||
str,
|
||||
tuple[
|
||||
tuple[str, str],
|
||||
tuple[ValueGetter, ValueGetter],
|
||||
Callable[[int, int], int],
|
||||
],
|
||||
]
|
||||
|
||||
|
||||
def zero_op(_a: int, _b: int) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def value_of(key: str) -> tuple[str, Callable[[dict[str, int]], int]]:
|
||||
try:
|
||||
return "", lambda _p, _v=int(key): _v
|
||||
except ValueError:
|
||||
return key, lambda values: values[key]
|
||||
|
||||
|
||||
def process(
|
||||
signals: Signals,
|
||||
values: dict[str, int],
|
||||
) -> dict[str, int]:
|
||||
while signals:
|
||||
signal = next(s for s in signals if all(p in values for p in signals[s][0]))
|
||||
_, deps, command = signals[signal]
|
||||
values[signal] = command(deps[0](values), deps[1](values)) % 65536
|
||||
del signals[signal]
|
||||
|
||||
return values
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any] | None:
|
||||
lines = input.splitlines()
|
||||
|
||||
signals: Signals = {}
|
||||
values: dict[str, int] = {"": 0}
|
||||
|
||||
for line in lines:
|
||||
command, signal = line.split(" -> ")
|
||||
|
||||
if command.startswith("NOT"):
|
||||
name = command.split(" ")[1]
|
||||
signals[signal] = (
|
||||
(name, ""),
|
||||
(lambda values, _n=name: values[_n], lambda _v: 0),
|
||||
lambda a, _b: ~a,
|
||||
)
|
||||
|
||||
elif not any(command.find(name) >= 0 for name in OPERATORS):
|
||||
try:
|
||||
values[signal] = int(command)
|
||||
except ValueError:
|
||||
signals[signal] = (
|
||||
(command, ""),
|
||||
(lambda values, _c=command: values[_c], lambda _v: 0),
|
||||
lambda a, _b: a,
|
||||
)
|
||||
|
||||
else:
|
||||
op: Callable[[int, int], int] = zero_op
|
||||
lhs_s, rhs_s = "", ""
|
||||
|
||||
for name in OPERATORS:
|
||||
if command.find(name) >= 0:
|
||||
op = OPERATORS[name]
|
||||
lhs_s, rhs_s = command.split(f" {name} ")
|
||||
break
|
||||
|
||||
lhs_s, lhs_fn = value_of(lhs_s)
|
||||
rhs_s, rhs_fn = value_of(rhs_s)
|
||||
|
||||
signals[signal] = ((lhs_s, rhs_s), (lhs_fn, rhs_fn), op)
|
||||
|
||||
values_1 = process(signals.copy(), values.copy())
|
||||
for k in sorted(values_1):
|
||||
self.logger.info(f"{k}: {values_1[k]}")
|
||||
yield values_1["a"]
|
||||
|
||||
yield process(signals.copy(), values | {"b": values_1["a"]})["a"]
|
32
src/holt59/aoc/2015/day8.py
Normal file
32
src/holt59/aoc/2015/day8.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from typing import Any, Iterator
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
yield sum(
|
||||
# left and right quotes (not in memory)
|
||||
2
|
||||
# each \\ adds one character in the literals (compared to memory)
|
||||
+ line.count(R"\\")
|
||||
# each \" adds one character in the literals (compared to memory)
|
||||
+ line[1:-1].count(R"\"")
|
||||
# each \xFF adds 3 characters in the literals (compared to memory), but we must not
|
||||
# count A\\x (A != \), but we must count A\\\x (A != \) - in practice we should also
|
||||
# avoid \\\\x, etc., but this does not occur in the examples and the actual input
|
||||
+ 3 * (line.count(R"\x") - line.count(R"\\x") + line.count(R"\\\x"))
|
||||
for line in lines
|
||||
)
|
||||
|
||||
yield sum(
|
||||
# needs to wrap in quotes (2 characters)
|
||||
2
|
||||
# needs to escape every \ with an extra \
|
||||
+ line.count("\\")
|
||||
# needs to escape every " with an extra \ (including the first and last ones)
|
||||
+ line.count('"')
|
||||
for line in lines
|
||||
)
|
28
src/holt59/aoc/2015/day9.py
Normal file
28
src/holt59/aoc/2015/day9.py
Normal file
@@ -0,0 +1,28 @@
|
||||
import itertools
|
||||
from collections import defaultdict
|
||||
from typing import Any, Iterator, cast
|
||||
|
||||
import parse # type: ignore
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
distances: dict[str, dict[str, int]] = defaultdict(dict)
|
||||
for line in lines:
|
||||
origin, destination, length = cast(
|
||||
tuple[str, str, int],
|
||||
parse.parse("{} to {} = {:d}", line), # type: ignore
|
||||
)
|
||||
distances[origin][destination] = distances[destination][origin] = length
|
||||
|
||||
distance_of_routes = {
|
||||
route: sum(distances[o][d] for o, d in zip(route[:-1], route[1:]))
|
||||
for route in map(tuple, itertools.permutations(distances))
|
||||
}
|
||||
|
||||
yield min(distance_of_routes.values())
|
||||
yield max(distance_of_routes.values())
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,12 +1,13 @@
|
||||
import sys
|
||||
from math import prod
|
||||
from typing import Literal, cast
|
||||
from typing import Literal, TypeAlias, cast
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
||||
commands = [
|
||||
(cast(Literal["forward", "up", "down"], (p := line.split())[0]), int(p[1]))
|
||||
for line in lines
|
||||
Command: TypeAlias = Literal["forward", "up", "down"]
|
||||
|
||||
commands: list[tuple[Command, int]] = [
|
||||
(cast(Command, (p := line.split())[0]), int(p[1])) for line in lines
|
||||
]
|
||||
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
@@ -1,6 +1,4 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
lines = sys.stdin.read().splitlines()
|
||||
|
19
src/holt59/aoc/2021/day7.py
Normal file
19
src/holt59/aoc/2021/day7.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import sys
|
||||
|
||||
positions = [int(c) for c in sys.stdin.read().strip().split(",")]
|
||||
|
||||
min_position, max_position = min(positions), max(positions)
|
||||
|
||||
# part 1
|
||||
answer_1 = min(
|
||||
sum(abs(p - position) for p in positions)
|
||||
for position in range(min_position, max_position + 1)
|
||||
)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = min(
|
||||
sum(abs(p - position) * (abs(p - position) + 1) // 2 for p in positions)
|
||||
for position in range(min_position, max_position + 1)
|
||||
)
|
||||
print(f"answer 2 is {answer_2}")
|
44
src/holt59/aoc/2021/day9.py
Normal file
44
src/holt59/aoc/2021/day9.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import sys
|
||||
from math import prod
|
||||
|
||||
values = [[int(c) for c in row] for row in sys.stdin.read().splitlines()]
|
||||
n_rows, n_cols = len(values), len(values[0])
|
||||
|
||||
|
||||
def neighbors(point: tuple[int, int]):
|
||||
i, j = point
|
||||
for di, dj in ((-1, 0), (+1, 0), (0, -1), (0, +1)):
|
||||
if 0 <= i + di < n_rows and 0 <= j + dj < n_cols:
|
||||
yield (i + di, j + dj)
|
||||
|
||||
|
||||
def basin(start: tuple[int, int]) -> set[tuple[int, int]]:
|
||||
visited: set[tuple[int, int]] = set()
|
||||
queue = [start]
|
||||
|
||||
while queue:
|
||||
i, j = queue.pop()
|
||||
|
||||
if (i, j) in visited or values[i][j] == 9:
|
||||
continue
|
||||
|
||||
visited.add((i, j))
|
||||
queue.extend(neighbors((i, j)))
|
||||
|
||||
return visited
|
||||
|
||||
|
||||
low_points = [
|
||||
(i, j)
|
||||
for i in range(n_rows)
|
||||
for j in range(n_cols)
|
||||
if all(values[ti][tj] > values[i][j] for ti, tj in neighbors((i, j)))
|
||||
]
|
||||
|
||||
# part 1
|
||||
answer_1 = sum(values[i][j] + 1 for i, j in low_points)
|
||||
print(f"answer 1 is {answer_1}")
|
||||
|
||||
# part 2
|
||||
answer_2 = prod(sorted(len(basin(point)) for point in low_points)[-3:])
|
||||
print(f"answer 2 is {answer_2}")
|
@@ -122,8 +122,8 @@ lines = sys.stdin.read().splitlines()
|
||||
|
||||
grid = [[ord(cell) - ord("a") for cell in line] for line in lines]
|
||||
|
||||
start: tuple[int, int]
|
||||
end: tuple[int, int]
|
||||
start: tuple[int, int] | None = None
|
||||
end: tuple[int, int] | None = None
|
||||
|
||||
# for part 2
|
||||
start_s: list[tuple[int, int]] = []
|
||||
@@ -138,6 +138,9 @@ for i_row, row in enumerate(grid):
|
||||
elif col == 0:
|
||||
start_s.append((i_row, i_col))
|
||||
|
||||
assert start is not None
|
||||
assert end is not None
|
||||
|
||||
# fix values
|
||||
grid[start[0]][start[1]] = 0
|
||||
grid[end[0]][end[1]] = ord("z") - ord("a")
|
96
src/holt59/aoc/2022/day15.py
Normal file
96
src/holt59/aoc/2022/day15.py
Normal file
@@ -0,0 +1,96 @@
|
||||
import sys
|
||||
from typing import Any, Iterator
|
||||
|
||||
import numpy as np
|
||||
import parse # type: ignore
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from ..base import BaseSolver
|
||||
|
||||
|
||||
class Solver(BaseSolver):
|
||||
def part1(
|
||||
self, sensor_to_beacon: dict[tuple[int, int], tuple[int, int]], row: int
|
||||
) -> int:
|
||||
no_beacons_row_l: list[NDArray[np.floating[Any]]] = []
|
||||
|
||||
for (sx, sy), (bx, by) in sensor_to_beacon.items():
|
||||
d = abs(sx - bx) + abs(sy - by) # closest
|
||||
|
||||
no_beacons_row_l.append(sx - np.arange(0, d - abs(sy - row) + 1)) # type: ignore
|
||||
no_beacons_row_l.append(sx + np.arange(0, d - abs(sy - row) + 1)) # type: ignore
|
||||
|
||||
beacons_at_row = set(bx for (bx, by) in sensor_to_beacon.values() if by == row)
|
||||
no_beacons_row = set(np.concatenate(no_beacons_row_l)).difference(
|
||||
beacons_at_row
|
||||
) # type: ignore
|
||||
|
||||
return len(no_beacons_row)
|
||||
|
||||
def part2_intervals(
|
||||
self, sensor_to_beacon: dict[tuple[int, int], tuple[int, int]], xy_max: int
|
||||
) -> tuple[int, int, int]:
|
||||
for y in self.progress.wrap(range(xy_max + 1)):
|
||||
its: list[tuple[int, int]] = []
|
||||
for (sx, sy), (bx, by) in sensor_to_beacon.items():
|
||||
d = abs(sx - bx) + abs(sy - by)
|
||||
dx = d - abs(sy - y)
|
||||
|
||||
if dx >= 0:
|
||||
its.append((max(0, sx - dx), min(sx + dx, xy_max)))
|
||||
|
||||
its = sorted(its)
|
||||
_, e = its[0]
|
||||
|
||||
for si, ei in its[1:]:
|
||||
if si > e + 1:
|
||||
return si - 1, y, 4_000_000 * (si - 1) + y
|
||||
if ei > e:
|
||||
e = ei
|
||||
|
||||
return (0, 0, 0)
|
||||
|
||||
def part2_cplex(
|
||||
self, sensor_to_beacon: dict[tuple[int, int], tuple[int, int]], xy_max: int
|
||||
) -> tuple[int, int, int]:
|
||||
from docplex.mp.model import Model
|
||||
|
||||
m = Model()
|
||||
|
||||
x, y = m.continuous_var_list(2, ub=xy_max, name=["x", "y"])
|
||||
|
||||
for (sx, sy), (bx, by) in sensor_to_beacon.items():
|
||||
d = abs(sx - bx) + abs(sy - by)
|
||||
m.add_constraint(
|
||||
m.abs(x - sx) + m.abs(y - sy) >= d + 1, ctname=f"ct_{sx}_{sy}"
|
||||
) # type: ignore
|
||||
|
||||
m.set_objective("min", x + y)
|
||||
|
||||
s = m.solve()
|
||||
assert s is not None
|
||||
|
||||
vx = int(s.get_value(x))
|
||||
vy = int(s.get_value(y))
|
||||
return vx, vy, 4_000_000 * vx + vy
|
||||
|
||||
def solve(self, input: str) -> Iterator[Any]:
|
||||
lines = input.splitlines()
|
||||
|
||||
sensor_to_beacon: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
|
||||
for line in lines:
|
||||
r: dict[str, str] = parse.parse( # type: ignore
|
||||
"Sensor at x={sx}, y={sy}: closest beacon is at x={bx}, y={by}", line
|
||||
)
|
||||
sensor_to_beacon[int(r["sx"]), int(r["sy"])] = (int(r["bx"]), int(r["by"]))
|
||||
|
||||
xy_max = 4_000_000 if max(sensor_to_beacon) > (1_000, 0) else 20
|
||||
row = 2_000_000 if max(sensor_to_beacon) > (1_000, 0) else 10
|
||||
|
||||
yield self.part1(sensor_to_beacon, row)
|
||||
|
||||
# x, y, a2 = part2_cplex(sensor_to_beacon, xy_max)
|
||||
x, y, a2 = self.part2_intervals(sensor_to_beacon, xy_max)
|
||||
self.logger.info("answer 2 is {at} (x={x}, y={y})")
|
||||
yield a2
|
@@ -1,5 +1,4 @@
|
||||
import sys
|
||||
from typing import FrozenSet
|
||||
|
||||
import numpy as np
|
||||
|
@@ -1,9 +1,9 @@
|
||||
import sys
|
||||
from typing import Literal
|
||||
from typing import Any, Literal
|
||||
|
||||
import numpy as np
|
||||
import parse
|
||||
from tqdm import tqdm
|
||||
import parse # pyright: ignore[reportMissingTypeStubs]
|
||||
from numpy.typing import NDArray
|
||||
|
||||
Reagent = Literal["ore", "clay", "obsidian", "geode"]
|
||||
REAGENTS: tuple[Reagent, ...] = (
|
||||
@@ -35,7 +35,7 @@ class State:
|
||||
self.robots = robots
|
||||
self.reagents = reagents
|
||||
|
||||
def __eq__(self, other) -> bool:
|
||||
def __eq__(self, other: object) -> bool:
|
||||
return (
|
||||
isinstance(other, State)
|
||||
and self.robots == other.robots
|
||||
@@ -66,7 +66,7 @@ lines = sys.stdin.read().splitlines()
|
||||
|
||||
blueprints: list[dict[Reagent, IntOfReagent]] = []
|
||||
for line in lines:
|
||||
r = parse.parse(
|
||||
r: list[int] = parse.parse( # type: ignore
|
||||
"Blueprint {}: "
|
||||
"Each ore robot costs {:d} ore. "
|
||||
"Each clay robot costs {:d} ore. "
|
||||
@@ -94,11 +94,12 @@ def run(blueprint: dict[Reagent, dict[Reagent, int]], max_time: int) -> int:
|
||||
name: max(blueprint[r].get(name, 0) for r in REAGENTS) for name in REAGENTS
|
||||
}
|
||||
|
||||
state_after_t: dict[int, set[State]] = {0: [State()]}
|
||||
state_after_t: dict[int, set[State]] = {0: {State()}}
|
||||
|
||||
for t in range(1, max_time + 1):
|
||||
# list of new states at the end of step t that we are going to prune later
|
||||
states_for_t: set[State] = set()
|
||||
robots_that_can_be_built: list[Reagent]
|
||||
|
||||
for state in state_after_t[t - 1]:
|
||||
robots_that_can_be_built = [
|
||||
@@ -132,7 +133,7 @@ def run(blueprint: dict[Reagent, dict[Reagent, int]], max_time: int) -> int:
|
||||
for robot in robots_that_can_be_built:
|
||||
robots = state.robots.copy()
|
||||
robots[robot] += 1
|
||||
reagents = {
|
||||
reagents: IntOfReagent = {
|
||||
reagent: state.reagents[reagent]
|
||||
+ state.robots[reagent]
|
||||
- blueprint[robot].get(reagent, 0)
|
||||
@@ -151,7 +152,7 @@ def run(blueprint: dict[Reagent, dict[Reagent, int]], max_time: int) -> int:
|
||||
]
|
||||
)
|
||||
|
||||
to_keep = []
|
||||
to_keep: list[NDArray[np.integer[Any]]] = []
|
||||
while len(np_states) > 0:
|
||||
first_dom = (np_states[1:] >= np_states[0]).all(axis=1).any()
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user