Example #1
0
def test_ints():
    s = 'What they-43 were 8 saying was <albeit 7> (9) mi85ninte and -2'

    nums = ints(s)
    expected = [-43, 8, 7, 9, 85, -2]

    assert (expected == nums)
Example #2
0
def load_data(quiet=True):
    find_path_to_helpers(quiet=quiet)
    if __package__:
        from ..helpers import get_input, ints
    else:
        from helpers import get_input, ints

    data = ints(get_input())

    return data
Example #3
0
def solve(rulelist, messages):
    rules = {}

    for rule in rulelist:
        if '"' in rule:
            l = rule.split(':')
            n = int(l[0])
            let = l[1].split('"')[-2]
            rules[n] = [let]

    while len(rules) < len(rulelist):
        for rule in rulelist:
            l = rule.split(':')
            n = int(l[0])

            if n in rules:
                continue

            nums = ints(l[1])

            if any(i not in rules for i in nums):
                continue

            parts = l[1].split('|')
            variants = []

            for x, part in enumerate(parts):
                partnums = ints(part)

                ss = ['']

                for partnum in partnums:
                    newss = []
                    for p in product(ss, rules[partnum]):
                        newss.append(''.join(p))
                    ss = newss

                variants.extend(ss)

            rules[n] = variants

    return sum(m in rules[0] for m in messages)
Example #4
0
def solve(passports):
    required = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}

    valid = 0

    for passport in passports:
        characteristics = set()
        good = True

        for line in passport:
            for pair in line:
                k, v = list(pair.split(':'))
                characteristics.add(k)
                if k == 'byr':
                    if len(v) != 4 or not 1920 <= int(v) <= 2002:
                        good = False
                if k == 'iyr':
                    if len(v) != 4 or not 2010 <= int(v) <= 2020:
                        good = False
                if k == 'eyr':
                    if len(v) != 4 or not 2020 <= int(v) <= 2030:
                        good = False
                if k == 'hgt':
                    nums = ints(v)
                    cm = len(v) > 1 and v[-2:] == 'cm'
                    inch = len(v) > 1 and v[-2:] == 'in'

                    if not (cm or inch):
                        good = False

                    if cm and not 150 <= nums[0] <= 193:
                        good = False
                    if inch and not 59 <= nums[0] <= 76:
                        good = False
                if k == 'hcl':
                    if len(v) != 7 or v[0] != '#' or any(
                            c not in '0123456789abcdef' for c in v[1:]):
                        good = False
                if k == 'pid':
                    if len(v) != 9 or any(c not in '0123456789' for c in v):
                        good = False
                if k == 'ecl':
                    if v not in [
                            'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'
                    ]:
                        good = False

        if good and len(characteristics & required) == len(required):
            valid += 1

    return valid
Example #5
0
    return addresses


def solve(instructions):
    memory = defaultdict(int)
    mask = ''

    for ins in instructions:
        if len(ins) == 1:
            mask = ins[0]
            continue

        addr, val = ins

        for address in get_addresses(addr, mask):
            memory[address] = val

    return sum(memory.values())

if __name__ == '__main__':
    instructions = []

    with open('14.txt') as f:
        for line in f.readlines():
            if 'mask' in line:
                instructions.append([line.split()[-1]])
            else:
                instructions.append(ints(line))

    print(solve(instructions))
Example #6
0
from itertools import combinations, permutations, product

from helpers import distance, distance_sq, eight_neighs, eight_neighs_bounded, grouped_lines, ints, manhattan, neighs, neighs_bounded


def solve(nums, iters):
    spoken = defaultdict(list)
    prev = -1

    for x in range(iters):
        if x < len(nums):
            spoken[nums[x]].append(x)
            prev = nums[x]
            continue

        if len(spoken[prev]) == 1:
            spoken[0].append(x)
            prev = 0
        else:
            d = spoken[prev][-1] - spoken[prev][-2]
            spoken[d].append(x)
            prev = d

    return prev


if __name__ == '__main__':
    with open('15.txt') as f:
        for line in f.readlines():
            print(solve(ints(line), 30000000))
