Example #1
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)

    wx, wy = 10, 1
    x, y, a = 0, 0, 0
    for inst in inp:
        d, v = inst[0], int(inst[1:])
        if d == "N":
            wy += v
        if d == "S":
            wy -= v
        if d == "E":
            wx += v
        if d == "W":
            wx -= v
        if d == "R":
            for i in range(v // 90):
                owx = wx
                wx = +wy
                wy = -owx
        if d == "L":
            for i in range(v // 90):
                owx = wx
                wx = -wy
                wy = +owx
        if d == "F":
            x += v * wx
            y += v * wy

    return abs(x) + abs(y)
Example #2
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)

    s = count_trees(inp, (3, 1))

    return s
Example #3
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
    candidates = {}
    ing = []
    for recipe in inp:
        ingredients, allergens = recipe.split('(')
        ingredients = ingredients.strip().split(' ')
        allergens = allergens.strip()[9:-1].split(', ')
        for a in allergens:
            if a in candidates:
                candidates[a] = candidates[a].intersection(ingredients)
            else:
                candidates[a] = set(ingredients)
        ing += ingredients
    s = 0
    for i in ing:
        allergen = False
        for a in candidates:
            if i in candidates[a]:
                allergen = True
                break
        if not allergen:
            s += 1
    return s
Example #4
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
    done = False

    cur_idx = next(i for i, inst in enumerate(inp)
                   if "jmp" in inst or "nop" in inst)
    cid = 0
    while not done:
        if "jmp" in inp[cur_idx]:
            inp[cur_idx] = inp[cur_idx].replace("jmp", "nop")
        elif "nop" in inp[cur_idx]:
            inp[cur_idx] = inp[cur_idx].replace("nop", "jmp")

        prg = Prg(inp)
        acc, done = prg.run()

        if "jmp" in inp[cur_idx]:
            inp[cur_idx] = inp[cur_idx].replace("jmp", "nop")
        elif "nop" in inp[cur_idx]:
            inp[cur_idx] = inp[cur_idx].replace("nop", "jmp")

        cur_idx = next(i + cur_idx + 1
                       for i, inst in enumerate(inp[cur_idx + 1:])
                       if "jmp" in inst or "nop" in inst)

    return acc
Example #5
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)

    one_mask = 0
    zero_mask = 0
    mem = {}

    for inst in inp:
        k, v = inst.split("=")
        if k.strip() == "mask":
            one_mask = 0
            zero_mask = 0
            v = v.strip()
            assert len(v) == 36
            for i, c in enumerate(v):
                if c == "0":
                    zero_mask |= 1 << (36 - i - 1)
                elif c == "1":
                    one_mask |= 1 << (36 - i - 1)
                elif c == "X":
                    continue
                else:
                    raise Exception(f"Unknown char {c}")
            zero_mask = ~zero_mask
        else:
            loc = k.strip()[4:-1]
            v = int(v.strip())
            mem[loc] = (v | one_mask) & zero_mask

    return sum(v for v in mem.values())
Example #6
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
    inp = list(map(int, inp))

    for i, n in enumerate(inp[25:]):
        if not any(n - k in inp[i:i + 25] for k in inp[i:i + 25]):
            return n
    return inp
Example #7
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)

    slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]

    s = 1
    for sl in slopes:
        n = count_trees(inp, sl)
        print(sl, n)
        s *= n
    return s
Example #8
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
    mat = [get_seat_id(p) for p in inp]
    X = [s[0] for s in mat]
    Y = [s[1] for s in mat]
    xmin, xmax = min(X), max(X)
    ymin, ymax = min(Y), max(Y)

    for y in range(ymin, ymax):
        for x in range(xmin, xmax):
            if (x, y) not in mat:
                return seat_id((x, y))
Example #9
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
    bags = build_bags(inp)

    s = 0
    for k in bags:
        if k == 'shiny gold':
            continue
        s += bags[k].visit('shiny gold')

    print(bags['shiny gold'].visit('shiny gold', True))
    return s
