import os import sys from typing import List, Tuple import numpy as np dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 coor = [ [tuple((int(v) for v in c.split(","))) for c in x.split(" -> ")] for x in files.read_lines("input.txt", dir) ] class Map: store: List width: int height: int def __init__(self, itter: List[List[Tuple[int, int]]]): self.width = 0 self.height = 0 for c1, c2 in itter: if max(c1[0], c2[0]) > self.width: self.width = max(c1[0], c2[0]) if max(c1[1], c2[1]) > self.height: self.height = max(c1[1], c2[1]) self.width += 1 self.height += 1
import os import sys from copy import deepcopy from typing import Dict, List, Optional, Tuple import numpy as np dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 lines = files.read_lines("input.txt", dir) draw = [int(x) for x in lines[0].split(",")] inputs = np.split(lines[1:], range(0, len(lines[1:]), 5)) class Board: grid: List[List[int]] mark: List[List[bool]] def __init__(self, input: List[str]): self.grid = [] for row in input: self.grid.append([int(x) for x in row.split()]) assert len(self.grid[0]) == 5 assert len(self.grid) == 5 self.mark = [[False for _ in range(5)] for _ in range(5)] assert len(self.mark[0]) == 5 assert len(self.mark) == 5 def mark_number(self, number):
import os import sys from copy import deepcopy from typing import List dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 initial_state = [int(x) for x in files.read_lines("input.txt", dir)[0].split(",")] def sim_for_days(fish: List[int], total_days: int) -> int: """ Simulate fish increase for given amount of days. """ store = {} for i in range(9): store[i] = 0 # Fill the store with the current fish counts for f in fish: store[f] += 1 days = 0 while days < total_days: temp = {} for key in store.keys(): if key == 8: temp[key] = store[0] continue
self.last_spoken = new_number self.counter += 1 if self.counter == part * parts: print(parts * ".", end="\r") parts += 1 return self.last_spoken def _save_number(self, number): if number not in self.log: self.log[number] = (0, self.counter) self.log[number] = (self.counter - self.log[number][1], self.counter) # puzzle 1 numbers = [ int(num) for num in files.read_lines("input.txt", dir)[0].split(",") ] game = MemoryGame() game.handle_start(numbers) print(f""" Puzzle number 1: The 2020th number spoken is {game.run_turns(2020)} """) # puzzle 2 print(f""" Puzzle number 2: The 30 millionth unique number is: {game.run_turns(30_000_000)} """)
import os import sys from collections import defaultdict from copy import deepcopy from typing import Dict, List, Tuple dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 data = files.read_lines("test.txt", dir) class Pocket: """ Pocket is the main dict. During cycle operation: Frozen is used for the cycle querry loop. Nothing may operate on frozen to prevent RuntimeErrors. """ dimensions: int pocket: defaultdict[int, defaultdict[int, defaultdict[int, bool]]] def __init__(self, plane: List[str], dimensions: int): self.dimensions = dimensions self.pocket = defaultdict(self._y_values) for y, line in enumerate(plane): for x, state in enumerate(line): self.pocket[x][y][0] = True if state == "#" else False frozen = deepcopy(self.pocket)
import os import sys dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 commands = [ (cmnd.split()[0], int(cmnd.split()[1])) for cmnd in files.read_lines("input.txt", dir) ] # puzzle 1 forward = 0 depth = 0 for command, value in commands: if command == "forward": forward += value if command == "up": depth -= value if command == "down": depth += value print( f""" Puzzle number 1: Product of end values is {forward * depth} """ ) # puzzle 2
import os import sys from collections import defaultdict from typing import Tuple dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files # noqa E402 instructions = [char for char in files.read_lines("input.txt", dir)[0]] def move(instruction: str, coor: Tuple[int, int]) -> tuple[int, int]: x, y = coor if instruction == ">": x += 1 if instruction == "<": x -= 1 if instruction == "^": y += 1 if instruction == "v": y -= 1 return (x, y) # puzzle 1 addresses = defaultdict(int) location = (0, 0) addresses[str(location)] += 1 for instruction in instructions:
import os import sys from collections import defaultdict from copy import deepcopy dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 diagnostics = files.read_lines("input.txt", dir) def count_common(numbers): # count occurence of bits in a list of numbers # c[index] > 0 means "1" bit most common # c[index] < 0 means "0" bit most common # c[index] == 0 means both bits equally common c = defaultdict(int) for number in numbers: for index, bit in enumerate(number): c[index] = c[index] + 1 if bit == "1" else c[index] - 1 return c # puzzle 1 common = count_common(diagnostics) gamma = "".join(["1" if x > 0 else "0" for x in common.values()]) epsilon = "".join(["1" if x < 0 else "0" for x in common.values()]) print(f""" Puzzle number 1:
self._float_bits(slots) return slots @property def bitsum(self) -> int: sum = 0 for decimal in self.store.values(): sum += self._decimal_to_base10(decimal) return sum # puzzle 1 memory = Memory() instructions = [x.split(" = ") for x in files.read_lines("input.txt", dir)] for key, value in instructions: mask = "" mem_init: List[List[str]] = [] if key == "mask": memory.set_mask(value) elif key[:3] == "mem": memory.apply_instruction(key, value) print(f""" Puzzle number 1: Sum of all converted bits is: {memory.bitsum} """) # puzzle 2
import os import sys from functools import cache from typing import Generator, List, Tuple, Union dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files # noqa E402 departure = int(files.read_lines("input.txt", dir)[0]) busses = [] for bus in files.read_lines("input.txt", dir)[1].split(","): try: busses.append(int(bus)) except ValueError: continue def bus_wait_time(time: int, bus_id: int) -> int: remainder = time % bus_id return 0 if remainder == 0 else bus_id - remainder # puzzle 1 wait_time = {} for bus in busses: wait_time[bus] = bus_wait_time(departure, bus) shortest_wait = min(zip(wait_time.values(), wait_time.keys())) print(
import os import sys from typing import Dict, List, Tuple dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 entries = [ tuple(([x for x in combis.split()] for combis in entry.split("|"))) for entry in files.read_lines("input.txt", dir) ] connection = { 0: "abcefg", 1: "cf", 2: "acdeg", 3: "acdfg", 4: "bcdf", 5: "abdfg", 6: "abdefg", 7: "acf", 8: "abcdefg", 9: "abcdfg", } unique_lengths = { # number of bars : int value 2: 1, 4: 4, 3: 7, 7: 8,
import os import sys from typing import Any, Dict, List, Optional, Tuple import numpy as np dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 map_rows = [[int(x) for x in row] for row in files.read_lines("input.txt", dir)] class Map: """ A class for storing a 2d map. The input is a List of horizontal rows of the map. """ store: List width: int height: int def __init__(self, itter: List[List[int]]): self.width = len(itter[0]) self.height = len(itter) self.store = ["x"] * (self.width * self.height) self._fill_map(itter) def get(self, x: int, y: int) -> Optional[int]:
import os import sys from functools import reduce dir = os.path.dirname(__file__) sys.path.append("/home/merijn/software/advent-of-code") from tools import files, utils # noqa E402 measurements = [int(x) for x in files.read_lines("input.txt", dir)] # puzzle 1 increase = 0 for index, measurement in enumerate(measurements, start=1): if index < len(measurements) and measurements[index] > measurement: increase += 1 print(f""" Puzzle number 1: Measurements increased {increase} times. """) # puzzle 2 increase_window = 0 for index, _ in enumerate(measurements[3:], start=3): if sum(measurements[index - 3:index]) < sum( measurements[index - 2:index + 1]): increase_window += 1 print(f""" Puzzle number 2: Measurement window increased {increase_window} times.