예제 #1
0
    g = GameBoy(code)
    g.fix_corrupted_code()
    return g.run()[0]


if __name__ == "__main__":
    from aocd.models import Puzzle

    test_data = """nop +0
                   acc +1
                   jmp +4
                   acc +3
                   jmp -3
                   acc -99
                   acc +1
                   jmp -4
                   acc +6"""

    assert solve1(test_data) == 5
    assert solve2(test_data) == 8

    puz8 = Puzzle(2020, 8)
    data = puz8.input_data
    puz8.answer_a = solve1(data)
    puz8.answer_b = solve2(data)

    with open('2020/inputs/Day8_tanakov.txt') as f:
        inputs = f.read()
        print(solve1(inputs))
        print(solve2(inputs))
예제 #2
0
        62
        55
        65
        95
        102
        117
        150
        182
        127
        219
        299
        277
        309
        576'''
    nums = list(map(int, t.split('\n')))

    assert find_bad(nums, 5) == 127
    assert find_run(nums, 127) == [15, 25, 47, 40]
    assert list(find_run_fast(nums, 127)) == [15, 25, 47, 40]

    puz = Puzzle(2020, 9)
    nums = list(map(int, puz.input_data.split('\n')))

    target = find_bad(nums, 25)
    puz.answer_a = target
    print(f'Part 1: {puz.answer_a}')

    run = find_run(nums, target)
    puz.answer_b = min(run) + max(run)
    print(f'Part 2: {puz.answer_b}')
예제 #3
0
from aocd.models import Puzzle

import intcode2019

from functools import reduce
from operator import xor
import string
import re
from copy import deepcopy
from collections import defaultdict, Counter,deque
from itertools import product, permutations
import queue
puzzle = Puzzle(year=2019,day=8)
program = puzzle.input_data

width, height = 25, 6
num_layer = len(program)//width//height

num_zeros = width*height+1
answer_a = 0

for i_layer in range(num_layer):
    layer = program[i_layer*width*height:(i_layer+1)*width*height]
    cond = Counter(layer)
    if cond['0'] < num_zeros:
        num_zeros = cond['0']
        answer_a = cond['1']*cond['2']
# puzzle.answer_a = answer_a


answer_b = ['2' for i in range(width*height)]
예제 #4
0
                step = move(x, i, x_coords, y_coords, step, data)
            y += int(point[1:])
        elif point[0] == 'D':
            for i in range(y, y - int(point[1:]), -1):
                step = move(x, i, x_coords, y_coords, step, data)
            y -= int(point[1:])
        elif point[0] == 'R':
            for i in range(x, x + int(point[1:])):
                step = move(i, y, x_coords, y_coords, step, data)
            x += int(point[1:])
        elif point[0] == 'L':
            for i in range(x, x - int(point[1:]), -1):
                step = move(i, y, x_coords, y_coords, step, data)
            x -= int(point[1:])
    return coo_matrix((data, (y_coords, x_coords)), shape=(dim, dim))


def move(x, y, x_coords, y_coords, step, data):
    x_coords.append(x)
    y_coords.append(y)
    data.append(step)
    step += 1
    return step


if __name__ == '__main__':
    puzzle = Puzzle(year=2019, day=3)
    cables = list(puzzle.input_data.splitlines())
    puzzle.answer_a = int(distance(cables))
    puzzle.answer_b = steps(cables)
예제 #5
0
                   F7
                   R90
                   F11"""

    tonys_test_data = """F1
                        N1
                        E1
                        S1
                        W1
                        R90
                        F1
                        R180
                        F1
                        R270
                        F1
                        L90
                        F1
                        L180
                        F2
                        L270
                        F3"""

    assert solve1(test_data) == 25
    assert solve2(test_data) == 286
    assert solve2(tonys_test_data) == 42

    puz12 = Puzzle(2020, 12)
    data = puz12.input_data
    puz12.answer_a = solve1(data)
    # puz12.answer_b = solve2(data)
예제 #6
0
def test_get_answer_not_existing(aocd_dir, requests_mock):
    requests_mock.get("https://adventofcode.com/2017/day/13")
    puzzle = Puzzle(day=13, year=2017)
    with pytest.raises(AttributeError):
        puzzle.answer_b
예제 #7
0
def test_get_answer_not_existing_ok_on_25dec(aocd_dir, requests_mock):
    answer_path = aocd_dir / "thetesttoken" / "2017_25a_answer.txt"
    answer_path.write_text("yeah")
    puzzle = Puzzle(day=25, year=2017)
    assert not puzzle.answer_b
    assert puzzle.answers == ("yeah", "")
예제 #8
0
    twos = 0
    threes = 0
    for box in boxes:
        counts = Counter(box).values()
        if 2 in counts:
            twos += 1
        if 3 in counts:
            threes += 1
    return twos * threes


def part2(boxes):
    """
    >>> part2(["abcde", "fghij", "klmno", "pqrst", "fguij", "axcye", "wvxyz"])
    'fgij'
    """
    for box1, box2 in combinations(boxes, 2):
        shared = [char1 for char1, char2 in zip(box1, box2) if char1 == char2]
        if len(shared) == len(box1) - 1:
            return ''.join(shared)


if __name__ == "__main__":
    import doctest
    doctest.testmod()

    puzzle = Puzzle(year=2018, day=2)
    boxes = puzzle.input_data.split('\n')
    puzzle.answer_a = part1(boxes)
    puzzle.answer_b = part2(boxes)
예제 #9
0
from aocd.models import Puzzle

from computer import Computer
from util import inspect


def part1(program):
    result = Computer(program, input=1).run()
    if isinstance(result, list):
        raise Exception(f"Opcode errors: {result}")
    return result


def part2(program):
    return Computer(program, input=2).run()


if __name__ == "__main__":
    import doctest
    doctest.testmod()

    puzzle = Puzzle(year=2019, day=9)
    program = [int(val) for val in puzzle.input_data.split(',')]
    puzzle.answer_a = inspect(part1(program), prefix='Part 1: ')
    puzzle.answer_b = inspect(part2(program), prefix='Part 2: ')
예제 #10
0
def test_check_guess_against_saved_incorrect(mocker):
    mocker.patch("aocd.models.Puzzle._get_answer", return_value="two")
    puzzle = Puzzle(year=2019, day=4)
    rv = puzzle._check_guess_against_existing("one", "a")
    assert "Part a already solved with different answer: two" in rv
예제 #11
0
import re
from math import gcd
from collections import defaultdict

from aocd.models import Puzzle

puzzle = Puzzle(year=2019, day=12)
in1 = puzzle.input_data.split('\n')

# in1 = '''<x=-1, y=0, z=2>
# <x=2, y=-10, z=-7>
# <x=4, y=-8, z=8>
# <x=3, y=5, z=-1>'''.split('\n')
# in1 = '''<x=-8, y=-10, z=0>
# <x=5, y=5, z=10>
# <x=2, y=-7, z=3>
# <x=9, y=-8, z=-3>'''.split('\n')


