Ejemplo n.º 1
0
from pathlib import Path
from aocd import get_data
lines = get_data(day=24, year=2020).splitlines()

p = Path(__file__).resolve()
with open(p.parent / 'in.txt') as f:
    lines2 = f.read().splitlines()

directions = []

for line in lines:
    line_directions = []
    while len(line) > 0:
        if line.startswith(("e", "w")):
            line_directions.append(line[0])
            line = line[1:]
        else:
            line_directions.append(line[0:2])
            line = line[2:]
    directions.append(line_directions)


def move(direction):
    x = 0
    y = 0
    for mv in direction:
        if mv == "w":
            x -= 1
        elif mv == "e":
            x += 1
        elif mv == "ne":
Ejemplo n.º 2
0
from aocd import get_data, submit

data = get_data(day=6, year=2015)
lines = data.splitlines()

grid = [[0 for _ in range(1000)] for _ in range(1000)]

for line in lines:
    parts = line.split()
    x1, y1 = map(int, parts[-3].split(","))
    x2, y2 = map(int, parts[-1].split(","))

    for i in range(x1, x2 + 1):
        for j in range(y1, y2 + 1):
            if parts[0] == "toggle":
                grid[i][j] += 2
            elif parts[1] == "on":
                grid[i][j] += 1
            elif parts[1] == "off":
                grid[i][j] = max(0, grid[i][j] - 1)

on = 0
for row in grid:
    for cell in row:
        if cell:
            on += cell

print(on)
submit(on, part="b", day=6, year=2015)
Ejemplo n.º 3
0
from aocd import get_data

data = get_data(year=2021, day=7).split(',')
data = tuple(map(int, data))
data = min(sum(map(lambda a: abs(a-i), data)) for i in range(min(data), max(data)))
print(data)
Ejemplo n.º 4
0
def data():
    data = aocd.get_data(day=DAY, year=YEAR).splitlines()
    return int(data[0]), data[1].split(',')
Ejemplo n.º 5
0
from aocd import get_data

my_list = get_data(year=2020, day=5).split("\n")


def seat_ID(string):
    row_string = string[0:7].replace("F", "0").replace("B", "1")
    column_string = string[7:10].replace("L", "0").replace("R", "1")
    row = int(row_string, 2)
    column = int(column_string, 2)
    return row * 8 + column


max = 0

for i in range(0, len(my_list)):
    sID = seat_ID(my_list[i])

    if (sID >= max):
        max = sID

print(max)
Ejemplo n.º 6
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 12 15:53:08 2020