Example #10
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
    candidates = {}
    ing = []
    for recipe in inp:
        ingredients, allergens = recipe.split('(')
        ingredients = ingredients.strip().split(' ')
        allergens = allergens.strip()[9:-1].split(', ')
        for a in allergens:
            if a in candidates:
                candidates[a] = candidates[a].intersection(ingredients)
            else:
                candidates[a] = set(ingredients)
        ing += ingredients
    for i in ing:
        allergen = False
        for a in candidates:
            if i in candidates[a]:
                allergen = True
                break
        if not allergen:
            for a in candidates:
                if i in candidates[a]:
                    candidates[a].remove(i)
    stack = list(candidates.items())

    def resolve(j, avail):
        f, cand = stack[j]
        for i in avail.intersection(cand):
            if len(avail) == 1:
                return [i]
            avail.remove(i)
            res = resolve(j + 1, avail)
            avail.add(i)
            if res is not False:
                return [i] + res
        return False

    def is_allergen(x):
        for a in candidates:
            if x in candidates[a]:
                return True
        return False

    ing = filter(is_allergen, ing)
    avail = set(ing)
    names = list(map(lambda x: x[0], stack))
    return ",".join(
        map(lambda x: x[0],
            sorted(zip(resolve(0, avail), names), key=lambda x: x[1])))
Example #11
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
    earliest = int(inp[0])
    notes = inp[1].split(',')
    min_bus = None
    for bus in notes:
        if bus == 'x':
            continue
        bus = int(bus)
        wait_time = bus - earliest % bus
        if min_bus == None or wait_time < (min_bus - earliest % min_bus):
            min_bus = bus
    return min_bus * (min_bus - earliest % min_bus)
Example #12
0
def solution2(inp):
    """Solves the second part of the challenge"""
    s1 = solution1(inp)

    inp = get_lines(inp)
    inp = list(map(int, inp))

    for i, n in enumerate(inp):
        k = 2
        s = sum(inp[i:i + k])
        while s < s1:
            k += 1
            s = sum(inp[i:i + k])
        if s == s1:
            nmin, nmax = min(inp[i:i + k]), max(inp[i:i + k])
            return nmin + nmax
Example #13
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
    notes = inp[1].split(",")

    offsets = {}
    for i, bus in enumerate(notes):
        if bus == 'x':
            continue
        bus = int(bus)
        offsets[bus] = i
    buses = set(offsets)
    old_buses = buses.copy()

    def search(bus, offset, t):
        if (t + offset) % bus == 0:
            buses.remove(bus)
            if len(buses) == 0:
                return True
            new_bus = max(buses)
            return search(new_bus, offsets[new_bus], t)
        return False

    cbus = max(buses)
    max_bus = cbus
    s = 100_000_000_000_000
    s = 0
    s = s - s % cbus - offsets[cbus]
    delta = cbus
    stack = buses.copy()
    stack.remove(cbus)
    sec_max = max(stack)
    while not search(max_bus, offsets[max_bus], offsets[max_bus]):
        buses = old_buses.copy()
        s += delta
        if (s + offsets[sec_max]) % sec_max == 0:
            if len(stack) != 0:
                cbus = max(stack)
                stack.remove(cbus)
                if len(stack) != 0:
                    sec_max = max(stack)
                else:
                    return s
                delta *= cbus

    return s - offsets[max(offsets)]
Example #14
0
def build_tiles(inp):
    inp = get_lines(inp)
    tiles = {}
    for l in inp:
        x, y = 0, 0
        while len(l) > 0:
            for d in dirs:
                if l.startswith(d[0]):
                    dx, dy = d[1]
                    y += dy
                    x += dx
                    l = l[len(d[0]):]
                    break
        coords = f"{x},{y}"
        if coords not in tiles:
            tiles[coords] = True
        else:
            tiles[coords] = not tiles[coords]
    return tiles
