import modules.aoc as AOC input = AOC.readDayInput('07') myBag = 'shiny gold bag' ## INPUT PROCESSING allBags = dict() for line in input: currentBag, bagContentStr = line.split(' contain ') currentBag = currentBag.replace('bags', 'bag') bagContentList = bagContentStr.rstrip('.').split(',') bagContent = dict() for content in bagContentList: if (content != 'no other bags'): amount, color = content.replace('bags', 'bag').split(maxsplit=1) bagContent[color] = amount allBags[currentBag] = bagContent ## FIRST STAR contentBags = [myBag] contentIndex = 0 while (contentIndex < len(contentBags)): currentBag = contentBags[contentIndex] for bagKey in allBags: if currentBag in allBags[bagKey] and bagKey not in contentBags:
import modules.aoc as AOC input = AOC.readDayInput('12') directions = { 'N': (0, 1), 'S': (0, -1), 'W': (-1, 0), 'E': (1, 0) } ## FIRST STAR shipRotations = { 'L': lambda a, b, n: (a - b + n) % n, 'R': lambda a, b, n: (a + b) % n, } indexToDirection = ['N', 'E', 'S', 'W'] coords = [0, 0] direction = indexToDirection.index('E') for command in input: action = command[:1] value = int(command[1:]) if action == 'F': action = indexToDirection[direction] if action in directions.keys():
import modules.aoc as AOC input = AOC.readDayInput('18') def getPostfixNotation(expression, precedence): tokens = list(expression.replace(' ', '')) postfix = [] operators = [] for token in tokens: if token.isnumeric(): postfix.append(token) elif token == '(': operators.append(token) elif token == ')': while operators[-1] != '(': postfix.append(operators.pop()) operators.pop() else: # operator while operators and operators[-1] != '(' and precedence[token] <= precedence[operators[-1]]: postfix.append(operators.pop()) operators.append(token) while operators: postfix.append(operators.pop()) return postfix def evaluateExpression(expression, precedence):
import modules.aoc as AOC input = [list(line) for line in AOC.readDayInput('11')] occupiedSeat = '#' emptySeat = 'L' floor = '.' lenX = len(input[0]) lenY = len(input) positions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] def getOccupiedInEquilibrium(seats, getVisibleOccupied, becomeEmptyMin=4): oldSeats = None newSeats = [line[:] for line in seats] changes = -1 while changes != 0: oldSeats = [line[:] for line in newSeats] changes = 0 for y in range(lenY): for x in range(lenX): if (oldSeats[y][x] == floor): continue visible = getVisibleOccupied(oldSeats, x, y) if oldSeats[y][x] == emptySeat and visible == 0:
import modules.aoc as AOC input = AOC.readDayInput('03') tree = '#' def checkTrees(map, right, down): x = 0 xMax = len(map[0]) trees = 0 for y in range(down, len(map), down): x = (x + right) % xMax if (map[y][x] == tree): trees += 1 return trees # FIRST STAR allTrees = checkTrees(input, 3, 1) AOC.printDayAnswer(1, allTrees) # SECOND STAR slopes = [ [1, 1], [5, 1], [7, 1], [1, 2] ] for slope in slopes: allTrees *= checkTrees(input, slope[0], slope[1]) AOC.printDayAnswer(2, allTrees)
import re import modules.aoc as AOC input = AOC.readDayInput('04') # FIRST STAR passports = [] currentPassport = {} for line in input: if line: passportData = line.split() for info in passportData: field, value = info.split(':', 1) if field != 'cid': currentPassport[field] = value else: passports.append(currentPassport) currentPassport = {} passports.append(currentPassport) requiredFields = ['byr', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid'] validPassports = [] for passport in passports: if len(set(passport.keys()) & set(requiredFields)) == len(requiredFields): validPassports.append(passport)
import re import modules.aoc as AOC input = AOC.readDayInput('02') # FIRST STAR regex = re.compile(r"(\d+)-(\d+) ([a-z]): ([a-z]+)") correctWords = 0 for password in input: groups = regex.match(password).groups() min = int(groups[0]) max = int(groups[1]) letter = groups[2] word = groups[3] counter = 0 for let in word: if (let == letter): counter += 1 if (counter >= min and counter <= max): correctWords += 1 AOC.printDayAnswer(1, correctWords) # SECOND STAR correctWords = 0
import itertools import modules.aoc as AOC input = AOC.readDayInput('17') sumCoord = lambda a, b: tuple([a[i] + b[i] for i in range(len(a))]) def bootingCycles(startState, dimensions): startGrid = dict() startGridZeroes = [0] * (dimensions - 2) for i in range(len(startState)): for j in range(len(startState[0])): startGrid[tuple([i, j] + startGridZeroes)] = startState[i][j] neighbors = set( itertools.combinations_with_replacement([-1, 0, 1] * dimensions, dimensions)) neighbors.remove(tuple([0] * dimensions)) for i in range(6): for cube in list(startGrid.keys()): for neighbor in neighbors: neighborCoord = sumCoord(cube, neighbor) if neighborCoord not in startGrid: startGrid[neighborCoord] = '.' newGrid = startGrid.copy() for cube in startGrid:
import itertools import modules.aoc as AOC input = AOC.readDayInput('09', True) preamble = 25 ## FIRST STAR for i in range(preamble, len(input)): if not any([ sum(comb) == input[i] for comb in itertools.combinations(input[i - preamble:i], 2) ]): invalid = input[i] AOC.printDayAnswer(1, input[i]) break ## SECOND STAR start = 0 end = 1 weakSum = input[start] + input[end] while (weakSum != invalid): if (weakSum < invalid): end += 1 weakSum += input[end] elif (weakSum > invalid): while (weakSum > invalid and start < end): weakSum -= input[start] start += 1
import modules.aoc as AOC input = AOC.readDayInput('10', True) input.sort() ## FIRST STAR differences = [0, 0, 1] differences[input[0] - 1] += 1 for i in range(1, len(input)): differences[input[i] - input[i - 1] - 1] += 1 AOC.printDayAnswer(1, differences[0] * differences[2]) ## SECOND STAR input = [0] + input possibilities = [None] * len(input) maxJolt = max(input) def calcPossibilities(i): if (input[i] == maxJolt): return 1 count = 0 for next in range(i + 1, i + 4): if next < len(input) and (input[next] - input[i]) <= 3: if possibilities[next] is None: count += calcPossibilities(next) else:
import modules.aoc as AOC input = AOC.readDayInput('14') toBinary = lambda n, b: ('{:0' + str(b) + 'b}').format(n) ## FIRST STAR memory = dict() currentMaskTo1 = None currentMaskTo0 = None for line in input: command, value = line.split(' = ') if (command == 'mask'): currentMaskTo1 = int(value.replace('X', '0'), base=2) currentMaskTo0 = int(value.replace('X', '1'), base=2) continue command = command.replace('mem[', '').replace(']', '') value = int(value) memory[command] = (value | currentMaskTo1) & currentMaskTo0 AOC.printDayAnswer(1, sum(memory.values())) ## SECOND STAR memory = dict() currentMask = '' for line in input:
import modules.aoc as AOC input = AOC.groupInput(AOC.readDayInput('06')) def createLetterDict(): letterDict = dict() for i in range(ord('a'), ord('z') + 1): letterDict[chr(i)] = 0 return letterDict # FIRST STAR totalAnswers = 0 for group in input: groupSet = set() for personAnswers in group: [groupSet.add(answer) for answer in personAnswers] totalAnswers += len(groupSet) AOC.printDayAnswer(1, totalAnswers) # SECOND STAR totalAnswers = 0 for group in input: frequency = createLetterDict()
import math import modules.aoc as AOC input = AOC.readDayInput('13') myEarliestTime = int(input[0]) buses = [int(bus) if bus != 'x' else bus for bus in input[1].split(',')] ## FIRST STAR earliestBusID = None earliestBusTime = myEarliestTime * myEarliestTime for busID in buses: if (busID == 'x'): continue firstBus = int(math.ceil(myEarliestTime / busID)) * busID if (firstBus < earliestBusTime): earliestBusTime = firstBus earliestBusID = busID AOC.printDayAnswer(1, earliestBusID * (earliestBusTime - myEarliestTime)) ## SECOND STAR def chineseRemainderTheorem(numbers, remainders): product = math.prod(numbers) productDiv = [product // num for num in numbers] inverses = [
import copy import modules.aoc as AOC input = AOC.readDayInput('08') ## INPUT PROCESSING def getInstruction(inputLine): instruction = dict() op, arg = inputLine.split(' ', 1) instruction['op'] = op instruction['arg'] = int(arg) return instruction instructions = [getInstruction(line) for line in input] ## FIRST STAR def executeBoot(instructions): accumulator = 0 executedIndexes = set() index = 0 looped = False while index < len(instructions): if index in executedIndexes: looped = True
import re import modules.aoc as AOC def getBinaryFromInput(line): line = re.sub(r"[F|L]", '0', line) return re.sub(r"[B|R]", '1', line) input = [getBinaryFromInput(line) for line in AOC.readDayInput('05')] seatIDs = [int(seat, base=2) for seat in input] ## FIRST STAR AOC.printDayAnswer(1, max(seatIDs)) ## SECOND STAR seatIDs.sort() for i in range(len(seatIDs) - 1): if seatIDs[i] + 2 == seatIDs[i + 1]: AOC.printDayAnswer(2, seatIDs[i] + 1) break
import modules.aoc as AOC input = AOC.readDayInput('15')[0].split(',') input = [int(x) for x in input] def memoryGame(starters, lastNumber): occurences = dict() spoken = starters[:] for i in range(len(spoken)): occurences[spoken[i]] = [i] for i in range(len(spoken), lastNumber): lastSpoken = spoken[i - 1] if len(occurences[lastSpoken]) == 1: spoken.append(0) else: spoken.append(occurences[lastSpoken][-1] - occurences[lastSpoken][-2]) if spoken[i] in occurences: occurences[spoken[i]].append(i) else: occurences[spoken[i]] = [i] return spoken[-1] ## FIRST STAR