@author: johan
"""


from aocd import get_data
import numpy as np

nav_data = get_data(day=12).split('\n')


test_data="""F10
N3
F7
R90
F11""".split('\n')



def first_challenge(data):
    debug = False
    direction = 0 # east = xpos>0 and ypos=0
    x,y = 0,0

    if debug : print(data)
    for line in data:
        dy = int(np.cos(np.deg2rad(direction)))
Ejemplo n.º 7
0
from aocd import get_data
from agc import AdventGuidanceComputer, EndOfProgram
from collections import Counter
aoc_data = get_data(year=2019, day=13).split(',')
screen = {}
arcade = AdventGuidanceComputer(aoc_data)()

try:
    while True:
        x = next(arcade)
        y = next(arcade)
        screen[(x, y)] = next(arcade)
except EndOfProgram:
    pass

print(Counter(screen.values())[2])

# import code
# code.interact(local=locals())
Ejemplo n.º 8
0
from aocd import get_data


def part1(inp):
    return min(sum(abs(x-c) for x in inp) for c in range(max(inp)))


def part2(inp):
    return min(sum(abs(x-c)*(abs(x-c)+1)//2 for x in inp) for c in range(max(inp)))


if __name__ == '__main__':
    data = get_data(day=7, year=2021)
    inp = list(map(int, data.split(',')))
    print(part1(inp))
    print(part2(inp))
Ejemplo n.º 9
0
def part_one(data: t.List[int]) -> int:
    data = sorted(data)
    # include outlet and device
    data = [0] + data + [data[-1] + 3]
    counter = Counter([jolt - data[i - 1] for i, jolt in enumerate(data)][1:])
    return counter[1] * counter[3]


def part_two(data: t.List[int]) -> int:
    data = sorted(data)
    valid = set(data)
    last = max(data)

    @lru_cache(maxsize=None)
    def combos(jolt):
        if jolt == last:
            return 1
        counter = 0
        for check in range(1, 4):
            if (check_jolt := jolt + check) in valid:
                counter += combos(check_jolt)
        return counter

    return combos(0)


if __name__ == "__main__":
    data = int_numbers(aocd.get_data(day=10, year=2020))
    print("Part 1: ", part_one(data))
    print("Part 2: ", part_two(data))
Ejemplo n.º 10
0
def part_one(schedules: Schedules) -> int:
    """Product of the id of the next bus by the time to wait for it."""
    wait, id_next = min(((id_ - schedules.timestamp % id_, id_)
                         for id_ in schedules.ids if id_), key=lambda di: di[0])
    return wait * id_next


def part_two(schedules: Schedules) -> int:
    """
    The earliest timestamp such that all of the listed bus IDs depart
    at offsets matching their positions in the list.
    """
    match_time: int = 0
    bus = [(lag, id_) for lag, id_ in enumerate(schedules.ids) if id_]
    _, step = bus.pop(0)
    while bus:
        for lag, id_ in reversed(bus):
            if (match_time + lag) % id_ == 0:
                step *= id_
                bus.remove((lag, id_))
        match_time += step
    return match_time - step


if __name__ == "__main__":
    print("--- Day 13: Shuttle Search ---")
    puzzle = parse(get_data(day=13, year=2020))
    print("Part One:", part_one(puzzle))
    print("Part Two:", part_two(puzzle))
Ejemplo n.º 11
0
from aocd import get_data
from aocd import submit
import itertools
import re

day = re.findall("day_(.*?).py", __file__)[0]
data_raw = get_data(day=day)

freq = 0
for expression in data_raw.splitlines():
    freq += int(expression)

print(freq)
submit(freq, level=1, day=day, year=2018)

freq = 0
freqs = {}
for expression in itertools.cycle(data_raw.splitlines()):
    freq += int(expression)
    if freq in freqs:
        break
    else:
        freqs[freq] = 1

print(freq)
submit(freq, level=2, day=day, year=2018)
Ejemplo n.º 12
0
# Setup
from aocd import get_data
from itertools import product
d = int(get_data(year=2018, day=11))

# Longform
power_lvl = lambda x, y: ((x + 10) * y + d) * (x + 10) // 100 % 10 - 5
power_lvls = {
    coord: power_lvl(*coord)
    for coord in product(range(1, 301), range(1, 301))
}
matrix_lvl = lambda x, y: sum(
    power_lvls[coord] for coord in product(range(x, x + 3), range(y, y + 3)))
matrix_lvls = {
    coord: matrix_lvl(*coord)
    for coord in product(range(1, 299), range(1, 299))
}
answer = max(matrix_lvls, key=lambda x: matrix_lvls[x])
# Golfed

# Output
print('{},{}'.format(*answer))
Ejemplo n.º 13
0
HH -> N
CB -> H
NH -> C
HB -> C
HC -> B
HN -> C
NN -> C
BH -> H
NC -> B
NB -> B
BN -> B
BB -> N
BC -> B
CC -> N
CN -> C"""
data = get_data(day=day, year=2021)
p, pairs = data.split("\n\n")
ans = 0

d = {}

for i in pairs.splitlines():
    k, v = i.split(" -> ")
    d[k] = v

for _ in range(10):
    new = ""
    for i in range(1, len(p)):
        new += p[i - 1] + d[p[i - 1] + p[i]]
    new += p[-1]
    p = new
Ejemplo n.º 14
0
from aocd import get_data

data = list(map(int, get_data(day=15, year=2020).split(",")))
dic = {element: data.index(element) for element in data}
length = len(data)
currentElement = 0