Example #7
0
if __name__ == '__main__':
    fields = []
    fieldsfound = False
    your = []
    other = []

    with open('16.txt') as f:
        for line in f.readlines():
            if not line.strip():
                fieldsfound = True
            elif not fieldsfound:
                fieldslist = line.split()
                name = ''

                for field in fieldslist:
                    if field[-1] == ':':
                        name += ' ' + field[:-1]
                        break
                    name += ' ' + field

                nums = [abs(n) for n in ints(line)]

                fields.append([name.strip()] + nums)

            elif not your:
                your = ints(line)
            elif ints(line):
                other.append(ints(line))

    print(solve(fields, your, other))
Example #8
0
from collections import Counter, defaultdict, deque
from functools import reduce
from heapq import heappop, heappush
from itertools import combinations, permutations, product

from helpers import distance, distance_sq, eight_neighs, eight_neighs_bounded, grouped_lines, ints, manhattan, neighs, neighs_bounded


def solve(start, buses):
    best = [10**10, 10**10]

    for bus in buses:
        times = (start // bus) + 1

        wait = (times * bus) % start

        if wait < best[1]:
            best = [wait * bus, wait]

    return best[0]


if __name__ == '__main__':
    lines = open('13.txt').readlines()

    start = int(lines[0])
    buses = ints(lines[1])

    print(solve(start, buses))
Example #9
0
def solve(rulelist, messages):
    for x, rule in enumerate(rulelist):
        if rule == '8: 42':
            rulelist[x] = '8: 42 | 42 8'
        elif rule == '11: 42 31':
            rulelist[x] = '11: 42 31 | 42 11 31'

    rules = {}

    for rule in rulelist:
        if '"' in rule:
            l = rule.split(':')
            n = int(l[0])
            let = l[1].split('"')[-2]
            rules[n] = [let]

    longest = max(len(m) for m in messages)

    while len(rules) < len(rulelist) - 3:
        for rule in rulelist:
            l = rule.split(':')
            n = int(l[0])

            if n in rules:
                continue

            nums = ints(l[1])

            if any(i not in rules for i in nums):
                continue

            parts = l[1].split('|')
            variants = []

            for x, part in enumerate(parts):
                partnums = ints(part)

                ss = ['']

                for partnum in partnums:
                    newss = []
                    for p in product(ss, rules[partnum]):
                        newss.append(''.join(p))
                    ss = newss

                variants.extend(ss)

            rules[n] = variants

    startsforlen = [set() for _ in range(longest + 1)]
    endsforlen = [set() for _ in range(longest + 1)]

    for m in messages:
        for x in range(1, len(m)):
            startsforlen[x].add(m[:x])
            endsforlen[x].add(m[-x:])

    zeroleft = {r: 1 for r in rules[42]}

    while True:
        newzeroleft = {}

        for s1, count in zeroleft.items():
            for s2 in rules[42]:
                u = s1 + s2

                if u not in zeroleft and len(
                        u) < longest and u in startsforlen[len(u)]:
                    newzeroleft[u] = count + 1

        if not newzeroleft:
            break

        for k, v in newzeroleft.items():
            zeroleft[k] = v

    zeroright = {r: 1 for r in rules[31]}

    while True:
        newzeroright = {}

        for s1, count in zeroright.items():
            for s2 in rules[31]:
                u = s2 + s1

                if u not in zeroright and len(u) < longest and u in endsforlen[
                        len(u)]:
                    newzeroright[u] = count + 1

        if not newzeroright:
            break

        for k, v in newzeroright.items():
            zeroright[k] = v

    rules[0] = []

    for s, scount in zeroleft.items():
        for t, tcount in zeroright.items():
            if scount > tcount:
                rules[0].append(s + t)

    return sum(m in rules[0] for m in messages)
Example #10
0
            for field in fields:
                if (field[0] <= val <= abs(field[1])
                        or field[2] <= val <= -field[3]):
                    valid = True
                    break

            if not valid:
                tot += val

    return tot


if __name__ == '__main__':
    fields = []
    fieldsfound = False
    your = []
    other = []

    with open('16.txt') as f:
        for line in f.readlines():
            if not line.strip():
                fieldsfound = True
            if not fieldsfound:
                fields.append(ints(line))
            elif not your:
                your = ints(line)
            else:
                other.append(ints(line))

    print(solve(fields, other))
Example #11
0
        count = 0

        for y in range(96 - mheight + 1):
            for x in range(96 - mwidth + 1):
                if image[y][x:x + mwidth] == monster[0] and image[
                        y + 1][x:x + mwidth] == monster[1] and image[
                            y + 2][x:x + mwidth] == monster[2]:
                    count += 1

        c[count] += 1
    print(c)
    tiles = {}
    tile = []
    id = -1

    with open('20.txt') as f:
        for line in f.readlines():
            if line.strip():
                if ints(line):
                    id = ints(line)[0]
                else:
                    tile.append(line.strip())
            else:
                tiles[id] = tile
                id = -1
                tile = []

    tiles[id] = tile

    print(solve(tiles))
Example #12
0
from itertools import combinations, permutations, product

from helpers import distance, distance_sq, eight_neighs, eight_neighs_bounded, grouped_lines, ints, manhattan, neighs, neighs_bounded


def solve(nums, iters):
    spoken = defaultdict(list)
    prev = -1

    for x in range(iters):
        if x < len(nums):
            spoken[nums[x]].append(x)
            prev = nums[x]
            continue

        if len(spoken[prev]) == 1:
            spoken[0].append(x)
            prev = 0
        else:
            d = spoken[prev][-1] - spoken[prev][-2]
            spoken[d].append(x)
            prev = d

    return prev


if __name__ == '__main__':
    with open('15.txt') as f:
        for line in f.readlines():
            print(solve(ints(line), 2020))
Example #13
0
def solve(rulelist, messages):
    for x, rule in enumerate(rulelist):
        if rule == '8: 42':
            rulelist[x] = '8: 42 | 42 8'
        elif rule == '11: 42 31':
            rulelist[x] = '11: 42 31 | 42 11 31'

    rules = {}

    for rule in rulelist:
        if '"' in rule:
            l = rule.split(':')
            n = int(l[0])
            let = l[1].split('"')[-2]
            rules[n] = [let]

    longest = max(len(m) for m in messages)

    while len(rules) < len(rulelist)-3:
        for rule in rulelist:
            l = rule.split(':')
            n = int(l[0])

            if n in rules:
                continue

            nums = ints(l[1])

            if any(i not in rules for i in nums):
                continue

            parts = l[1].split('|')
            variants = []

            for x, part in enumerate(parts):
                partnums = ints(part)

                ss = ['']

                for partnum in partnums:
                    newss = []
                    for p in product(ss, rules[partnum]):
                        newss.append(''.join(p))
                    ss = newss

                variants.extend(ss)

            rules[n] = variants

    eight = {v: 1 for v in rules[42]}

    startsforlen = [set() for _ in range(longest+1)]
    endsforlen = [set() for _ in range(longest+1)]

    for m in messages:
        for x in range(1, len(m)):
            startsforlen[x].add(m[:x])
            endsforlen[x].add(m[-x:])

    while True:
        neweight = {}
        done = True

        for s, i in eight.items():
            for t, j in eight.items():
                st = s + t
                l = len(st)
                if l <= longest and st in startsforlen[l]:
                    neweight[st] = i+j

        for s, i in neweight.items():
            if s not in eight:
                done = False
                eight[s] = i

        if done:
            break

    rules[8] = [e for e in eight.keys()]

    rules[0] = set()

    ses = {r: 1 for r in rules[42]}

    while True:
        newses = {}

        for s1, count in ses.items():
            for s2 in rules[42]:
                u = s1+s2

                if u not in ses and len(u) < longest and u in startsforlen[len(u)]:
                    newses[u] = count+1

        if not newses:
            break

        for k, v in newses.items():
            ses[k] = v

    ts = {r: 1 for r in rules[31]}

    while True:
        newts = {}

        for s1, count in ts.items():
            for s2 in rules[31]:
                u = s2+s1

                if u not in ts and len(u) < longest and u in endsforlen[len(u)]:
                    newts[u] = count+1

        if not newts:
            break

        for k, v in newts.items():
            ts[k] = v

    rules[0] = []

    for s, scount in ses.items():
        for t, tcount in ts.items():
            if scount > tcount:
                rules[0].append(s+t)

    return sum(m in rules[0] for m in messages)