Refactor 2021 for new UI.
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is failing

This commit is contained in:
Mikaël Capelle 2024-12-08 14:03:34 +01:00
parent cd96140378
commit 1b4dd32898
25 changed files with 310 additions and 355 deletions

View File

@ -1,14 +1,17 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lines = input.splitlines()
values = [int(line) for line in lines] values = [int(line) for line in lines]
# part 1 # part 1
answer_1 = sum(v2 > v1 for v1, v2 in zip(values[:-1], values[1:])) yield sum(v2 > v1 for v1, v2 in zip(values[:-1], values[1:]))
print(f"answer 1 is {answer_1}")
# part 2 # part 2
runnings = [sum(values[i : i + 3]) for i in range(len(values) - 2)] runnings = [sum(values[i : i + 3]) for i in range(len(values) - 2)]
answer_2 = sum(v2 > v1 for v1, v2 in zip(runnings[:-1], runnings[1:])) yield sum(v2 > v1 for v1, v2 in zip(runnings[:-1], runnings[1:]))
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,16 +1,19 @@
import sys
from math import prod from math import prod
from typing import Literal, TypeAlias, cast from typing import Any, Iterator, Literal, TypeAlias, cast
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
Command: TypeAlias = Literal["forward", "up", "down"] Command: TypeAlias = Literal["forward", "up", "down"]
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lines = input.splitlines()
commands: list[tuple[Command, int]] = [ commands: list[tuple[Command, int]] = [
(cast(Command, (p := line.split())[0]), int(p[1])) for line in lines (cast(Command, (p := line.split())[0]), int(p[1])) for line in lines
] ]
def depth_and_position(use_aim: bool): def depth_and_position(use_aim: bool):
aim, pos, depth = 0, 0, 0 aim, pos, depth = 0, 0, 0
for command, value in commands: for command, value in commands:
@ -31,11 +34,5 @@ def depth_and_position(use_aim: bool):
return depth, pos return depth, pos
yield prod(depth_and_position(False))
# part 1 yield prod(depth_and_position(True))
answer_1 = prod(depth_and_position(False))
print(f"answer 1 is {answer_1}")
# part 2
answer_2 = prod(depth_and_position(True))
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,11 +1,7 @@
import sys from typing import Any, Iterator
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
# part 1
answer_1 = ...
print(f"answer 1 is {answer_1}")
# part 2 class Solver(BaseSolver):
answer_2 = ... def solve(self, input: str) -> Iterator[Any]: ...
print(f"answer 2 is {answer_2}")

View File