while length < 30000000 - 1:
    if currentElement in dic:
        index = dic[currentElement]
        dic[currentElement] = length
        currentElement = length - index
    else:
        dic[currentElement] = length
        currentElement = 0
    length += 1

    if length == 2019:
        print(currentElement)
print(currentElement)
Ejemplo n.º 15
0
from aocd import get_data
from pathlib import Path

# This is a standalone script meant to be run to automatically grab my data
# for a given year/day and dump it into an automatically-named file.

YEAR_NUM = 2019
DAY_NUM = 1

data = get_data(year=YEAR_NUM, day=DAY_NUM)

file_location = Path(f'inputs/advent{YEAR_NUM}_day{DAY_NUM:02d}_input.txt')
file_location.write_text(data)
Ejemplo n.º 16
0
import math
import itertools
import functools
from aocd import get_data, submit

data = get_data(day=10, year=2020)
lines = data.splitlines()
lines = [int(x) for x in lines]

lines = sorted(lines)

lines.insert(0, 0)
lines.append(max(lines) + 3)

s = 0
t = 0

for i in range(1, len(lines)):
    diff = lines[i] - lines[i-1]
    if diff == 3:
        t += 1
    if diff == 1:
        s += 1
print(s * t)


Ejemplo n.º 17
0

def get_groups(inp):
    groups = set()
    for conn in (b.union({a}) for a, b in inp.items()):
        if any(g.intersection(conn) for g in groups):
            for old_group in (g for g in groups.copy()
                              if g.intersection(conn)):
                groups.remove(old_group)
                conn = conn.union(old_group)
        groups.add(conn)
    return groups


def part1(inp):
    return next(len(g) for g in get_groups(inp) if 0 in g)


def part2(inp):
    return len(get_groups(inp))


if __name__ == '__main__':
    data = get_data(day=12, year=2017)
    inp = {
        int(a): frozenset(map(int, b.split(', ')))
        for a, b in (l.split(' <-> ') for l in data.splitlines())
    }
    print(part1(inp))
    print(part2(inp))
Ejemplo n.º 18
0
""" Advent of Code day 6 """

from aocd import get_data
from dotenv import load_dotenv


def day6_1(answers):
    """What is the sum of counts for each group to which anyone answered 'yes'? """
    return sum([len(set(answer.replace('\n', '')))
                for answer in answers])


def day6_2(answers):
    """What is the sum of counts for each group to which everyone answered 'yes'? """
    counts = []
    for answer in answers:
        setlist = [set(a) for a in answer.splitlines()]
        u = set.intersection(*setlist)
        counts.append(len(u))
    return sum(counts)


if __name__ == "__main__":
    load_dotenv()

    input_data = get_data(day=6, year=2020).split("\n\n")

    print(f"Part One: For each group, the number of questions to which anyone answered 'yes': {day6_1(answers=input_data)}")

    print(f"Part Two: For each group, the number of questions to which everyone answered 'yes': {day6_2(answers=input_data)}")
Ejemplo n.º 19
0
import aocd, itertools as it

data = """#############
#...........#
###B#C#B#D###
  #A#D#C#A#
  #########"""

data = aocd.get_data(year=2021, day=23)

data = data.split("\n")[2:-1]
data.insert(1, "#D#C#B#A#")
data.insert(2, "#D#B#A#C#")
data = [[am for am in list(line) if am in "ABCD"] for line in data]

# Final rooms
A, B, C, D = ["A", "B", "C", "D"]
# Hallway, LB and RB are back of L and R, LF and RF are front of L and R (near hall)
LB, LF, RB, RF, AB, BC, CD = ["LB", "LF", "RB", "RF", "AB", "BC", "CD"]

