예제 #1
0
파일: 24.py 프로젝트: gubatron/AoC
def loadProgram():
    data = aoc.readFileToStringList('24.txt')
    program = []
    for l in data:
        inst = l.split(' ')
        inst_code = instruction_codes[inst[0]]
        if inst_code == INP:
            program.append((inst_code, 'w'))
        else:
            arg1 = inst[1]
            arg2 = inst[2] if inst[2] in ('w', 'x', 'y', 'z') else int(inst[2])
            program.append((inst_code, (arg1, arg2)))
    return program
예제 #2
0
파일: 6.py 프로젝트: gubatron/AoC
import aoc

ages = list(map(int, aoc.readFileToStringList("6.test.txt")[0].split(",")))
fish_map = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}

for age in ages:
    if age not in fish_map:
        fish_map[age] = 0
    fish_map[age] += 1

for day in range(257):
    print(f"Day {day}, n={sum(fish_map.values())}")
    if day == 80:
        ANS1 = sum(fish_map.values())
    if day == 256:
        ANS2 = sum(fish_map.values())

    new_fish = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0}
    items = fish_map.items()
    for age in range(9):
        num_fish = fish_map[age]
        if age == 0:
            new_fish[6] += num_fish
            new_fish[8] += num_fish
        else:
            new_fish[age - 1] += num_fish
    fish_map = new_fish

print("ans1={}".format(ANS1))  # ans1=352195
print("ans2={}".format(ANS2))  # ans2=1600306001288
예제 #3
0
파일: 12.py 프로젝트: gubatron/AoC
import aoc

graph = {}
paths = aoc.readFileToStringList("12.txt")

for path in paths:
    a, b = path.split('-')
    if a not in graph:
        graph[a] = [b]
    else:
        graph[a].append(b)
    if b not in graph:
        graph[b] = [a]
    else:
        graph[b].append(a)
print(graph)


def countPaths(graph, current, seen):
    if current == 'end':
        return 1
    if current.islower() and current in seen:
        return 0
    seen = [current] + seen
    count = 0
    for node in graph[current]:
        count += countPaths(graph, node, seen)
    return count


def countPaths2(graph, current, seen, repeat):
예제 #4
0
파일: 3.py 프로젝트: gubatron/AoC
import aoc

ANS1 = 0
ANS2 = 0

report = aoc.readFileToStringList("3.1.txt")


def mostCommonBitAt(report, i):
    n = len(report)
    ones = 0
    zeroes = 0
    for x in report:
        if x[i] == '1':
            ones += 1
        else:
            zeroes += 1
    if zeroes > ones:
        return '0'
    return '1'


def mostCommonBits(report):
    commonBits = ""
    wordLength = len(report[0])
    for i in range(wordLength):
        commonBits += mostCommonBitAt(report, i)
    return commonBits


def invertBinaryString(s):
예제 #5
0
파일: 9.py 프로젝트: gubatron/AoC
import aoc
from functools import reduce
l = aoc.readFileToStringList("9.txt")
G = []
for line in l:
    G.append(list(map(int, list(line))))


def getNeighbors(G, i, j, includeCoordinates=False):
    neighbors = []
    # top
    if i > 0:
        if includeCoordinates:
            neighbors.append((G[i - 1][j], (i - 1, j)))
        else:
            neighbors.append(G[i - 1][j])
    # bottom
    if i < len(G) - 1:
        if includeCoordinates:
            neighbors.append((G[i + 1][j], (i + 1, j)))
        else:
            neighbors.append(G[i + 1][j])
    # right
    if j < len(G[0]) - 1:
        if includeCoordinates:
            neighbors.append((G[i][j + 1], (i, j + 1)))
        else:
            neighbors.append(G[i][j + 1])
    # left
    if j > 0:
        if includeCoordinates:
예제 #6
0
파일: 20.py 프로젝트: gubatron/AoC
def allBordersLit(imgDict):
    return allBorders(imgDict, '#')


def processImage(imgDict, algo, steps):
    for step in range(steps):
        defaultChar = '.'
        # if the first char in the algorithm is '#' sequences of '.........' will turn everything into #, so we invert it
        if algo[0] == '#' and step % 2 == 1:
            defaultChar = '#'
        imgDict = enhanceImage(imgDict, algo, defaultChar)
    return countLitPixels(imgDict)


#data = aoc.readFileToStringList("20.test.txt")
data = aoc.readFileToStringList("20.txt")
imgAlgo = data[0]
imageData = data[2:]
imageDict = loadImageDict(imageData)

# part 1
ANS1 = processImage(imageDict, imgAlgo, 2)

#part 2
imageDict = loadImageDict(imageData)
ANS2 = processImage(imageDict, imgAlgo, 50)

print("ans1={}".format(ANS1))  # 5361
print("ans2={}".format(ANS2))  # 16826
예제 #7
0
import aoc

raw_data = aoc.readFileToStringList('13.txt')


