mirror of
https://github.com/thib8956/advent-of-code.git
synced 2026-11-27 00:46:34 +00:00
fix lint
This commit is contained in:
1 parent
0232b9326d
commit
5c3fb89870
50 files changed
+97
-117
No files matched your search
@@ -27,12 +27,12 @@ def example(ingredients):
|
||||
# for example input, two ingredients such that
|
||||
# a + b = 100 with a and b >= 0
|
||||
max_score = 0
|
||||
for a in range(0, 101):
|
||||
for a in range(101):
|
||||
b = 100 - a
|
||||
# ignore last property (calories)
|
||||
qty_a = [x * a for x in ingredients[0][:-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)
|
||||
max_score = max(score, max_score)
|
||||
return max_score
|
||||
@@ -40,14 +40,14 @@ def example(ingredients):
|
||||
|
||||
def example_part2(ingredients):
|
||||
max_score = 0
|
||||
for a in range(0, 101):
|
||||
for a in range(101):
|
||||
b = 100 - a
|
||||
qty_a = [x * a for x in ingredients[0]]
|
||||
qty_b = [x * b for x in ingredients[1]]
|
||||
# check calories == 500
|
||||
if qty_a[-1] + qty_b[-1] != 500:
|
||||
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])
|
||||
max_score = max(score, max_score)
|
||||
return max_score
|
||||
@@ -61,7 +61,7 @@ def part1(ingredients):
|
||||
qty_c = [x * c for x in ingredients[2][:-1]]
|
||||
qty_d = [x * d for x in ingredients[3][:-1]]
|
||||
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)
|
||||
]
|
||||
score = reduce(mul, props)
|
||||
@@ -77,7 +77,7 @@ def part2(ingredients):
|
||||
qty_c = [x * c for x in ingredients[2]]
|
||||
qty_d = [x * d for x in ingredients[3]]
|
||||
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)
|
||||
]
|
||||
# check calories == 500
|
||||
|
||||
@@ -17,7 +17,7 @@ def main(lines):
|
||||
c = Counter(line)
|
||||
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
|
||||
print(f"Part 1: ", total_twice * total_thrice)
|
||||
print("Part 1: ", total_twice * total_thrice)
|
||||
|
||||
part2(lines)
|
||||
|
||||
@@ -26,5 +26,5 @@ if __name__ == "__main__":
|
||||
import sys
|
||||
infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt"
|
||||
with open(infile) as inp:
|
||||
main([l.rstrip() for l in inp.readlines()])
|
||||
main([l.rstrip() for l in inp])
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
import itertools
|
||||
from dataclasses import dataclass
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -35,7 +34,7 @@ def main(inp):
|
||||
regions[x, y].add(id_)
|
||||
|
||||
total = sum(len(x) > 1 for x in regions.values())
|
||||
print(f"Part 1: ", total)
|
||||
print("Part 1: ", total)
|
||||
|
||||
all_ids = set()
|
||||
overlapping_ids = set()
|
||||
@@ -51,5 +50,5 @@ if __name__ == '__main__':
|
||||
import sys
|
||||
infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt"
|
||||
with open(infile) as inp:
|
||||
main([l.rstrip() for l in inp.readlines()])
|
||||
main([l.rstrip() for l in inp])
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
from collections import defaultdict, Counter
|
||||
from pprint import pprint
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def main(inp):
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from collections import defaultdict, namedtuple
|
||||
|
||||
|
||||
Point = namedtuple('Point', ['x', 'y'])
|
||||
|
||||
|
||||
|
||||
@@ -84,5 +84,5 @@ if __name__ == '__main__':
|
||||
import sys
|
||||
infile = sys.argv[1] if len(sys.argv) > 1 else "example.txt"
|
||||
with open(infile) as inp:
|
||||
main([l.rstrip() for l in inp.readlines()])
|
||||
main([l.rstrip() for l in inp])
|
||||
|
||||
@@ -25,9 +25,7 @@ def test_part2():
|
||||
expected = (2, 966, 50346)
|
||||
for i, inp in enumerate(inputs):
|
||||
result = calculate_fuel_iterative(inp)
|
||||
assert result == expected[i], "Result for {} should be {}, was {}".format(
|
||||
inp, expected[i], result
|
||||
)
|
||||
assert result == expected[i], f"Result for {inp} should be {expected[i]}, was {result}"
|
||||
print("All tests passed for part 2.")
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import time
|
||||
import math
|
||||
import cmath
|
||||
from itertools import combinations
|
||||
from collections import defaultdict
|
||||
import math
|
||||
from bisect import insort
|
||||
from collections import defaultdict
|
||||
from itertools import combinations
|
||||
|
||||
|
||||
def dist(a, b):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from adventofcode.intcode import interpret_intcode, Interpreter
|
||||
from adventofcode.intcode import Interpreter
|
||||
|
||||
|
||||
def paint(program, initial_state):
|
||||
|
||||
@@ -39,7 +39,7 @@ def parse_map(output):
|
||||
grid[x, y] = tile
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -54,9 +54,7 @@ def tests():
|
||||
expected = (6, 159, 135)
|
||||
for i, inp in enumerate(inputs):
|
||||
result = find_min_distance(inp[0], inp[1])
|
||||
assert result == expected[i], "Result for {} should be {}, was {}".format(
|
||||
inp, expected[i], result
|
||||
)
|
||||
assert result == expected[i], f"Result for {inp} should be {expected[i]}, was {result}"
|
||||
|
||||
# Part 2
|
||||
# expected number of steps
|
||||
@@ -64,9 +62,7 @@ def tests():
|
||||
print("All tests passed.")
|
||||
for i, inp in enumerate(inputs):
|
||||
result = find_least_steps(inp[0], inp[1])
|
||||
assert result == expected_part2[i], "Result for {} should be {}, was {}".format(
|
||||
inp, expected_part2[i], result
|
||||
)
|
||||
assert result == expected_part2[i], f"Result for {inp} should be {expected_part2[i]}, was {result}"
|
||||
|
||||
if __name__ == "__main__":
|
||||
tests()
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
#! /usr/bin/env python3
|
||||
from collections import namedtuple
|
||||
from enum import Enum
|
||||
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):
|
||||
|
||||
@@ -93,7 +93,6 @@ class HaltInstruction(Instruction):
|
||||
|
||||
def execute(self, intcode, arguments):
|
||||
intcode.halted = True
|
||||
return None
|
||||
|
||||
|
||||
class Argument:
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def path(graph, start, goal):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from itertools import cycle, permutations
|
||||
from adventofcode.intcode import interpret_intcode, Interpreter
|
||||
|
||||
from adventofcode.intcode import Interpreter, interpret_intcode
|
||||
|
||||
|
||||
def main(inp):
|
||||
mem = list(map(int, inp.readline().rstrip().split(",")))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
from itertools import count, takewhile
|
||||
from itertools import takewhile
|
||||
|
||||
directions = (
|
||||
(-1, -1),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
from collections import defaultdict
|
||||
from array import array
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def main(initial_suite, max_iteration):
|
||||
|
||||
@@ -29,9 +29,7 @@ def check_passeport(passeport, run_validators=False):
|
||||
]
|
||||
for field, validator in fields:
|
||||
value = passeport.get(field)
|
||||
if value is None:
|
||||
return False
|
||||
elif run_validators and not validator(value):
|
||||
if value is None or run_validators and not validator(value):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#! /usr/bin/env python3
|
||||
from itertools import product
|
||||
from bisect import bisect
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#! /usr/bin/env python3
|
||||
from day5 import *
|
||||
|
||||
|
||||
def tests():
|
||||
inputs = {
|
||||
"FBFBBFFRLR": (44, 5, 357),
|
||||
|
||||
@@ -58,7 +58,7 @@ def part2(inp):
|
||||
|
||||
def main(input_file):
|
||||
with open(input_file) as f:
|
||||
entries = [x.rstrip() for x in f.readlines()]
|
||||
entries = [x.rstrip() for x in f]
|
||||
part1(entries)
|
||||
part2(entries)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from dataclasses import dataclass
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class BingoItem:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def main(infile):
|
||||
points = defaultdict(int)
|
||||
with open(infile) as f:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from collections import defaultdict, Counter
|
||||
from collections import Counter, defaultdict
|
||||
|
||||
|
||||
def calculate_fishes(inp, days):
|
||||
fishes = Counter(inp)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from collections import OrderedDict
|
||||
|
||||
|
||||
def part1(crabs):
|
||||
moves = OrderedDict()
|
||||
for pos in range(min(crabs), max(crabs) + 1):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from itertools import zip_longest
|
||||
from functools import reduce
|
||||
from itertools import zip_longest
|
||||
from operator import and_
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from typing import Dict, List, Set, Tuple
|
||||
from dataclasses import dataclass
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
|
||||
@@ -42,7 +41,7 @@ PIPES = {
|
||||
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 x, c in enumerate(row):
|
||||
if c == "S":
|
||||
@@ -50,7 +49,7 @@ def find_start_position(grid: List[str]) -> Vec2d:
|
||||
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
|
||||
"""
|
||||
@@ -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)
|
||||
|
||||
|
||||
def parse_graph(grid: List[str]) -> Dict[Vec2d, List[Vec2d]]:
|
||||
def parse_graph(grid: list[str]) -> dict[Vec2d, list[Vec2d]]:
|
||||
graph = defaultdict(list)
|
||||
|
||||
for y, row in enumerate(grid):
|
||||
@@ -95,7 +94,7 @@ def parse_graph(grid: List[str]) -> Dict[Vec2d, List[Vec2d]]:
|
||||
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
|
||||
find the length of the longest path in the graph
|
||||
@@ -154,5 +153,5 @@ if __name__ == "__main__":
|
||||
infile = sys.argv[1]
|
||||
|
||||
with open(infile) as f:
|
||||
lines = [l.rstrip() for l in f.readlines()]
|
||||
lines = [l.rstrip() for l in f]
|
||||
main(lines)
|
||||
@@ -1,9 +1,9 @@
|
||||
from typing import Tuple, List, Set
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Item:
|
||||
pos: Tuple[int, int]
|
||||
pos: tuple[int, int]
|
||||
symbol: str
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ def browse_schema(schema):
|
||||
buf = []
|
||||
max_row, max_col = len(schema), len(schema[0])
|
||||
|
||||
symbols: List[Tuple[Item, Set[Item]]] = []
|
||||
numbers: List[Item] = []
|
||||
symbols: list[tuple[Item, set[Item]]] = []
|
||||
numbers: list[Item] = []
|
||||
|
||||
for y in range(max_row):
|
||||
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)
|
||||
symbols = filter(lambda x: not x.symbol.isnumeric() and not x.symbol in (".", "\n"), neighbors)
|
||||
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
|
||||
start_x = x - length
|
||||
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
|
||||
|
||||
|
||||
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])
|
||||
x, y = pos
|
||||
neighbors: List[Item] = []
|
||||
neighbors: list[Item] = []
|
||||
|
||||
# top
|
||||
if y-1 >= 0:
|
||||
@@ -112,5 +112,5 @@ if __name__ == "__main__":
|
||||
import sys
|
||||
infile = sys.argv[1]
|
||||
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)
|
||||
@@ -27,8 +27,7 @@ def part2(sections):
|
||||
print(f"calculate_for_subseeds(subseeds len={len(subseeds)})")
|
||||
res = calculate_for_subseeds(subseeds, sections)
|
||||
mini = min(res)
|
||||
if mini < min_seed:
|
||||
min_seed = mini
|
||||
min_seed = min(min_seed, mini)
|
||||
|
||||
print(f"Part 2 {min_seed}")
|
||||
|
||||
@@ -58,8 +57,8 @@ def parse_input(infile):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
import os
|
||||
import sys
|
||||
SCRIPTPATH = os.path.dirname(os.path.realpath(__file__))
|
||||
|
||||
infile = next(iter(sys.argv[1:]), None)
|
||||
|
||||
@@ -10,7 +10,7 @@ def calculate_wins(data):
|
||||
total = 1
|
||||
for time, record in data:
|
||||
ways = 0
|
||||
for n in range(0, time+1):
|
||||
for n in range(time+1):
|
||||
speed = n
|
||||
distance = (time-n) * speed
|
||||
if distance > record:
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import re
|
||||
import math
|
||||
import re
|
||||
from itertools import cycle
|
||||
|
||||
|
||||
def parse_input(infile):
|
||||
with open(infile) as f:
|
||||
content = f.read().rstrip()
|
||||
@@ -63,8 +64,8 @@ def part2(directions, nodes):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
import os
|
||||
import sys
|
||||
SCRIPTPATH = os.path.dirname(os.path.realpath(__file__))
|
||||
infile = sys.argv[1] if len(sys.argv) == 2 else "example.txt"
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
def parse_input(infile):
|
||||
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):
|
||||
@@ -25,8 +25,8 @@ def solve(data):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
import os
|
||||
import sys
|
||||
SCRIPTPATH = os.path.dirname(os.path.realpath(__file__))
|
||||
infile = sys.argv[1] if len(sys.argv) == 2 else "example.txt"
|
||||
data = parse_input(os.path.join(SCRIPTPATH, infile))
|
||||
|
||||
@@ -2,7 +2,7 @@ from collections import Counter
|
||||
|
||||
|
||||
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))
|
||||
print("Part 1: ", total)
|
||||
|
||||
|
||||
@@ -63,6 +63,6 @@ if __name__ == "__main__":
|
||||
import sys
|
||||
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
|
||||
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)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from collections import Counter
|
||||
|
||||
|
||||
def main(data):
|
||||
part1 = run(data, 25)
|
||||
print("Part 1: ", part1)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from dataclasses import dataclass
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -78,6 +77,6 @@ if __name__ == "__main__":
|
||||
import sys
|
||||
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
|
||||
with open(infile) as f:
|
||||
grid = [l.rstrip() for l in f.readlines()]
|
||||
grid = [l.rstrip() for l in f]
|
||||
main(grid)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from math import prod
|
||||
from collections import Counter
|
||||
from math import prod
|
||||
|
||||
|
||||
def parse_bots(lines):
|
||||
|
||||
@@ -9,7 +9,7 @@ DIRECTIONS = {
|
||||
def find_start_pos(grid):
|
||||
for y, row in enumerate(grid):
|
||||
for x, _ in enumerate(row):
|
||||
if grid[y][x] == "@":
|
||||
if row[x] == "@":
|
||||
return complex(x, y)
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ def calculate_gps_coords(grid):
|
||||
total = 0
|
||||
for y, row in enumerate(grid):
|
||||
for x, _ in enumerate(row):
|
||||
if grid[y][x] == "O":
|
||||
if row[x] == "O":
|
||||
total += 100*y + x
|
||||
return total
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from dataclasses import dataclass
|
||||
from heapq import heappop, heappush
|
||||
|
||||
|
||||
DIRECTIONS = {
|
||||
">": 1 + 0j, # EAST
|
||||
"v": 0 + 1j, # SOUTH
|
||||
@@ -27,9 +26,9 @@ def find_start_and_goal(grid):
|
||||
start, goal = None, None
|
||||
for y, row in enumerate(grid):
|
||||
for x, _ in enumerate(row):
|
||||
if grid[y][x] == "S":
|
||||
if row[x] == "S":
|
||||
start = complex(x, y)
|
||||
elif grid[y][x] == "E":
|
||||
elif row[x] == "E":
|
||||
goal = complex(x, y)
|
||||
return start, goal
|
||||
|
||||
@@ -112,6 +111,6 @@ if __name__ == "__main__":
|
||||
import sys
|
||||
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
|
||||
with open(infile) as f:
|
||||
grid = [list(l.rstrip()) for l in f.readlines()]
|
||||
grid = [list(l.rstrip()) for l in f]
|
||||
main(grid)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from dataclasses import dataclass
|
||||
from heapq import heappush, heappop
|
||||
|
||||
from heapq import heappop, heappush
|
||||
|
||||
DIRECTIONS = (
|
||||
1 + 0j, # EAST
|
||||
|
||||
@@ -47,16 +47,16 @@ def part2(grid):
|
||||
if grid[y+1][x+1] != "A": # center letter is always "A"
|
||||
continue
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
print("Part 2: ", count)
|
||||
|
||||
@@ -66,7 +66,7 @@ if __name__ == "__main__":
|
||||
import sys
|
||||
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
|
||||
with open(infile) as f:
|
||||
grid = [l.rstrip() for l in f.readlines()]
|
||||
grid = [l.rstrip() for l in f]
|
||||
part1(grid)
|
||||
part2(grid)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from collections import defaultdict
|
||||
from itertools import pairwise
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from itertools import cycle
|
||||
from dataclasses import dataclass
|
||||
from pprint import pprint
|
||||
from itertools import cycle
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -75,6 +74,6 @@ if __name__ == "__main__":
|
||||
import sys
|
||||
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
|
||||
with open(infile) as f:
|
||||
grid = [list(l.rstrip()) for l in f.readlines()]
|
||||
grid = [list(l.rstrip()) for l in f]
|
||||
main(grid)
|
||||
|
||||
@@ -30,7 +30,7 @@ if __name__ == "__main__":
|
||||
import sys
|
||||
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
|
||||
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]
|
||||
main(data)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
import fileinput
|
||||
from sys import argv
|
||||
|
||||
|
||||
def area(a, b):
|
||||
@@ -38,8 +37,7 @@ def generate_ppm(inp, scale=100):
|
||||
with open("test.ppm", "w") as f:
|
||||
f.write(f"P3\n{width} {height}\n255\n")
|
||||
for row in arr:
|
||||
for cell in row:
|
||||
f.write(f"{cell * 255} 0 0 ")
|
||||
f.writelines(f"{cell * 255} 0 0 " for cell in row)
|
||||
f.write("\n")
|
||||
|
||||
print("PPM file written to test.ppm")
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
@@ -10,8 +9,7 @@ from pathlib import Path
|
||||
MIN_YEAR = 2015
|
||||
MAX_YEAR = 2025
|
||||
ROOTPATH = Path(os.path.dirname(os.path.realpath(__file__)))
|
||||
TEMPLATE = """#!/usr/bin/env python3
|
||||
import fileinput
|
||||
TEMPLATE = """import fileinput
|
||||
|
||||
|
||||
def main(inp):
|
||||
|
||||
@@ -1 +1 @@
|
||||
from .intcode import interpret_intcode, Interpreter, Operation, Mode
|
||||
from .intcode import Interpreter, Mode, Operation, interpret_intcode
|
||||
@@ -1,8 +1,7 @@
|
||||
#! /usr/bin/env python3
|
||||
from collections import defaultdict
|
||||
from enum import Enum
|
||||
import logging
|
||||
import os
|
||||
from enum import Enum
|
||||
|
||||
loglevel = (os.getenv("LOGLEVEL") or "WARN").upper()
|
||||
logging.basicConfig(format="%(levelname)s:%(message)s", level=loglevel)
|
||||
@@ -38,7 +37,7 @@ class Instruction:
|
||||
self.memory = memory
|
||||
self.opcode = memory[ip]
|
||||
# A B C D E
|
||||
# 0 1 1 0 3
|
||||
# 0 1 1 0 3
|
||||
# A B C modes, DE opcode
|
||||
self.operation = Operation(self.opcode % 100)
|
||||
self.modes = [Mode(get_nth_digit(n, self.opcode)) for n in range(2, 5)]
|
||||
@@ -140,13 +139,13 @@ class Instruction:
|
||||
match self.modes[offset - 1]:
|
||||
case Mode.POSITION: return value
|
||||
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):
|
||||
first = self._get_value(1)
|
||||
second = self._get_value(2)
|
||||
return first, second
|
||||
|
||||
|
||||
def _write(self, address, value):
|
||||
while address >= len(self.memory):
|
||||
self.memory += [0] * len(self.memory)
|
||||
@@ -191,4 +190,3 @@ def interpret_intcode(program, stdin=[]):
|
||||
interpreter = Interpreter(program, stdin)
|
||||
interpreter.interpret(break_on_output=False)
|
||||
return interpreter
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
# Run with pytest
|
||||
import logging
|
||||
from intcode import *
|
||||
|
||||
|
||||
@@ -82,18 +81,13 @@ def test_day9_base():
|
||||
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():
|
||||
quine = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]
|
||||
run_test(quine, expected_out=quine)
|
||||
|
||||
|
||||
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, 104, 1, 99], expected_out=[1])
|
||||
run_test([109, -1, 204, 1, 99], expected_out=[109])
|
||||
@@ -107,5 +101,5 @@ def test_day9_relative():
|
||||
def test_fac():
|
||||
# factorial test
|
||||
fac = [3,29,1007,29,2,28,1005,28,24,2,27,29,27,1001,29,-1,29,1101,0,0,28,1006,28,2,4,27,99,1,0,0]
|
||||
res = interpret_intcode(fac, [4])
|
||||
res = interpret_intcode(fac, [4])
|
||||
assert res.stdout == [24]
|
||||
Reference in new issue
Block a user