class Moon:
    def __init__(self, pos, velo=None, name=None):
        if velo is None:
            velo = [0] * len(pos)
        self.position = pos
        self.velocity = velo
        self.name = name

    def apply_gravity(self, other):
        for axis in range(len(self.position)):
            if self.position[axis] < other.position[axis]:
                self.velocity[axis] += 1
예제 #12
0
def test_check_guess_against_saved_correct(mocker):
    mocker.patch("aocd.models.Puzzle._get_answer", return_value="one")
    puzzle = Puzzle(year=2019, day=4)
    rv = puzzle._check_guess_against_existing("one", "a")
    assert rv == "Part a already solved with same answer: one"
예제 #13
0
def test_check_guess_against_empty(mocker):
    mocker.patch("aocd.models.Puzzle._get_answer", return_value="")
    puzzle = Puzzle(year=2019, day=4)
    rv = puzzle._check_guess_against_existing("one", "a")
    assert rv is None
예제 #14
0
def test_check_guess_against_unsolved(mocker):
    mocker.patch("aocd.models.Puzzle._get_answer",
                 side_effect=PuzzleUnsolvedError)
    puzzle = Puzzle(year=2019, day=4)
    rv = puzzle._check_guess_against_existing("one", "a")
    assert rv is None
예제 #15
0

test_input = """light red bags contain 1 bright white bag, 2 muted yellow bags.
faded blue bags contain no other bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
dotted black bags contain no other bags.
"""

test_input2 = """shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags."""

if __name__ == '__main__':
    puzzle = Puzzle(year=2020, day=7)
    if False:
        array = parse_input(test_input)
    else:
        array = parse_input(puzzle.input_data)
    # print(array)
    solve_puzzle_one(array)
    solve_puzzle_two(array)
예제 #16
0

def part1(s):
    total = 0
    for dims in parse(s):
        areas = list(
            map(lambda x: x[0] * x[1], itertools.permutations(dims, 2)))
        total += sum(areas) + min(areas)
    return total


def part2(s):
    total = 0
    for dims in parse(s):
        perims = list(
            map(lambda x: 2 * (x[0] + x[1]), itertools.permutations(dims, 2)))
        total += min(perims) + math.prod(dims)
    return total


if __name__ == '__main__':
    from aocd.models import Puzzle

    puz = Puzzle(2015, 2)

    puz.answer_a = part1(puz.input_data)
    print(f'Part 1: {puz.answer_a}')

    puz.answer_b = part2(puz.input_data)
    print(f'Part 2: {puz.answer_b}')
