def main(): aoc.header("Sensor Boost") aoc.run_tests() program = list(map(int,aoc.get_input().readline().split(","))) aoc.output(1, part, args=[program, [1]]) aoc.output(2, part, args=[program, [2]])
def main(): aoc.header("Sunny with a Chance of Asteroids") aoc.run_tests() test_program = list(map(int, aoc.get_input().readline().split(","))) aoc.output(1, run, args=[test_program, [1], INSTRUCTIONS_P1]) aoc.output(2, run, args=[test_program, [5], INSTRUCTIONS_P2])
def main(): aoc.header("Amplification Circuit") aoc.run_tests() program = list(map(int, aoc.get_input().readline().split(","))) aoc.output(1, part1, args=[program]) aoc.output(2, part2, args=[program])
def main(): aoc.header("Secure Container") aoc.run_tests() (lower, upper) = aoc.get_input().readline().split("-") aoc.output(1, part, args=[int(lower), int(upper), validate_p1]) aoc.output(2, part, args=[int(lower), int(upper), validate_p2])
def run(noun : int, verb : int): initial_memory = [int(x) for x in aoc.get_input().readline().split(",")] initial_memory[1] = noun initial_memory[2] = verb m = IntcodeMachine(initial_memory) m.run() return m.memory[0]
def main(): aoc.header("Universal Orbit Map") aoc.run_tests() orbits = aoc.get_input().readlines() output = aoc.output(1, part1, args=[orbits], post=itemgetter(0)) aoc.output(2, part2_graph, args=[orbits, *output[1:]], comment="Dijstra's algorithm") aoc.output(2, part2_ancestor, args=[orbits, *output[1:]], comment="Common ancestor")
def input(day: int, file_name: str = "") -> None: resp: List[str] = aoc.get_input(day) if file_name == "": pprint.pprint(resp, compact=True) else: with open(file_name, "w") as f: for line in resp: f.write(str(line) + "\n")
def main(): aoc.header("Space Image Format") aoc.run_tests() data = aoc.get_input().readline().strip() s = Size(width=25, height=6) (_, layers) = aoc.output(1, part1, args=[data, s], post=itemgetter(0)) aoc.output(2, part2, args=[layers, s], post=lambda i: (i, s), output=lambda t: print_image4(t[0], t[1]))
def main(): aoc.header("Crossed Wires") aoc.run_tests() inp = aoc.get_input() path_a = list(inp.readline().split(",")) path_b = list(inp.readline().split(",")) aoc.output(1, part1, args=[path_a, path_b]) aoc.output(2, part2, args=[path_a, path_b])
#!/usr/bin/env python from aoc import get_input # AoC data = get_input(13).splitlines() time = int(data[0]) busses = [] for busid in data[1].split(","): if (busid != "x"): busses.append(int(busid)) busses.sort() def getTimestamp(busid, i): return busid * i bustimes = dict() for busid in busses: i = 0 bustimes[busid] = [] while True: timestamp = getTimestamp(busid, i) bustimes[busid].append(timestamp) if (timestamp > time): break
import aoc import re myinput = aoc.get_input(18) # myinput = open('sample', 'r').read().splitlines() class T: def __init__(self, val): self.val = val def __truediv__(self, other): # Not really divison, just addition return T(self.val + other.val) def __add__(self, other): return T(self.val + other.val) def __mul__(self, other): return T(self.val * other.val) def __sub__(self, other): return T(self.val * other.val) def __str__(self): return str(self.val) def __radd__(self, other): if isinstance(other, int): return self.val + other elif isinstance(other, T): return T(self.val + other.val)
#!/usr/bin/env python from aoc import get_input # AoC import re # regex nums = list(map(int, get_input(9).splitlines())) def checkValid(nums, numsum): for num1 in nums: for num2 in nums: if (num1 + num2 == numsum and num1 != num2): return [num1, num2], numsum return False, numsum def checkIfNumValid(amble, index): prevNums = nums[index - amble:index] numsum = nums[index] sumnumbers, numsum2 = checkValid(prevNums, numsum) return sumnumbers, numsum2 amble, invalid, invalidindex = 25, None, None for i in range(len(nums)): if (i > amble - 1): valid = checkIfNumValid(amble, i) if (not valid[0]):
from collections import defaultdict import re import time import functools from aoc import get_input rules = get_input(day=7) def clean(bagstring): number, modifier, color, bag = re.fullmatch( r'(\d+) ([a-z]+) ([a-z]+) (bag)s?', bagstring).groups() return int(number), ' '.join((modifier, color)) fits_in = defaultdict(set) holds = defaultdict(set) for rule in rules: outer, inners = rule.split(' contain ') outer = outer[:-5] for inner in inners.split(','): inner = inner.strip().removesuffix('.') if inner != 'no other bags': number, inner = clean(inner) fits_in[inner].add((number, outer)) holds[outer].add((number, inner))
import aoc from collections import Counter def inpfct(x): return list(map(int, list(x))) inp = aoc.get_input(inpfct) _logger = aoc.get_logger(__name__) width = 25 height = 6 n = width * height layers = [inp[i:i + n] for i in range(0, len(inp), n)] if aoc.part_one(): _logger.info('%s Layers found (size: %s x %s)', len(layers), width, height) clayers = sorted(list(map(Counter, layers)), key=lambda x: x[0]) print(clayers[0][1] * clayers[0][2]) if aoc.part_two(): print() cnt = 0 layer = [2] * n for l in layers: for i, y in enumerate(l): if layer[i] == 2: layer[i] = y for y in range(0, height):
from math import cos, sin, pi from aoc import get_input instructions = [(i[0], int(i[1:])) for i in get_input(day=12)] mappings = {'N': (0, 1), 'S': (0, -1), 'E': (1, 0), 'W': (-1, 0)} def move(action, value, pos, direc): if action in 'NSEW': nx = pos[0] + value * mappings[action][0] ny = pos[1] + value * mappings[action][1] pos = nx, ny elif action == 'L': direc = (direc + value) % 360 elif action == 'R': direc = (direc - value) % 360 elif action in 'F': nx = pos[0] + int(round(cos(direc / 360 * 2 * pi))) * value ny = pos[1] + int(round(sin(direc / 360 * 2 * pi))) * value pos = nx, ny else: raise ValueError return pos, direc # 12-1 pos = (0, 0) direc = 0 for action, value in instructions:
#!/usr/bin/env python from aoc import get_input # AoC from functools import lru_cache minjolt, maxjolt = 1, 3 jolts = sorted(list(map(int, get_input(10).splitlines()))) jolts.insert(0, 0) # first one is allways 0 jolts.append(max(jolts) + 3) # my adapter, allways higher than the highest by 3 used = [] def getBest(i, jolts): num = jolts[i] diffs = [] for i in range(len(jolts)): if (i > 0): bestdiff = jolts[i] - jolts[i - 1] diffs.append(bestdiff) diff1, diff3 = diffs.count(1), diffs.count(3) part1 = diff1 * diff3 # part 2
import numpy as np import aoc directions = { 'U': np.array([0, 1]), 'D': np.array([0, -1]), 'R': np.array([1, 0]), 'L': np.array([-1, 0]) } day = 3 lines = aoc.get_input(day) cable1 = [(inst[0], int(inst[1:])) for inst in lines[0].split(',')] cable2 = [(inst[0], int(inst[1:])) for inst in lines[1].split(',')] grid = {} at = np.array([0, 0]) step = 0 for direction, length in cable1: delta = directions[direction] for _ in range(length): at += delta step += 1 if at.tostring() not in grid.keys(): grid[at.tostring()] = step min_dist = 1e100 min_at = None
#!/usr/bin/env python from aoc import get_input inp = get_input(2).splitlines() def getOper(inp): ops = [] passw = [] for op in inp: ops.append(op.split(":")[0]) passw.append(op.split(":")[1]) return ops, passw def getRng(op): x = op.split(" ") rng = list( map( int, x[0].split("-") ) ) char = x[1] return rng, char def countChar(string, char): s = 0 for i in range(len(string)): if( string[i] == char ): s += 1 return s ops, passw = getOper(inp) validsum = 0 #PART 1
import time from itertools import accumulate, combinations from aoc import get_input code = [int(line) for line in get_input(day=9)] # 9-1 N = 25 i = N for i in range(N, len(code)): if not code[i] in {sum(c) for c in combinations(code[i - N:i], 2)}: target = code[i] print(target) break # 9-2 slow t0 = time.time() for i in range(len(code)): j = i + 1 running_total = code[i] while j < len(code) and running_total < target: running_total += code[j] if running_total == target: print(i, j, min(code[i:j + 1]) + max(code[i:j + 1])) break j += 1 print(f'{time.time() - t0} seconds') # 9-2 fast t0 = time.time()
import aoc data = {*map(int, aoc.get_input(1).splitlines())} for x in data: for y in data: if (x + y == 2020): print(x * y) for x in data: for y in data: for z in data: if (x + y + z == 2020): print(x * y * z)
#!/usr/bin/env python from aoc import get_input # AoC import re # regex from copy import copy CodeLines = get_input(8).splitlines() print(CodeLines) def parseCode(code): if (code and code != ""): regex = r"^([a-z]{3}) ([\+\-]{1})([0-9]+)$" op, sign, num = re.match(regex, code).groups() return op, sign, int(num) else: print("INVALID CODE:", code) return accu = 0 line = 0 def runCode(op, sign, num, newline=line, newaccu=accu): if (op == "nop"): newline += 1 elif (op == "acc"): if (sign == "+"): newaccu += num
#!/usr/bin/env python from aoc import get_input # AoC import re # regex data = get_input(DAY)
#!/usr/bin/env python from aoc import get_input inp = get_input(3).splitlines() mapp = inp maplen = len(mapp) def slope(a, b): trees = 0 x, y = 0, 0 while True: try: x += a y += b if (x >= len(mapp[0])): x = x - len(mapp[0]) if (mapp[y][x] == "#"): trees += 1 except: break return trees tree1 = slope(3, 1)
if c == '(': close = pos + find_close(equation[pos:]) c = str(parse(equation[pos + 1:close])) # recursion pos = close elif c == ')': raise ValueError if c.isnumeric(): if op == '+': ans += int(c) op = None elif op == '*': ans *= int(c) op = None else: raise ValueError( f'Encountered a number {c=} at {pos=} without having an operator set' ) elif c in '+*': op = c else: raise ValueError(c) pos += 1 return ans # 18-1 equations = get_input(day=18) print(sum(parse(equation) for equation in equations))
import sys import curses import time import termcolor from collections import defaultdict, namedtuple import aoc import matplotlib.pyplot as plt def inp_decode(x): return list(map(int, x.split(","))) inp = aoc.get_input(inp_decode) _logger = aoc.get_logger() opcode = namedtuple("opcode", ["name", "parameter"]) opcodes = { 1: opcode(name="add", parameter="iio"), 2: opcode(name="mul", parameter="iio"), 3: opcode(name="inp", parameter="o"), 4: opcode(name="out", parameter="i"), 5: opcode(name="jit", parameter="ii"), 6: opcode(name="jif", parameter="ii"), 7: opcode(name="lt ", parameter="iio"), 8: opcode(name="eq ", parameter="iio"), 9: opcode(name="arb", parameter="i"), 99: opcode(name="hlt", parameter=""), }
#!/usr/bin/env python from aoc import get_input import re groups = get_input(6).split("\n\n") def toList(string): list = [] list[:0] = string return list print(groups) def countQuestions(group): persons = group.split("\n") groupQs = [] for person in persons: chars = toList(person) for char in chars: if (not char in groupQs): groupQs.append(char) return len(groupQs)
import sys import aoc def part1(numbers): for n in numbers: other = 2020 - n if other in numbers: print(f"{n} * {other} = {n * other}") return def part2(numbers): for n1 in numbers: for n2 in numbers: if n1 == n2: continue n3 = 2020 - n1 - n2 if n3 in numbers: print(f"{n1} * {n2} * {n3} = {n1 * n2 * n3}") return input = aoc.get_input('day1.txt') numbers = {int(line) for line in input.splitlines()} part1(numbers) part2(numbers)
from dataclasses import dataclass import re from aoc import get_input @dataclass class Entry: letter: str pol_min: int pol_max: int password: str database = [] for line in get_input(day=2): pol_min, pol_max, letter, pw = re.fullmatch(r'(\d+)-(\d+) (\w): (\w+)', line).groups() database.append(Entry(letter, int(pol_min), int(pol_max), pw)) # 2-1 print(sum(entry.pol_min <= entry.password.count(entry.letter) <= entry.pol_max for entry in database)) # 2-2 n_valid = 0 for entry in database: first = entry.password[entry.pol_min - 1] == entry.letter second = entry.password[entry.pol_max - 1] == entry.letter if first ^ second: # xor n_valid += 1
def main(): aoc.header("Space Police") program = list(map(int, aoc.get_input().readline().split(","))) aoc.output(1, run_robot, args=[program, False], post=lambda t: len(t[1])) aoc.output(2, run_robot, args=[program, True], output=part2_post)
def flip(positions): floor = defaultdict(bool) for pos in positions: floor[pos] = not floor[pos] return floor # 24-1 with open('input/24-1-test.txt') as f: test_positions = [sum(parse(line)) for line in f.read().splitlines()] assert sum(flip(test_positions).values()) == 10 positions = [sum(parse(line)) for line in get_input(day=24)] print(sum(flip(positions).values())) # 24-2 def neighbors(pos): yield from (pos + vec for vec in DIRECTIONS.values()) def play(grid, T): for t in range(1, T + 1): neigh_counts = defaultdict(int) # make copy while getting rid of white tiles (False) from data structure grid = defaultdict(bool, {k: v for k, v in grid.items() if v}) new_grid = deepcopy(grid)