This commit is contained in:
thib8956 committed 2026-11-11 15:36:53 +01:00
1 parent 0232b9326d
commit 5c3fb89870
50 files changed
+94 -114

No files matched your search

+6 -6
View File
@@ -27,12 +27,12 @@ def example(ingredients):
# for example input, two ingredients such that # for example input, two ingredients such that
# a + b = 100 with a and b >= 0 # a + b = 100 with a and b >= 0
max_score = 0 max_score = 0
for a in range(0, 101): for a in range(101):
b = 100 - a b = 100 - a
# ignore last property (calories) # ignore last property (calories)
qty_a = [x * a for x in ingredients[0][:-1]] qty_a = [x * a for x in ingredients[0][:-1]]
qty_b = [x * b for x in ingredients[1][:-1]] qty_b = [x * b for x in ingredients[1][:-1]]
props = [x + y if x + y > 0 else 0 for x, y in zip(qty_a, qty_b)] props = [max(0, x + y) for x, y in zip(qty_a, qty_b)]
score = reduce(mul, props) score = reduce(mul, props)
max_score = max(score, max_score) max_score = max(score, max_score)
return max_score return max_score
@@ -40,14 +40,14 @@ def example(ingredients):
def example_part2(ingredients): def example_part2(ingredients):
max_score = 0 max_score = 0
for a in range(0, 101): for a in range(101):
b = 100 - a b = 100 - a
qty_a = [x * a for x in ingredients[0]] qty_a = [x * a for x in ingredients[0]]
qty_b = [x * b for x in ingredients[1]] qty_b = [x * b for x in ingredients[1]]
# check calories == 500 # check calories == 500
if qty_a[-1] + qty_b[-1] != 500: if qty_a[-1] + qty_b[-1] != 500:
continue continue
props = [x + y if x + y > 0 else 0 for x, y in zip(qty_a, qty_b)] props = [max(0, x + y) for x, y in zip(qty_a, qty_b)]
score = reduce(mul, props[:-1]) score = reduce(mul, props[:-1])
max_score = max(score, max_score) max_score = max(score, max_score)
return max_score return max_score
@@ -61,7 +61,7 @@ def part1(ingredients):
qty_c = [x * c for x in ingredients[2][:-1]] qty_c = [x * c for x in ingredients[2][:-1]]
qty_d = [x * d for x in ingredients[3][:-1]] qty_d = [x * d for x in ingredients[3][:-1]]
props = [ props = [
x + y + z + w if x + y + z + w > 0 else 0 max(0, x + y + z + w)
for x, y, z, w in zip(qty_a, qty_b, qty_c, qty_d) for x, y, z, w in zip(qty_a, qty_b, qty_c, qty_d)
] ]
score = reduce(mul, props) score = reduce(mul, props)
@@ -77,7 +77,7 @@ def part2(ingredients):
qty_c = [x * c for x in ingredients[2]] qty_c = [x * c for x in ingredients[2]]
qty_d = [x * d for x in ingredients[3]] qty_d = [x * d for x in ingredients[3]]
props = [ props = [
x + y + z + w if x + y + z + w > 0 else 0 max(0, x + y + z + w)
for x, y, z, w in zip(qty_a, qty_b, qty_c, qty_d) for x, y, z, w in zip(qty_a, qty_b, qty_c, qty_d)
] ]
# check calories == 500 # check calories == 500
+2 -2
View File
@@ -17,7 +17,7 @@ def main(lines):
c = Counter(line) c = Counter(line)
total_twice += 1 if [k for k,v in c.items() if v == 2] != [] else 0 total_twice += 1 if [k for k,v in c.items() if v == 2] != [] else 0
total_thrice += 1 if [k for k,v in c.items() if v == 3] != [] else 0 total_thrice += 1 if [k for k,v in c.items() if v == 3] != [] else 0
print(f"Part 1: ", total_twice * total_thrice) print("Part 1: ", total_twice * total_thrice)
part2(lines) part2(lines)
@@ -26,5 +26,5 @@ if __name__ == "__main__":
import sys import sys
infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt" infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt"
with open(infile) as inp: with open(infile) as inp:
main([l.rstrip() for l in inp.readlines()]) main([l.rstrip() for l in inp])
+3 -4
View File
@@ -1,8 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import re import re
import itertools
from dataclasses import dataclass
from collections import defaultdict from collections import defaultdict
from dataclasses import dataclass
@dataclass @dataclass
@@ -35,7 +34,7 @@ def main(inp):
regions[x, y].add(id_) regions[x, y].add(id_)
total = sum(len(x) > 1 for x in regions.values()) total = sum(len(x) > 1 for x in regions.values())
print(f"Part 1: ", total) print("Part 1: ", total)
all_ids = set() all_ids = set()
overlapping_ids = set() overlapping_ids = set()
@@ -51,5 +50,5 @@ if __name__ == '__main__':
import sys import sys
infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt" infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt"
with open(infile) as inp: with open(infile) as inp:
main([l.rstrip() for l in inp.readlines()]) main([l.rstrip() for l in inp])
+1 -2
View File
@@ -1,7 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import re import re
from collections import defaultdict, Counter from collections import defaultdict
from pprint import pprint
def main(inp): def main(inp):
-1
View File
@@ -1,6 +1,5 @@
from collections import defaultdict, namedtuple from collections import defaultdict, namedtuple
Point = namedtuple('Point', ['x', 'y']) Point = namedtuple('Point', ['x', 'y'])
+1 -1
View File
@@ -84,5 +84,5 @@ if __name__ == '__main__':
import sys import sys
infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt" infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt"
with open(infile) as inp: with open(infile) as inp:
main([l.rstrip() for l in inp.readlines()]) main([l.rstrip() for l in inp])
+1 -3
View File
@@ -25,9 +25,7 @@ def test_part2():
expected = (2, 966, 50346) expected = (2, 966, 50346)
for i, inp in enumerate(inputs): for i, inp in enumerate(inputs):
result = calculate_fuel_iterative(inp) result = calculate_fuel_iterative(inp)
assert result == expected[i], "Result for {} should be {}, was {}".format( assert result == expected[i], f"Result for {inp} should be {expected[i]}, was {result}"
inp, expected[i], result
)
print("All tests passed for part 2.") print("All tests passed for part 2.")
+3 -4
View File
@@ -1,9 +1,8 @@
import time
import math
import cmath import cmath
from itertools import combinations import math
from collections import defaultdict
from bisect import insort from bisect import insort
from collections import defaultdict
from itertools import combinations
def dist(a, b): def dist(a, b):
+1 -1
View File
@@ -1,4 +1,4 @@
from adventofcode.intcode import interpret_intcode, Interpreter from adventofcode.intcode import Interpreter
def paint(program, initial_state): def paint(program, initial_state):
+1 -1
View File
@@ -39,7 +39,7 @@ def parse_map(output):
grid[x, y] = tile grid[x, y] = tile
paddle = next((k for k, v in grid.items() if v == 3), None) paddle = next((k for k, v in grid.items() if v == 3), None)
ball = next((k for k, v in grid.items() if v == 4), None) ball = next((k for k, v in grid.items() if v == 4), None)
bounds = (max(x for x, y in grid.keys()), max(y for x, y in grid.keys())) bounds = (max(x for x, y in grid), max(y for x, y in grid))
return grid, bounds, score, paddle, ball return grid, bounds, score, paddle, ball
+2 -6
View File
@@ -54,9 +54,7 @@ def tests():
expected = (6, 159, 135) expected = (6, 159, 135)
for i, inp in enumerate(inputs): for i, inp in enumerate(inputs):
result = find_min_distance(inp[0], inp[1]) result = find_min_distance(inp[0], inp[1])
assert result == expected[i], "Result for {} should be {}, was {}".format( assert result == expected[i], f"Result for {inp} should be {expected[i]}, was {result}"
inp, expected[i], result
)
# Part 2 # Part 2
# expected number of steps # expected number of steps
@@ -64,9 +62,7 @@ def tests():
print("All tests passed.") print("All tests passed.")
for i, inp in enumerate(inputs): for i, inp in enumerate(inputs):
result = find_least_steps(inp[0], inp[1]) result = find_least_steps(inp[0], inp[1])
assert result == expected_part2[i], "Result for {} should be {}, was {}".format( assert result == expected_part2[i], f"Result for {inp} should be {expected_part2[i]}, was {result}"
inp, expected_part2[i], result
)
if __name__ == "__main__": if __name__ == "__main__":
tests() tests()
+2 -3
View File
@@ -1,9 +1,8 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
from collections import namedtuple
from enum import Enum
import logging import logging
from enum import Enum
logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.WARN) logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.WARNING)
def get_nth_digit(n, number): def get_nth_digit(n, number):
-1
View File
@@ -93,7 +93,6 @@ class HaltInstruction(Instruction):
def execute(self, intcode, arguments): def execute(self, intcode, arguments):
intcode.halted = True intcode.halted = True
return None
class Argument: class Argument:
-1
View File
@@ -1,4 +1,3 @@
from collections import defaultdict
def path(graph, start, goal): def path(graph, start, goal):
+3 -3
View File
@@ -1,7 +1,7 @@
import sys
from pathlib import Path
from itertools import cycle, permutations from itertools import cycle, permutations
from adventofcode.intcode import interpret_intcode, Interpreter
from adventofcode.intcode import Interpreter, interpret_intcode
def main(inp): def main(inp):
mem = list(map(int, inp.readline().rstrip().split(","))) mem = list(map(int, inp.readline().rstrip().split(",")))
+1 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from itertools import count, takewhile from itertools import takewhile
directions = ( directions = (
(-1, -1), (-1, -1),
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from collections import defaultdict
from array import array from array import array
from collections import defaultdict
def main(initial_suite, max_iteration): def main(initial_suite, max_iteration):
+1 -3
View File
@@ -29,9 +29,7 @@ def check_passeport(passeport, run_validators=False):
] ]
for field, validator in fields: for field, validator in fields:
value = passeport.get(field) value = passeport.get(field)
if value is None: if value is None or run_validators and not validator(value):
return False
elif run_validators and not validator(value):
return False return False
return True return True
-1
View File
@@ -1,5 +1,4 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
from itertools import product
from bisect import bisect from bisect import bisect
+1
View File
@@ -1,6 +1,7 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
from day5 import * from day5 import *
def tests(): def tests():
inputs = { inputs = {
"FBFBBFFRLR": (44, 5, 357), "FBFBBFFRLR": (44, 5, 357),
+1 -1
View File
@@ -58,7 +58,7 @@ def part2(inp):
def main(input_file): def main(input_file):
with open(input_file) as f: with open(input_file) as f:
entries = [x.rstrip() for x in f.readlines()] entries = [x.rstrip() for x in f]
part1(entries) part1(entries)
part2(entries) part2(entries)
+2 -1
View File
@@ -1,5 +1,6 @@
from dataclasses import dataclass
from collections import deque from collections import deque
from dataclasses import dataclass
@dataclass @dataclass
class BingoItem: class BingoItem:
+1
View File
@@ -1,5 +1,6 @@
from collections import defaultdict from collections import defaultdict
def main(infile): def main(infile):
points = defaultdict(int) points = defaultdict(int)
with open(infile) as f: with open(infile) as f:
+2 -1
View File
@@ -1,4 +1,5 @@
from collections import defaultdict, Counter from collections import Counter, defaultdict
def calculate_fishes(inp, days): def calculate_fishes(inp, days):
fishes = Counter(inp) fishes = Counter(inp)
+1
View File
@@ -1,5 +1,6 @@
from collections import OrderedDict from collections import OrderedDict
def part1(crabs): def part1(crabs):
moves = OrderedDict() moves = OrderedDict()
for pos in range(min(crabs), max(crabs) + 1): for pos in range(min(crabs), max(crabs) + 1):
+1 -1
View File
@@ -1,5 +1,5 @@
from itertools import zip_longest
from functools import reduce from functools import reduce
from itertools import zip_longest
from operator import and_ from operator import and_
+6 -7
View File
@@ -1,6 +1,5 @@
from typing import Dict, List, Set, Tuple
from dataclasses import dataclass
from collections import defaultdict from collections import defaultdict
from dataclasses import dataclass
from enum import Enum from enum import Enum
@@ -42,7 +41,7 @@ PIPES = {
PIPES_REVERSE_LOOKUP = {v: k for k,v in PIPES.items()} PIPES_REVERSE_LOOKUP = {v: k for k,v in PIPES.items()}
def find_start_position(grid: List[str]) -> Vec2d: def find_start_position(grid: list[str]) -> Vec2d:
for y, row in enumerate(grid): for y, row in enumerate(grid):
for x, c in enumerate(row): for x, c in enumerate(row):
if c == "S": if c == "S":
@@ -50,7 +49,7 @@ def find_start_position(grid: List[str]) -> Vec2d:
raise RuntimeError("The start position was not found") raise RuntimeError("The start position was not found")
def update_start_symbol(grid: List[str], start_pos: Vec2d): def update_start_symbol(grid: list[str], start_pos: Vec2d):
""" """
Updates the map by replacing the start symbol "S" with its actual corresponding pipe Updates the map by replacing the start symbol "S" with its actual corresponding pipe
""" """
@@ -82,7 +81,7 @@ def update_start_symbol(grid: List[str], start_pos: Vec2d):
grid[start_pos.y] = grid[start_pos.y].replace("S", pipe) grid[start_pos.y] = grid[start_pos.y].replace("S", pipe)
def parse_graph(grid: List[str]) -> Dict[Vec2d, List[Vec2d]]: def parse_graph(grid: list[str]) -> dict[Vec2d, list[Vec2d]]:
graph = defaultdict(list) graph = defaultdict(list)
for y, row in enumerate(grid): for y, row in enumerate(grid):
@@ -95,7 +94,7 @@ def parse_graph(grid: List[str]) -> Dict[Vec2d, List[Vec2d]]:
return graph return graph
def traverse_graph(graph, start_pos) -> Tuple[int, Set[Vec2d]]: def traverse_graph(graph, start_pos) -> tuple[int, set[Vec2d]]:
""" """
traverse the graph using BFS, return the path and the traverse the graph using BFS, return the path and the
find the length of the longest path in the graph find the length of the longest path in the graph
@@ -154,5 +153,5 @@ if __name__ == "__main__":
infile = sys.argv[1] infile = sys.argv[1]
with open(infile) as f: with open(infile) as f:
lines = [l.rstrip() for l in f.readlines()] lines = [l.rstrip() for l in f]
main(lines) main(lines)
+9 -9
View File
@@ -1,9 +1,9 @@
from typing import Tuple, List, Set
from dataclasses import dataclass from dataclasses import dataclass
@dataclass(frozen=True) @dataclass(frozen=True)
class Item: class Item:
pos: Tuple[int, int] pos: tuple[int, int]
symbol: str symbol: str
@@ -12,8 +12,8 @@ def browse_schema(schema):
buf = [] buf = []
max_row, max_col = len(schema), len(schema[0]) max_row, max_col = len(schema), len(schema[0])
symbols: List[Tuple[Item, Set[Item]]] = [] symbols: list[tuple[Item, set[Item]]] = []
numbers: List[Item] = [] numbers: list[Item] = []
for y in range(max_row): for y in range(max_row):
for x in range(max_col): for x in range(max_col):
@@ -61,13 +61,13 @@ def part2(symbols, numbers):
def is_engine_part(neighbors: List[Item]) -> bool: def is_engine_part(neighbors: list[Item]) -> bool:
# get list of symbols (not '.', \n or a number) # get list of symbols (not '.', \n or a number)
symbols = filter(lambda x: not x.symbol.isnumeric() and not x.symbol in (".", "\n"), neighbors) symbols = filter(lambda x: not x.symbol.isnumeric() and not x.symbol in (".", "\n"), neighbors)
return next(symbols, None) is not None return next(symbols, None) is not None
def get_neighbors(pos: Tuple[int, int], length: int, schema: List[List[str]]) -> List[Item]: def get_neighbors(pos: tuple[int, int], length: int, schema: list[list[str]]) -> list[Item]:
x, y = pos x, y = pos
start_x = x - length start_x = x - length
neighbors = [get_neighbors_of((x, y), schema) for x in range(start_x, x)] neighbors = [get_neighbors_of((x, y), schema) for x in range(start_x, x)]
@@ -75,10 +75,10 @@ def get_neighbors(pos: Tuple[int, int], length: int, schema: List[List[str]]) -
return neighbors return neighbors
def get_neighbors_of(pos: Tuple[int, int], schema: List[List[str]]) -> List[Item]: def get_neighbors_of(pos: tuple[int, int], schema: list[list[str]]) -> list[Item]:
max_row, max_col = len(schema), len(schema[0]) max_row, max_col = len(schema), len(schema[0])
x, y = pos x, y = pos
neighbors: List[Item] = [] neighbors: list[Item] = []
# top # top
if y-1 >= 0: if y-1 >= 0:
@@ -112,5 +112,5 @@ if __name__ == "__main__":
import sys import sys
infile = sys.argv[1] infile = sys.argv[1]
with open(infile) as f: with open(infile) as f:
schema = [[c for c in line] for line in f.readlines()] schema = [[c for c in line] for line in f]
browse_schema(schema) browse_schema(schema)
+2 -3
View File
@@ -27,8 +27,7 @@ def part2(sections):
print(f"calculate_for_subseeds(subseeds len={len(subseeds)})") print(f"calculate_for_subseeds(subseeds len={len(subseeds)})")
res = calculate_for_subseeds(subseeds, sections) res = calculate_for_subseeds(subseeds, sections)
mini = min(res) mini = min(res)
if mini < min_seed: min_seed = min(min_seed, mini)
min_seed = mini
print(f"Part 2 {min_seed}") print(f"Part 2 {min_seed}")
@@ -58,8 +57,8 @@ def parse_input(infile):
if __name__ == "__main__": if __name__ == "__main__":
import sys
import os import os
import sys
SCRIPTPATH = os.path.dirname(os.path.realpath(__file__)) SCRIPTPATH = os.path.dirname(os.path.realpath(__file__))
infile = next(iter(sys.argv[1:]), None) infile = next(iter(sys.argv[1:]), None)
+1 -1
View File
@@ -10,7 +10,7 @@ def calculate_wins(data):
total = 1 total = 1
for time, record in data: for time, record in data:
ways = 0 ways = 0
for n in range(0, time+1): for n in range(time+1):
speed = n speed = n
distance = (time-n) * speed distance = (time-n) * speed
if distance > record: if distance > record:
+3 -2
View File
@@ -1,7 +1,8 @@
import re
import math import math
import re
from itertools import cycle from itertools import cycle
def parse_input(infile): def parse_input(infile):
with open(infile) as f: with open(infile) as f:
content = f.read().rstrip() content = f.read().rstrip()
@@ -63,8 +64,8 @@ def part2(directions, nodes):
if __name__ == "__main__": if __name__ == "__main__":
import sys
import os import os
import sys
SCRIPTPATH = os.path.dirname(os.path.realpath(__file__)) SCRIPTPATH = os.path.dirname(os.path.realpath(__file__))
infile = sys.argv[1] if len(sys.argv) == 2 else "example.txt" infile = sys.argv[1] if len(sys.argv) == 2 else "example.txt"
+2 -2
View File
@@ -1,6 +1,6 @@
def parse_input(infile): def parse_input(infile):
with open(infile) as f: with open(infile) as f:
return [[int(x) for x in l.strip().split()] for l in f.readlines()] return [[int(x) for x in l.strip().split()] for l in f]
def process_line(line): def process_line(line):
@@ -25,8 +25,8 @@ def solve(data):
if __name__ == "__main__": if __name__ == "__main__":
import sys
import os import os
import sys
SCRIPTPATH = os.path.dirname(os.path.realpath(__file__)) SCRIPTPATH = os.path.dirname(os.path.realpath(__file__))
infile = sys.argv[1] if len(sys.argv) == 2 else "example.txt" infile = sys.argv[1] if len(sys.argv) == 2 else "example.txt"
data = parse_input(os.path.join(SCRIPTPATH, infile)) data = parse_input(os.path.join(SCRIPTPATH, infile))
+1 -1
View File
@@ -2,7 +2,7 @@ from collections import Counter
def main(lines): def main(lines):
firsts, seconds = list(sorted(x[0] for x in lines)), list(sorted(x[1] for x in lines)) firsts, seconds = sorted(x[0] for x in lines), sorted(x[1] for x in lines)
total = sum(abs(a - b) for (a, b) in zip(firsts, seconds)) total = sum(abs(a - b) for (a, b) in zip(firsts, seconds))
print("Part 1: ", total) print("Part 1: ", total)
+1 -1
View File
@@ -63,6 +63,6 @@ if __name__ == "__main__":
import sys import sys
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
with open(infile) as f: with open(infile) as f:
grid = [list(map(int, list(l.rstrip()))) for l in f.readlines()] grid = [list(map(int, list(l.rstrip()))) for l in f]
main(grid) main(grid)
+1
View File
@@ -1,5 +1,6 @@
from collections import Counter from collections import Counter
def main(data): def main(data):
part1 = run(data, 25) part1 = run(data, 25)
print("Part 1: ", part1) print("Part 1: ", part1)
+1 -2
View File
@@ -1,5 +1,4 @@
from dataclasses import dataclass from dataclasses import dataclass
from collections import defaultdict
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -78,6 +77,6 @@ if __name__ == "__main__":
import sys import sys
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
with open(infile) as f: with open(infile) as f:
grid = [l.rstrip() for l in f.readlines()] grid = [l.rstrip() for l in f]
main(grid) main(grid)
+1 -1
View File
@@ -1,5 +1,5 @@
from math import prod
from collections import Counter from collections import Counter
from math import prod
def parse_bots(lines): def parse_bots(lines):
+2 -2
View File
@@ -9,7 +9,7 @@ DIRECTIONS = {
def find_start_pos(grid): def find_start_pos(grid):
for y, row in enumerate(grid): for y, row in enumerate(grid):
for x, _ in enumerate(row): for x, _ in enumerate(row):
if grid[y][x] == "@": if row[x] == "@":
return complex(x, y) return complex(x, y)
@@ -69,7 +69,7 @@ def calculate_gps_coords(grid):
total = 0 total = 0
for y, row in enumerate(grid): for y, row in enumerate(grid):
for x, _ in enumerate(row): for x, _ in enumerate(row):
if grid[y][x] == "O": if row[x] == "O":
total += 100*y + x total += 100*y + x
return total return total
+3 -4
View File
@@ -1,7 +1,6 @@
from dataclasses import dataclass from dataclasses import dataclass
from heapq import heappop, heappush from heapq import heappop, heappush
DIRECTIONS = { DIRECTIONS = {
">": 1 + 0j, # EAST ">": 1 + 0j, # EAST
"v": 0 + 1j, # SOUTH "v": 0 + 1j, # SOUTH
@@ -27,9 +26,9 @@ def find_start_and_goal(grid):
start, goal = None, None start, goal = None, None
for y, row in enumerate(grid): for y, row in enumerate(grid):
for x, _ in enumerate(row): for x, _ in enumerate(row):
if grid[y][x] == "S": if row[x] == "S":
start = complex(x, y) start = complex(x, y)
elif grid[y][x] == "E": elif row[x] == "E":
goal = complex(x, y) goal = complex(x, y)
return start, goal return start, goal
@@ -112,6 +111,6 @@ if __name__ == "__main__":
import sys import sys
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
with open(infile) as f: with open(infile) as f:
grid = [list(l.rstrip()) for l in f.readlines()] grid = [list(l.rstrip()) for l in f]
main(grid) main(grid)
+1 -2
View File
@@ -1,6 +1,5 @@
from dataclasses import dataclass from dataclasses import dataclass
from heapq import heappush, heappop from heapq import heappop, heappush
DIRECTIONS = ( DIRECTIONS = (
1 + 0j, # EAST 1 + 0j, # EAST
+5 -5
View File
@@ -47,16 +47,16 @@ def part2(grid):
if grid[y+1][x+1] != "A": # center letter is always "A" if grid[y+1][x+1] != "A": # center letter is always "A"
continue continue
# M.S / .A. / M.S # M.S / .A. / M.S
if grid[y][x] == "M" and grid[y][x+2] == "S" and grid[y+2][x] == "M" and grid[y+2][x+2] == "S": if row[x] == "M" and row[x+2] == "S" and grid[y+2][x] == "M" and grid[y+2][x+2] == "S":
count += 1 count += 1
# M.M / .A. / S.S # M.M / .A. / S.S
if grid[y][x] == "M" and grid[y][x+2] == "M" and grid[y+2][x] == "S" and grid[y+2][x+2] == "S": if row[x] == "M" and row[x+2] == "M" and grid[y+2][x] == "S" and grid[y+2][x+2] == "S":
count += 1 count += 1
# S.M / .A. / S.M # S.M / .A. / S.M
if grid[y][x] == "S" and grid[y][x+2] == "M" and grid[y+2][x] == "S" and grid[y+2][x+2] == "M": if row[x] == "S" and row[x+2] == "M" and grid[y+2][x] == "S" and grid[y+2][x+2] == "M":
count += 1 count += 1
# S.S / .A. / M.M # S.S / .A. / M.M
if grid[y][x] == "S" and grid[y][x+2] == "S" and grid[y+2][x] == "M" and grid[y+2][x+2] == "M": if row[x] == "S" and row[x+2] == "S" and grid[y+2][x] == "M" and grid[y+2][x+2] == "M":
count += 1 count += 1
print("Part 2: ", count) print("Part 2: ", count)
@@ -66,7 +66,7 @@ if __name__ == "__main__":
import sys import sys
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
with open(infile) as f: with open(infile) as f:
grid = [l.rstrip() for l in f.readlines()] grid = [l.rstrip() for l in f]
part1(grid) part1(grid)
part2(grid) part2(grid)
-1
View File
@@ -1,4 +1,3 @@
from collections import defaultdict
from itertools import pairwise from itertools import pairwise
+2 -3
View File
@@ -1,6 +1,5 @@
from itertools import cycle
from dataclasses import dataclass from dataclasses import dataclass
from pprint import pprint from itertools import cycle
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -75,6 +74,6 @@ if __name__ == "__main__":
import sys import sys
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
with open(infile) as f: with open(infile) as f:
grid = [list(l.rstrip()) for l in f.readlines()] grid = [list(l.rstrip()) for l in f]
main(grid) main(grid)
+1 -1
View File
@@ -30,7 +30,7 @@ if __name__ == "__main__":
import sys import sys
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
with open(infile) as f: with open(infile) as f:
data = [l.rstrip().split(": ") for l in f.readlines()] data = [l.rstrip().split(": ") for l in f]
data = [(int(a), tuple(map(int, b.split(" ")))) for a, b in data] data = [(int(a), tuple(map(int, b.split(" ")))) for a, b in data]
main(data) main(data)
+1 -3
View File
@@ -1,6 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import fileinput import fileinput
from sys import argv
def area(a, b): def area(a, b):
@@ -38,8 +37,7 @@ def generate_ppm(inp, scale=100):
with open("test.ppm", "w") as f: with open("test.ppm", "w") as f:
f.write(f"P3\n{width} {height}\n255\n") f.write(f"P3\n{width} {height}\n255\n")
for row in arr: for row in arr:
for cell in row: f.writelines(f"{cell * 255} 0 0 " for cell in row)
f.write(f"{cell * 255} 0 0 ")
f.write("\n") f.write("\n")
print("PPM file written to test.ppm") print("PPM file written to test.ppm")
+1 -3
View File
@@ -1,4 +1,3 @@
#!/usr/bin/env python3
import os import os
import re import re
import subprocess import subprocess
@@ -10,8 +9,7 @@ from pathlib import Path
MIN_YEAR = 2015 MIN_YEAR = 2015
MAX_YEAR = 2025 MAX_YEAR = 2025
ROOTPATH = Path(os.path.dirname(os.path.realpath(__file__))) ROOTPATH = Path(os.path.dirname(os.path.realpath(__file__)))
TEMPLATE = """#!/usr/bin/env python3 TEMPLATE = """import fileinput
import fileinput
def main(inp): def main(inp):
+1 -1
View File
@@ -1 +1 @@
from .intcode import interpret_intcode, Interpreter, Operation, Mode from .intcode import Interpreter, Mode, Operation, interpret_intcode
+2 -4
View File
@@ -1,8 +1,7 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
from collections import defaultdict
from enum import Enum
import logging import logging
import os import os
from enum import Enum
loglevel = (os.getenv("LOGLEVEL") or "WARN").upper() loglevel = (os.getenv("LOGLEVEL") or "WARN").upper()
logging.basicConfig(format="%(levelname)s:%(message)s", level=loglevel) logging.basicConfig(format="%(levelname)s:%(message)s", level=loglevel)
@@ -140,7 +139,7 @@ class Instruction:
match self.modes[offset - 1]: match self.modes[offset - 1]:
case Mode.POSITION: return value case Mode.POSITION: return value
case Mode.RELATIVE: return value + self.base case Mode.RELATIVE: return value + self.base
case _: raise ValueError(f"{self.modes[i]}") case _: raise ValueError(f"{self.modes[offset - 1]}")
def _get_parameters(self): def _get_parameters(self):
first = self._get_value(1) first = self._get_value(1)
@@ -191,4 +190,3 @@ def interpret_intcode(program, stdin=[]):
interpreter = Interpreter(program, stdin) interpreter = Interpreter(program, stdin)
interpreter.interpret(break_on_output=False) interpreter.interpret(break_on_output=False)
return interpreter return interpreter
+1 -7
View File
@@ -1,5 +1,4 @@
# Run with pytest # Run with pytest
import logging
from intcode import * from intcode import *
@@ -82,18 +81,13 @@ def test_day9_base():
assert interpreter.base == 2025 assert interpreter.base == 2025
def test_day9_relative():
program = [109,6,21001,9,25,1,104,0,99,49]
ret = interpret_intcode(program)
assert ret.stdout == [74]
def test_day9_quine(): def test_day9_quine():
quine = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99] quine = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]
run_test(quine, expected_out=quine) run_test(quine, expected_out=quine)
def test_day9_relative(): def test_day9_relative():
run_test([109,6,21001,9,25,1,104,0,99,49], expected_out=[74])
run_test([109, -1, 4, 1, 99], expected_out=[-1]) run_test([109, -1, 4, 1, 99], expected_out=[-1])
run_test([109, -1, 104, 1, 99], expected_out=[1]) run_test([109, -1, 104, 1, 99], expected_out=[1])
run_test([109, -1, 204, 1, 99], expected_out=[109]) run_test([109, -1, 204, 1, 99], expected_out=[109])
Generated
+8
View File
@@ -0,0 +1,8 @@
version = 1
revision = 3
requires-python = ">=3.11"
[[package]]
name = "adventofcode"
version = "1.0.0"
source = { editable = "." }