예제 #17
0
def test_get_answer(aocd_dir):
    saved = aocd_dir / "thetesttoken" / "2017_13b_answer.txt"
    saved.write_text("the answer")
    puzzle = Puzzle(day=13, year=2017)
    assert puzzle.answer_b == "the answer"
예제 #18
0

def solve1(input):
    prob = Problem.parse_problem(input)
    prob.rules['0'] = prob.rules['0'].expand_rule(prob.rules)
    return sum([bool(re.fullmatch(prob.rules['0'].terms, message)) for message in prob.messages])


if __name__ == "__main__":

    from aocd.models import Puzzle

    test_input = """0: 4 1 5
                    1: 2 3 | 3 2
                    2: 4 4 | 5 5
                    3: 4 5 | 5 4
                    4: "a"
                    5: "b"

                    ababbb
                    bababa
                    abbbab
                    aaabbb
                    aaaabbb"""

    assert solve1(test_input) == 2

    puz19 = Puzzle(2020, 19)
    data = puz19.input_data
    # puz19.answer_a = solve1(data)
    # puz19.answer_b = solve2(data)
예제 #19
0
def test_puzzle_view(mocker):
    browser_open = mocker.patch("aocd.models.webbrowser.open")
    puzzle = Puzzle(year=2019, day=4)
    puzzle.view()
    browser_open.assert_called_once_with("https://adventofcode.com/2019/day/4")
예제 #20
0
            b = get_value(mode2,position+2,code,relative_base)
            c = get_location(mode3,position+3,code,relative_base)
            if(a == b):
                code[c]=1
            else:
                code[c]=0
            position+=4
        elif(opcode == 9):
            a = get_value(mode1,position+1,code,relative_base)
            relative_base+=a
            position+=2
        else:
            print("wrong op" + str(instruction))


data = Puzzle(year=2019, day=21).input_data.split(',')
code = list(map(lambda x : int(x),data))+list(np.zeros(10000))
print(code)

inputs = """NOT C J
AND D J
NOT B T
AND D T
OR T J
NOT A T
AND D T
OR T J
RUN
"""
inputs = list(map(lambda x: ord(x),inputs))
예제 #21
0
def test_setattr_submits(mocker, requests_mock):
    requests_mock.get("https://adventofcode.com/2017/day/7")
    puzzle = Puzzle(year=2017, day=7)
    mock = mocker.patch("aocd.models.Puzzle._submit")
    puzzle.answer_a = 4321
    mock.assert_called_once_with(part="a", value="4321")
예제 #22
0
                if not set(deps[item]) - done:
                    #                      print('Item available:', item)
                    avail = sorted(set(avail) | set(item))

    return total_time


if __name__ == '__main__':
    from aocd.models import Puzzle

    testdata = '''Step C must be finished before step A can begin.
    Step C must be finished before step F can begin.
    Step A must be finished before step B can begin.
    Step A must be finished before step D can begin.
    Step B must be finished before step E can begin.
    Step D must be finished before step E can begin.
    Step F must be finished before step E can begin.'''.split('\n')
    graph, deps = parse(testdata)

    assert topo_sort(graph) == list('CABDFE')
    assert process_queue(graph, deps, 2, 0) == 15

    puz = Puzzle(2018, 7)
    graph, deps = parse(puz.input_data.split('\n'))

    puz.answer_a = ''.join(topo_sort(graph))
    print(f'Part 1: {puz.answer_a}')

    puz.answer_b = process_queue(graph, deps)
    print(f'Part 2: {puz.answer_b}')
예제 #23
0
        grouped[day % 7] += ready

        # These two variables account being shifted into each other and eventually
        # included accounts for the two day + one propgation cycle delay before having
        # offspring.
        ready = aging
        aging = new

    return sum(grouped) + ready + aging


if __name__ == '__main__':
    from aocd.models import Puzzle

    sample = '''3,4,3,1,2'''

    assert age(parse(sample), 18) == 26

    test_a, test_b = run(sample)
    assert test_a == 5934
    assert test_b == 26984457539

    puz = Puzzle(2021, 6)
    part_a, part_b = run(puz.input_data)

    puz.answer_a = part_a
    print(f'Part 1: {puz.answer_a}')

    puz.answer_b = part_b
    print(f'Part 2: {puz.answer_b}')
예제 #24
0
                full_full_grid[i].append((
                    col + (n + 1)) if (col + (n + 1)) <= 9 else (col +
                                                                 (n + 1)) - 9)

    ffg_str = "\n".join(["".join(map(str, row)) for row in full_full_grid])
    return ffg_str


def solve2(input_data):
    return solve1(construct_full_grid(input_data))


if __name__ == "__main__":
    from aocd.models import Puzzle

    puzzle = Puzzle(2021, 15)

    test_data = """1163751742
    1381373672
    2136511328
    3694931569
    7463417111
    1319128137
    1359912421
    3125421639
    1293138521
    2311944581"""

    assert solve1(test_data) == 40
    assert solve2(test_data) == 315