def loadData(raw_data):
    dots = set()
    fold_instructions = []
    emptyLineFound = False
    for line in raw_data:
        if len(line) == 0:
            emptyLineFound = True
        elif not emptyLineFound:
            dots.add(tuple(map(int, line.split(','))))
        else:
            fold_instructions.append(line.split('fold along ')[1].split('='))
    return dots, fold_instructions


def getMaxXY(dots):
    max_x = 0
    max_y = 0
    for (x, y) in dots:
        if x > max_x:
            max_x = x
        if y > max_y:
            max_y = y
    return max_x, max_y


def printMatrix(dots):
예제 #8
0
파일: 5.py 프로젝트: gubatron/AoC
import aoc

data = aoc.readFileToStringList("5.1.txt")
segments = list(
    map(
        lambda line: list(
            map(lambda pStr: list(map(int, pStr.split(','))), line.split(
                ' -> '))), data))
START = 0
END = 1


class Point:
    def __init__(self, p: list[int]) -> None:
        self.x = p[0]
        self.y = p[1]

    def __hash__(self):
        return hash(self.__repr__())

    def __repr__(self) -> str:
        return "({},{})".format(self.x, self.y)

    def __str__(self) -> str:
        return self.__repr__()


def updatePoints(points: dict[str, int], p: Point) -> None:
    if str(p) in points:
        points[str(p)] += 1
    else:
예제 #9
0
파일: 14.py 프로젝트: gubatron/AoC
from collections import Counter
import aoc

data = aoc.readFileToStringList('14.txt')

template = data[0]

rules = {}
for r in data[2:]:
    a, b = r.split(' -> ')
    rules[a] = b


def initDB(template):
    counter = Counter()
    for i in range(len(template) - 1):
        pair = template[i:i + 2]
        counter[pair] += 1
    return counter


def walk(counter, rules, steps=10):
    for _ in range(steps):
        new_counter = Counter()
        for k, count in counter.items():
            if k in rules:
                pairA = k[0] + rules[k]
                pairB = rules[k] + k[1]
                new_counter[pairA] += count
                new_counter[pairB] += count
        counter = new_counter
예제 #10
0
파일: 7.py 프로젝트: gubatron/AoC
from math import floor
from statistics import median, mean
import aoc
crabPositions = list(map(int, aoc.readFileToStringList("7.txt")[0].split(',')))
median, mean = int(median(crabPositions)), floor(mean(crabPositions))
ANS1 = ANS2 = 0
for crabPos in crabPositions:
    ANS1 += abs(crabPos - median)
    ANS2 += sum(range(1, 1 + abs(crabPos - mean)))
print("ans1={}".format(ANS1))  # ans1=364898
print("ans2={}".format(ANS2))  # ans2=104149091
예제 #11
0
import aoc

instructions = aoc.readFileToStringList("2.1.txt")
horizontal = 0
depth = 0
aim = 0

#instructions = ["forward 5","down 5","forward 8","up 3","down 8","forward 2"]


def process_instruction(inst):
    global horizontal, depth
    action, step = (inst.split())
    step = int(step)
    if action == 'forward':
        horizontal += step
    if action == 'up':
        depth -= step
    if action == 'down':
        depth += step


list(map(process_instruction, instructions))

ans1 = depth * horizontal

horizontal = 0
depth = 0
aim = 0

예제 #12
0
파일: 4.py 프로젝트: gubatron/AoC
import aoc
# Giant Squid (Bingo)
input = aoc.readFileToStringList("4.1.txt")
bingoNumbers = list(map(int, input[0].split(',')))

# filter out empty lines, then split each line by spaces and convert to int lists
bingoBoardsData = list(
    map(lambda line: list(map(int, line.split())),
        filter(lambda line: len(line) > 0, input[2:])))


class BingoBoard:
    def __init__(self) -> None:
        self.numRows = []
        self.reset()

    def bingoed(self):
        return self.__bingoed

    def reset(self) -> None:
        self.initMarkedRows()
        self.__bingoed = False

    def initMarkedRows(self) -> None:
        self.markedRows = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

    def addRow(self, intList):
        self.numRows.append(intList)

    def tryToMarkNumber(self, number):
예제 #13
0
import aoc

lines = aoc.readFileToStringList("10.txt")


def handleChar(c, char_stack, illegal_stack):
    matching_opening = {')': '(', ']': '[', '}': '{', '>': '<'}
    score = {')': 3, ']': 57, '}': 1197, '>': 25137}
    if c in ['(', '[', '{', '<']:
        char_stack.append(c)
    if c in [')', ']', '}', '>']:
        if len(char_stack) == 0:
            illegal_stack.append(c)
            return score[c]
        else:
            if char_stack[-1] == matching_opening[c]:
                char_stack.pop()
            else:
                illegal_stack.append(c)
                return score[c]
    return 0


def process_line(line, illegal_stack):
    expression_stack = []
    for c in line:
        score = handleChar(c, expression_stack, illegal_stack)
        if score > 0:
            return score
    if len(expression_stack) > 0:
        return -1  # incomplete