@ -1,6 +1,7 @@
import sys
from collections import Counter from collections import Counter
from typing import Literal from typing import Any, Iterator, Literal
from ..base import BaseSolver
def generator_rating( def generator_rating(
@ -20,20 +21,23 @@ def generator_rating(
return values[0] return values[0]
lines = sys.stdin.read().splitlines() class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lines = input.splitlines()
# part 1 # part 1
most_and_least_common = [ most_and_least_common = [
tuple(Counter(line[col] for line in lines).most_common(2)[m][0] for m in range(2)) tuple(
Counter(line[col] for line in lines).most_common(2)[m][0]
for m in range(2)
)
for col in range(len(lines[0])) for col in range(len(lines[0]))
] ]
gamma_rate = int("".join(most for most, _ in most_and_least_common), base=2) gamma_rate = int("".join(most for most, _ in most_and_least_common), base=2)
epsilon_rate = int("".join(least for _, least in most_and_least_common), base=2) epsilon_rate = int("".join(least for _, least in most_and_least_common), base=2)
print(f"answer 1 is {gamma_rate * epsilon_rate}") yield gamma_rate * epsilon_rate
# part 2 # part 2
oxygen_generator_rating = int(generator_rating(lines, True, "1"), base=2) oxygen_generator_rating = int(generator_rating(lines, True, "1"), base=2)
co2_scrubber_rating = int(generator_rating(lines, False, "0"), base=2) co2_scrubber_rating = int(generator_rating(lines, False, "0"), base=2)
answer_2 = oxygen_generator_rating * co2_scrubber_rating yield oxygen_generator_rating * co2_scrubber_rating
print(f"answer 2 is {answer_2}")

View File

@ -1,8 +1,13 @@
import sys from typing import Any, Iterator
import numpy as np import numpy as np
lines = sys.stdin.read().splitlines() from ..base import BaseSolver
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lines = input.splitlines()
numbers = [int(c) for c in lines[0].split(",")] numbers = [int(c) for c in lines[0].split(",")]
@ -26,7 +31,9 @@ for round, number in enumerate(numbers):
if winning_rounds[index][0] > 0: if winning_rounds[index][0] > 0:
continue continue
if np.any(np.all(marked[index], axis=0) | np.all(marked[index], axis=1)): if np.any(
np.all(marked[index], axis=0) | np.all(marked[index], axis=1)
):
winning_rounds[index] = ( winning_rounds[index] = (
round, round,
number * int(np.sum(boards[index][~marked[index]])), number * int(np.sum(boards[index][~marked[index]])),
@ -38,8 +45,8 @@ for round, number in enumerate(numbers):
# part 1 # part 1
(_, score) = min(winning_rounds, key=lambda w: w[0]) (_, score) = min(winning_rounds, key=lambda w: w[0])
print(f"answer 1 is {score}") yield score
# part 2 # part 2
(_, score) = max(winning_rounds, key=lambda w: w[0]) (_, score) = max(winning_rounds, key=lambda w: w[0])
print(f"answer 2 is {score}") yield score

View File

@ -1,8 +1,13 @@
import sys from typing import Any, Iterator
import numpy as np import numpy as np
lines: list[str] = sys.stdin.read().splitlines() from ..base import BaseSolver
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lines = input.splitlines()
sections: list[tuple[tuple[int, int], tuple[int, int]]] = [ sections: list[tuple[tuple[int, int], tuple[int, int]]] = [
( (
@ -20,10 +25,8 @@ sections: list[tuple[tuple[int, int], tuple[int, int]]] = [
np_sections = np.array(sections).reshape(-1, 4) np_sections = np.array(sections).reshape(-1, 4)
x_min, x_max, y_min, y_max = ( x_max, y_max = (
min(np_sections[:, 0].min(), np_sections[:, 2].min()),
max(np_sections[:, 0].max(), np_sections[:, 2].max()), max(np_sections[:, 0].max(), np_sections[:, 2].max()),
min(np_sections[:, 1].min(), np_sections[:, 3].min()),
max(np_sections[:, 1].max(), np_sections[:, 3].max()), max(np_sections[:, 1].max(), np_sections[:, 3].max()),
) )
@ -41,8 +44,5 @@ for (x1, y1), (x2, y2) in sections:
for i, j in zip(y_rng, x_rng): for i, j in zip(y_rng, x_rng):
counts_2[i, j] += 1 counts_2[i, j] += 1
answer_1 = (counts_1 >= 2).sum() yield (counts_1 >= 2).sum()
print(f"answer 1 is {answer_1}") yield (counts_2 >= 2).sum()
answer_2 = (counts_2 >= 2).sum()
print(f"answer 2 is {answer_2}")

View File

@ -1,6 +1,11 @@
import sys from typing import Any, Iterator
values = [int(c) for c in sys.stdin.read().strip().split(",")] from ..base import BaseSolver
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
values = [int(c) for c in input.split(",")]
days = 256 days = 256
lanterns = {day: 0 for day in range(days)} lanterns = {day: 0 for day in range(days)}
@ -12,10 +17,5 @@ for day in range(days):
for day2 in range(day + 9, days, 7): for day2 in range(day + 9, days, 7):
lanterns[day2] += lanterns[day] lanterns[day2] += lanterns[day]
# part 1 yield sum(v for k, v in lanterns.items() if k < 80) + len(values)
answer_1 = sum(v for k, v in lanterns.items() if k < 80) + len(values) yield sum(lanterns.values()) + len(values)
print(f"answer 1 is {answer_1}")
# part 2
answer_2 = sum(lanterns.values()) + len(values)
print(f"answer 2 is {answer_2}")

View File

@ -1,19 +1,22 @@
import sys from typing import Any, Iterator
positions = [int(c) for c in sys.stdin.read().strip().split(",")] from ..base import BaseSolver
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
positions = [int(c) for c in input.split(",")]
min_position, max_position = min(positions), max(positions) min_position, max_position = min(positions), max(positions)
# part 1 # part 1
answer_1 = min( yield min(
sum(abs(p - position) for p in positions) sum(abs(p - position) for p in positions)
for position in range(min_position, max_position + 1) for position in range(min_position, max_position + 1)
) )
print(f"answer 1 is {answer_1}")
# part 2 # part 2
answer_2 = min( yield min(
sum(abs(p - position) * (abs(p - position) + 1) // 2 for p in positions) sum(abs(p - position) * (abs(p - position) + 1) // 2 for p in positions)
for position in range(min_position, max_position + 1) for position in range(min_position, max_position + 1)
) )
print(f"answer 2 is {answer_2}")

View File

@ -1,8 +1,7 @@
import itertools import itertools
import os from typing import Any, Iterator
import sys
VERBOSE = os.getenv("AOC_VERBOSE") == "True" from ..base import BaseSolver
digits = { digits = {
"abcefg": 0, "abcefg": 0,
@ -17,14 +16,18 @@ digits = {
"abcdfg": 9, "abcdfg": 9,
} }
lines = sys.stdin.read().splitlines()
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lines = input.splitlines()
# part 1 # part 1
lengths = {len(k) for k, v in digits.items() if v in (1, 4, 7, 8)} lengths = {len(k) for k, v in digits.items() if v in (1, 4, 7, 8)}
answer_1 = sum( yield sum(
len(p) in lengths for line in lines for p in line.split("|")[1].strip().split() len(p) in lengths
for line in lines
for p in line.split("|")[1].strip().split()
) )
print(f"answer 1 is {answer_1}")
# part 2 # part 2
values: list[int] = [] values: list[int] = []
@ -49,7 +52,9 @@ for line in lines:
bd = [u for u in per_length[4][0] if u not in cf] bd = [u for u in per_length[4][0] if u not in cf]
# the 3 digits of length 5 have a, d and g in common # the 3 digits of length 5 have a, d and g in common
adg = [u for u in per_length[5][0] if all(u in pe for pe in per_length[5][1:])] adg = [
u for u in per_length[5][0] if all(u in pe for pe in per_length[5][1:])
]
# we can remove a # we can remove a
dg = [u for u in adg if u != a] dg = [u for u in adg if u != a]
@ -77,11 +82,8 @@ for line in lines:
digit = "".join(sorted(mapping[c] for c in number)) digit = "".join(sorted(mapping[c] for c in number))
value = 10 * value + digits[digit] value = 10 * value + digits[digit]
if VERBOSE: self.logger.info(f"value for '{line}' is {value}")
print(value)
values.append(value) values.append(value)
yield sum(values)
answer_2 = sum(values)
print(f"answer 2 is {answer_2}")

View File

@ -1,18 +1,18 @@
import sys
from math import prod from math import prod
from typing import Any, Iterator
values = [[int(c) for c in row] for row in sys.stdin.read().splitlines()] from ..base import BaseSolver
n_rows, n_cols = len(values), len(values[0])
def neighbors(point: tuple[int, int]): def neighbors(point: tuple[int, int], n_rows: int, n_cols: int):
i, j = point i, j = point
for di, dj in ((-1, 0), (+1, 0), (0, -1), (0, +1)): for di, dj in ((-1, 0), (+1, 0), (0, -1), (0, +1)):
if 0 <= i + di < n_rows and 0 <= j + dj < n_cols: if 0 <= i + di < n_rows and 0 <= j + dj < n_cols:
yield (i + di, j + dj) yield (i + di, j + dj)
def basin(start: tuple[int, int]) -> set[tuple[int, int]]: def basin(values: list[list[int]], start: tuple[int, int]) -> set[tuple[int, int]]:
n_rows, n_cols = len(values), len(values[0])
visited: set[tuple[int, int]] = set() visited: set[tuple[int, int]] = set()
queue = [start] queue = [start]
@ -23,22 +23,25 @@ def basin(start: tuple[int, int]) -> set[tuple[int, int]]:
continue continue
visited.add((i, j)) visited.add((i, j))
queue.extend(neighbors((i, j))) queue.extend(neighbors((i, j), n_rows, n_cols))
return visited return visited
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
values = [[int(c) for c in row] for row in input.splitlines()]
n_rows, n_cols = len(values), len(values[0])
low_points = [ low_points = [
(i, j) (i, j)
for i in range(n_rows) for i in range(n_rows)
for j in range(n_cols) for j in range(n_cols)
if all(values[ti][tj] > values[i][j] for ti, tj in neighbors((i, j))) if all(
values[ti][tj] > values[i][j]
for ti, tj in neighbors((i, j), n_rows, n_cols)
)
] ]
# part 1 yield sum(values[i][j] + 1 for i, j in low_points)
answer_1 = sum(values[i][j] + 1 for i, j in low_points) yield prod(sorted(len(basin(values, point)) for point in low_points)[-3:])
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}")