예제 #25
0
        for y in [-1, 1]:
            map[start + x + y * 1j] = str(i)
            i += 1

    starts = tuple(k for k in map if map[k] in '1234')
    map_keys = set(k for k in KEYS if k in map.values())
    num_keys = len(map_keys)
    kpos = {map[p]: p for p in map if map[p] in KEYS + '1234'}

    g = build_graph(map, kpos)
    paths = build_paths(g, map_keys, kpos)

    print(f'build time: {perf_counter() - t:.2f}s')
    t = perf_counter()

    # part 2
    n = min(n for n in multisearch0())
    part_b = n
    print(f'part 2: {n}')
    # 2020
    # 70s
    # now .1s

    print(f'time: {perf_counter() - t:.2f}s')
    return part_a, part_b


if __name__ == '__main__':
    main()
    print(Puzzle(2019, 18).answers)
예제 #26
0
#!/usr/bin/env python3
"""
    - Make sure to 'export AOC_SESSION=<your_aoc_token>'
    - Run the script in an ipython session using '%run <name>'
"""

from aocd.models import Puzzle
from typing import NamedTuple, List, Dict
from collections import Counter, defaultdict

# Enter year and day
puzzle = Puzzle(2020, 16)

data = puzzle.input_data.split('\n\n')
######################################################################
#   Part 1
######################################################################
ranges = [(int(x.split('-')[0]), int(x.split('-')[1]))
          for l in data[0].split('\n') for x in l.split(": ")[1].split(' or ')]

nums = [
    x for l in data[1].split('\n')[1:] + data[2].split('\n')[1:]
    for x in list(map(int, l.split(',')))
]

D = set()
for i in range(max(nums)):
    for j, k in ranges:
        if j <= i <= k:
            D.add(i)
예제 #27
0
from aocd.models import Puzzle

input: str = Puzzle(day=17, year=2020).input_data
input = input.splitlines()
n = len(input)
m = len(input[0])
displacement = (n - 1) // 2
originalNodes = set()
for i in range(n):
    for j in range(m):
        if input[i][j] == "#":
            originalNodes.add((j - displacement, i - displacement, 0))


def active_neighbours(point, allThePoints):
    if len(point) == 3:
        x, y, z = point
        w = None
    else:
        x, y, z, w = point
    neighbours = []
    for X in [x - 1, x, x + 1]:
        for Y in [y - 1, y, y + 1]:
            for Z in [z - 1, z, z + 1]:
                if w is not None:
                    for W in [w - 1, w, w + 1]:
                        neighbours.append(((X, Y, Z, W), point))
                else:
                    neighbours.append(((X, Y, Z), point))
    return len(
        list(
예제 #28
0
    test_vals = process_input(
        """be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce"""
    )

    assert count_unique(test_vals) == 26

    puz = Puzzle(2021, 8)

    data = process_input(puz.input_data)

    puz.answer_a = count_unique(data)
    print(f"Part 1: {puz.answer_a}")

    test_val = process_input(
        """acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"""
    )[0]

    deductions = deduce_line(test_val[0])
    assert decode_line(test_val[1], deductions) == "5353"
    assert compute_lines([test_val]) == 5353

    puz.answer_b = compute_lines(data)
예제 #29
0
from aocd.models import Puzzle
import intcode2019
from functools import reduce
from operator import xor
import string
import re
from copy import deepcopy
from collections import defaultdict, Counter, deque
from itertools import product, permutations
from math import sqrt, atan2, pi
from functools import cmp_to_key
from fractions import gcd

puzzle = Puzzle(year=2019, day=10)
ast_map = puzzle.input_data.split('\n')

x_max, y_max = len(ast_map[0]), len(ast_map)

dirs = []


def add_to_dirs(x, y):
    found = False
    for dx, dy in dirs:
        if dx * y == dy * x and dx * x >= 0 and dy * y >= 0:
            found = True
            break
    if not found:
        dirs.append((x, y))

예제 #30
0
from aocd.models import Puzzle

from functools import reduce
from operator import xor
import string
import re
from copy import deepcopy
from collections import defaultdict, deque, Counter, OrderedDict
import queue
from itertools import combinations
from math import sqrt, floor, ceil

puzzle = Puzzle(year=2015,day=20).input_data.split('\n')

num_factors = dict()

def find_num_factors(num):
    temp1=sqrt(num)
    temp2=int(temp1)
    factors=set()
    factors.add(1)
    factors.add(num)
    if(temp1==temp2):
        for i in range (2,temp2):
            if(num%i==0):
                factors.add(i)
                factors.add(num//i)
        factors.add(temp2)
    else:
        for i in range (2,temp2+1):
            if(num%i==0):