Example #15
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
    for i, r in enumerate(inp):
        inp[i] = list(r)

    change = True
    i = 0
    while change:
        i += 1
        change = False
        new_grid = copy.deepcopy(inp)
        for y in range(len(inp)):
            for x in range(len(inp[0])):
                if inp[y][x] == "L" and adjacents2(inp, x, y) == 0:
                    new_grid[y][x] = "#"
                    change = True
                if inp[y][x] == "#" and adjacents2(inp, x, y) >= 5:
                    new_grid[y][x] = "L"
                    change = True
        inp = new_grid

    return reduce(lambda acc, x: acc + sum([c == "#" for c in x]), inp, 0)
Example #16
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
    pkc, pkd = map(int, inp)

    pk = pkc
    bwd = []
    ls = 0
    while pk != 1:
        ls += 1
        N = 0
        new_pk = (N * 20201227 + pk)
        while new_pk % 7 != 0:
            N += 1
            new_pk = (N * 20201227 + pk)
        pk = new_pk // 7
        bwd.append(pk)

    v = 1
    for _ in range(ls):
        v *= pkd
        v = v % 20201227
    return v
Example #17
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)

    mem = {}
    for inst in inp:
        k, v = inst.split("=")
        if k.strip() == "mask":
            current_mask = v.strip()
        else:
            loc = bin(int(k.strip()[4:-1]))[2:]
            loc = "0" * (len(current_mask) - len(loc)) + loc
            v = int(v.strip())
            for i, c in enumerate(current_mask):
                if c == "1":
                    loc = loc[:i] + "1" + loc[i + 1:]
                elif c == "X":
                    loc = loc[:i] + "X" + loc[i + 1:]
            addresses = gen_addresses(loc)
            for add in addresses:
                mem[int(add, 2)] = v

    return sum(v for v in mem.values())
Example #18
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
    x, y, a = 0, 0, 0
    for inst in inp:
        d, v = inst[0], int(inst[1:])
        if d == "N":
            y += v
        if d == "S":
            y -= v
        if d == "E":
            x += v
        if d == "W":
            x -= v
        if d == "R":
            a -= v
        if d == "L":
            a += v
        if d == "F":
            x += int(v * cos(a * 2 * pi / 360))
            y += int(v * sin(a * 2 * pi / 360))

    return abs(x) + abs(y)
Example #19
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
    W = len(inp) + 7 * 2
    mid = W // 2
    start = mid - len(inp) // 2
    mat = np.zeros((W, W, W, W), dtype=int)
    start_mat = np.zeros((len(inp), len(inp[0])), dtype=int)
    for y, l in enumerate(inp):
        for x, c in enumerate(l):
            start_mat[y, x] = 0 if c == "." else 1
    mat[start:start+len(inp), start:start+len(inp), mid, mid] = start_mat
    new_mat = np.zeros((W, W, W, W), dtype=int)
    for i in range(6):
        for x, y, z, w in product(range(1, mat.shape[0] - 1), repeat=4):
            n_neighbors = np.sum(mat[y-1:y+2, x-1:x+2, z-1:z+2, w-1:w+2]) - mat[y, x, z, w]
            if mat[y, x, z, w] == 0 and n_neighbors == 3:
                new_mat[y, x, z, w] = 1
            elif mat[y, x, z, w] == 1 and n_neighbors in [2, 3]:
                new_mat[y, x, z, w] = 1
        mat = new_mat
        new_mat = np.zeros((W, W, W, W), dtype=int)
    return np.sum(mat)
Example #20
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
Example #21
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
    prg = Prg(inp)
    acc, _ = prg.run()
    return acc
Example #22
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)
    return sum(
        map(lambda x: x[0], [eval(equ.replace(" ", ""), True) for equ in inp]))
Example #23
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
    res = [eval(parenthesize(e.replace(" ", "")), True)[0] for e in inp]
    return sum(res)
Example #24
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
    bags = build_bags(inp)

    return bags['shiny gold'].visit2() - 1
Example #25
0
def solution2(inp):
    """Solves the second part of the challenge"""
    inp = get_lines(inp)
Example #26
0
def solution1(inp):
    """Solves the first part of the challenge"""
    inp = get_lines(inp)

    return max([seat_id(get_seat_id(p)) for p in inp])