HALLWAY = [LB, LF, AB, BC, CD, RF, RB]
ROOM_SIZE = {
    A: 4,
    B: 4,
    C: 4,
    D: 4,
    LB: 1,
    LF: 1,
    RB: 1,
    RF: 1,
    AB: 1,
Ejemplo n.º 20
0
                next_seat = current_seat
                current = get_neighbors(input_matrix, x, y)
                adjacent_occupied = list(current).count("#")
                if current_seat == "#" and adjacent_occupied >= 4:
                    next_seat = "L"
                if current_seat == "L" and adjacent_occupied == 0:
                    next_seat = "#"
            new_row.append(next_seat)
            y += 1
        x += 1
        output_matrix.append(new_row)
    return output_matrix


if __name__ == '__main__':
    data = get_data(day=11).splitlines()
    # data_lines = data.splitlines()

    # data = [
    #     "L.LL.LL.LL",
    #     "LLLLLLL.LL",
    #     "L.L.L..L..",
    #     "LLLL.LL.LL",
    #     "L.LL.LL.LL",
    #     "L.LLLLL.LL",
    #     "..L.L.....",
    #     "LLLLLLLLLL",
    #     "L.LLLLLL.L",
    #     "L.LLLLL.LL"
    # ]
Ejemplo n.º 21
0
from aocd import get_data
data = get_data(day=5).split("\n")
plane = [[x * 8 + y for x in range(128)] for y in range(8)]
rows = list(range(128))
cols = list(range(8))


def traverse(tKey, tList):
    if len(tList) > 1:
        mid = len(tList) // 2
        if tKey[0] == "F" or tKey[0] == "L":
            return traverse(tKey[1:], tList[:mid])
        return traverse(tKey[1:], tList[mid:])
    return tList[0]


gSeat = 0
emptyList = []
for line in data:
    rInput, cInput = line[:7], line[7:]
    assignedRow = traverse(rInput, rows)
    assignedCol = traverse(cInput, cols)
    plane[assignedCol][assignedRow] = -1
    seat = assignedRow * 8 + assignedCol
    if seat > gSeat:
        gSeat = seat
print(f"The highest occupied seat ID is {gSeat}.")
for cols in plane:
    for seat in cols:
        if seat != -1:
            emptyList.append(seat)
Ejemplo n.º 22
0
    return len([k for k, v in danger_zone.items() if v >= 2])


def part_two(data: str) -> int:
    danger_zone = Counter(itertools.chain(*(line_algorithm(x, y) for x, y in parse(data))))
    return len([k for k, v in danger_zone.items() if v >= 2])


def test():
    test_input = """0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2"""
    answer_1 = part_one(test_input)
    answer_2 = part_two(test_input)
    assert answer_1 == 5, answer_1
    assert answer_2 == 12, answer_2


if __name__ == "__main__":
    test()
    data = aocd.get_data(day=5, year=2021)
    print("Part 1: ", part_one(data))
    print("Part 2: ", part_two(data))
Ejemplo n.º 23
0
import numpy as np
import re
from collections import Counter, defaultdict, deque
import itertools
from string import ascii_uppercase, ascii_lowercase
from copy import deepcopy
from blist import blist
from aocd import get_data
from functools import reduce

raw = get_data()
data = [line.strip('\n') for line in raw.splitlines()]

cart_locs = {}
cart_ops = {}
cart_ors = {}
carts = 0

vels = {'^': (-1, 0), '>': (0, 1), '<': (0, -1), 'v': (1, 0)}
ors = ['^', '>', 'v', '<']

for i in range(len(data)):
    line = data[i]
    k = -1
    for _ in range(line.count('^')):
        k = line.index('^', k + 1)
        cart_locs[carts] = (i, k)
        cart_ors[carts] = '^'
        carts += 1
    k = -1
    for _ in range(line.count('>')):
Ejemplo n.º 24
0
def main():
    data = aocd.get_data(year=2020, day=21).splitlines()
    parsed = parse(data)
    reduced = reduce(parsed, submit=True)
    solved = solve(reduced, submit=True)
Ejemplo n.º 25
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec  6 13:05:41 2020

@author: johan
"""
import string

from aocd import get_data
all_responses = get_data(day=6).split('\n\n')

test = """abc

a
b
c

ab
ac

a
a
a
a

b"""

test_responses = test.split('\n\n')

Ejemplo n.º 26
0
import collections as coll
import datetime as dt
import functools as ft
import itertools as it
import math
from operator import itemgetter as ig
import pprint as pp
import re
from copy import deepcopy
from utils import *
from functools import reduce
from aocd import get_data, submit

inp = get_data(day=24)

CHAR_TO_HEX_DELTA = {
    "ne": [-1, 0.5],
    "nw": [-1, -0.5],
    "e": [0, 1],
    "se": [1, 0.5],
    "sw": [1, -0.5],
    "w": [0, -1],
}

HEX_DELTA = [(-1, 0.5), (-1, -0.5), (0, 1), (1, 0.5), (1, -0.5), (0, -1)]


def solve1(d):
    inp = d.splitlines()
    grid = coll.defaultdict(lambda: False)
    for line in inp:
Ejemplo n.º 27
0
# Init
# %%
import numpy as np
from aocd import get_data, submit

get_data(day=,year=2020).splitlines()

# A
# %%


# %%
submit(answer)


# B
# %%


# %%
submit(answer)
Ejemplo n.º 28
0
    match packet.id:
        case 0:
            return sum(evaluate(p) for p in packet.subs)
        case 1:
            return reduce(operator.mul, (evaluate(p) for p in packet.subs))
        case 2:
            return min(evaluate(p) for p in packet.subs)
        case 3:
            return max(evaluate(p) for p in packet.subs)
        case 4:
            return packet.immediate
        case 5:
            return 1 if evaluate(packet.subs[0]) > evaluate(packet.subs[1]) else 0
        case 6:
            return 1 if evaluate(packet.subs[0]) < evaluate(packet.subs[1]) else 0
        case 7:
            return 1 if evaluate(packet.subs[0]) == evaluate(packet.subs[1]) else 0
        case x:
            raise NotImplementedError(x)


def part2(inp):
    return evaluate(inp)


if __name__ == '__main__':
    data = get_data(day=16, year=2021)
    inp = parse(''.join(format(int(d, 16), '04b') for d in data), 0)[0]
    print(part1(inp))
    print(part2(inp))
Ejemplo n.º 29
0
from aocd import get_data
from intcode import runProgram

program = list(map(int, get_data(day=13, year=2019).split(',')))
character = {0: " ", 1: "#", 2: "+", 3: "^", 4: "o"}
barX = ballX = 0
screen, outputs = [], []
program[0] = 2

def addPixel(x, y, value):
	global screen, ballX, barX
	if y >= len(screen):
		screen += [[" "]] * (y - len(screen) + 1) 
	if x >= len(screen[y]):
		screen[y] += [" "] * (x - len(screen[y]) + 1)
	screen[y][x] = character[value]
	if value == 4:
		ballX = x
	elif value == 3:
		barX = x

def processInput():
	global ballX, barX
	# print("\n".join(["".join(line) for line in screen]))
	return 1 if ballX > barX else (-1 if ballX < barX else 0)

def processOutput(output):
	global outputs, score
	outputs.append(output)
	if len(outputs) == 3 and outputs[0] == -1 and outputs[1] == 0:
		score = outputs[2]
Ejemplo n.º 30
0
from aocd import get_data
from collections import defaultdict, deque

data = get_data(day=20, year=2019)
grid = list(map(list, data.splitlines()))
w = len(grid[0])
h = len(grid)

portals = defaultdict(list)

for r, row in enumerate(grid):
    for c, char in enumerate(row):
        if char.isupper():
            # vertical portal
            if r + 1 < h and grid[r + 1][c].isupper():
                label = char + grid[r + 1][c]
                # entrance below label
                if r + 2 < h and grid[r + 2][c] == ".":
                    portals[label].append(((r + 1, c),(r + 2, c)))
                # entrance above label
                else:
                    portals[label].append(((r, c),(r - 1, c)))

            # horizontal portal
            if c + 1 < w and grid[r][c + 1].isupper():
                label = char + grid[r][c + 1]
                # entrance right of label
                if c + 2 < w and grid[r][c + 2] == ".":
                    portals[label].append(((r, c + 1),(r, c + 2)))
                # entrance left of label
                else: