Example #1
0
 def test_pass2(self):
     data = day2.parse(read_file("02", "2"))
     resultat = 0
     for noun in range(0, len(data)):
         for verb in range(0, len(data)):
             result = day2.solve(data, noun, verb)
             if result[0] == 19690720:
                 resultat = 100*noun + verb
                 break
             data = day2.parse(read_file("02", "2"))
         if resultat != 0:
             break
     self.assertEqual(result, 7603)
def solve():
    input = read_file("14")

    req = defaultdict(list)

    for line in input:
        line = list(line)
        while "," in line:
            line.remove(",")
        line = "".join(line)

        x = line.split(" ")
        comps = (len(x) - 3) // 2
        for i in range(comps):
            req[(int(x[-2]), x[-1])].append((int(x[i * 2]), x[i * 2 + 1]))

    available = 1000000000000

    low = available // produce("FUEL", 1, req)
    high = 2 * low

    while high - low > 1:
        middle = (high + low) // 2
        cost = produce("FUEL", middle, req)
        if cost <= available:
            low = middle
        else:
            high = middle

    return low
Example #3
0
def solve():
    reg = re.compile('(\d*)-(\d*) (\w): (\w*)')
    return sum([
        (occurances := password.count(char)) >= int(low)
        and occurances <= int(high)
        for low, high, char, password in reg.findall(' '.join(read_file("02")))
    ])
Example #4
0
def solve():
    input = read_file("06")

    orbits = generate_orbit_dict(input)
    all_planets = get_all_planets(input)

    return sum(get_pos(orbits, k) for k in all_planets)
Example #5
0
def solve():
    input = read_file("17")[0].split(",")
    prog = create_program(input)
    game = Game(prog)

    field = defaultdict(str)
    x, y = 0, 0

    while not game.halt:
        run_game(game)
        if game.output == 10:
            y += 1
            x = 0
        else:
            field[(x, y)] = chr(game.output)
            x += 1
        print(chr(game.output), end="")

    len_x, len_y = get_size(field)
    result = 0

    for y in range(1, len_y):
        for x in range(1, len_x):
            if field[(x-1, y)] == "#" and \
               field[(x, y-1)] == "#" and \
               field[(x+1, y)] == "#" and \
               field[(x, y+1)] == "#":
                result += x * y

    return result
def solve():
    winner, decks = play(build_decks(read_file("22")))
    return sum([
        decks[winner].pop() * multiplier
        for multiplier in range(1,
                                len(decks[winner]) + 1)
    ])
def solve():
    input = read_file("02")[0].split(",")
    input_store = [int(x) for x in input]

    for noun in range(100):
        for verb in range(100):
            input = input_store[:]
            pos = 0
            input[1] = noun
            input[2] = verb

            while input[pos] != 99:
                if input[pos] == 1:
                    input[input[pos +
                                3]] = input[input[pos + 1]] + input[input[pos +
                                                                          2]]

                if input[pos] == 2:
                    input[input[pos +
                                3]] = input[input[pos + 1]] * input[input[pos +
                                                                          2]]

                pos += 4

            if input[0] == 19690720:
                return 100 * noun + verb
Example #8
0
def solve():
    raw_input = read_file("12")
    x, y, wp_x, wp_y = 0, 0, 10, -1

    directions = {"N": (0, -1), "E": (1, 0), "S": (0, 1), "W": (-1, 0)}
    rot_r, rot_l = [("R", 90), ("L", 270)], [("L", 90), ("R", 270)]
    
    for instruction in raw_input:
        op, value = instruction[0], int("".join(instruction[1:]))
        
        if   op == "F":
            x, y = x + value * wp_x, y + value * wp_y
            
        elif op in ["R", "L"]:
            if value == 180:
                wp_x, wp_y = -wp_x, -wp_y
                
            elif (op, value) in rot_r:
                wp_x, wp_y = -wp_y, wp_x
            
            elif (op, value) in rot_l:
                wp_x, wp_y = wp_y, -wp_x
        
        else:
            wp_x, wp_y = wp_x + directions[op][0] * value, wp_y + directions[op][1] * value
       
    return abs(x) + abs(y)
def solve():
    input = read_file("17")[0].split(",")
    input[0] = 2
    prog = create_program(input)
    game = Game(prog)

    print_camera(game)

    # Solution derived on paper.
    # Automated solution will follow, when I find the time.

    instructions = []
    instructions.append([ord(c) for c in "A,B,A,C,A,B,C,B,C,A\n"])
    instructions.append([ord(c) for c in "L,12,R,4,R,4,L,6\n"])
    instructions.append([ord(c) for c in "L,12,R,4,R,4,R,12\n"])
    instructions.append([ord(c) for c in "L,10,L,6,R,4\n"])
    instructions.append([ord(c) for c in "n\n"])

    print_message(game)

    for inst in instructions:
        run_game(game, inst)
        print_message(game)

    print_camera(game)
    run_game(game)

    return read_output(game)
Example #10
0
def solve():
    input = read_file("15")[0].split(",")
    prog = create_program(input)
    game = Game(prog)
    field = get_map(game)

    return fill_with_oxygen(field)
Example #11
0
def main():
    f = aoc.read_file('01')
    a = [int(l) for l in f]
    res = [part1(a, 2020), part2(a, 2020)]

    print(f"Part 1 = {res[0]}\nPart 2 = {res[1]}")
    print("%s ms" % round((time.time() - start_time) * 1000))
Example #12
0
def get_fields_and_tickets():
    mode, fields, field_structure, your_ticket, nearby_tickets = 0, set(
    ), {}, [], []

    for line in read_file("16"):
        if not len(line) or "ticket" in line:
            mode += 1
            continue

        if mode == 0:
            field = findall(r'(.+): (\d+)-(\d+) or (\d+)-(\d+)', line)[0]
            field_structure[field[0]] = [int(num) for num in field[1:]]
            fields = fields | \
                     set(value for value in range(field_structure[field[0]][0], field_structure[field[0]][1] + 1)) | \
                     set(value for value in range(field_structure[field[0]][2], field_structure[field[0]][3] + 1))

        if mode == 2:
            your_ticket = [int(value) for value in line.split(",")]

        if mode == 4:
            values = [int(num) for num in line.split(",")]
            if not sum(value not in fields for value in values):
                nearby_tickets.append(values)

    return field_structure, nearby_tickets, your_ticket
Example #13
0
def solve():
    raw_input = read_file("12")
    x, y, dir = 0, 0, 1

    for instruction in raw_input:
        op, value = instruction[0], int("".join(instruction[1:]))

        if op == "N" or (op == "F" and dir == 0):
            y -= value

        elif op == "E" or (op == "F" and dir == 1):
            x += value

        elif op == "S" or (op == "F" and dir == 2):
            y += value

        elif op == "W" or (op == "F" and dir == 3):
            x -= value

        elif op == "R":
            dir = (dir + value // 90) % 4

        elif op == "L":
            dir = (dir - value // 90) % 4

    return abs(x) + abs(y)
def solve():
    field = read_file("24")
    known = set()
    
    while (bio := bio_diversity(field)) not in known:
        known.add(bio)
        field = evolve(field)
Example #15
0
def solve():
    input     = read_file("07")
    built     = []
    workers   = []
    steps     = defaultdict(list)
    all_steps = set()
    timer     = 0

    for line in input:
        first = line.split(" ")[1]
        after = line.split(" ")[7]
        steps[after].append(first)
        all_steps.update(first, after)

    all_steps = sorted(list(all_steps))
    amount_of_steps = len(all_steps)
    
    while len(built) < amount_of_steps:
        if len(workers) < 5:
            for after in all_steps:
                if all(first_steps in built for first_steps in steps[after]):
                    workers.append({"step": after, "duration": ord(after) - 4})
                    all_steps.remove(after)

        worker_id = 0
        while worker_id < len(workers):
            if workers[worker_id]["duration"] > 1:
                workers[worker_id]["duration"] -= 1
                worker_id += 1
            else:
                built.append(workers[worker_id]["step"])
                del workers[worker_id]

        timer += 1
    return timer
def solve():
    input = read_file("08")
    mod_pos = -1
    seen = set()

    while True:
        code = [line.split() for line in input]
        
        mod_pos += 1
        
        if code[mod_pos][0] == "jmp":
            code[mod_pos][0] = "nop"
        elif code[mod_pos][0] == "nop":
            code[mod_pos][0] = "jmp"
        else:
            continue

        accu, pos = 0, 0

        while pos not in seen:
            seen.add(pos)
            if code[pos][0] == "acc":
                accu += int(code[pos][1])
            elif code[pos][0] == "jmp":
                pos += int(code[pos][1]) - 1
            pos += 1

            if pos == len(code):
                return accu

        seen.clear()
Example #17
0
def solve():
    reg = re.compile('(\d*)-(\d*) (\w): (\w*)')
    return sum([
        (password[int(pos_1) - 1] == char) ^ (password[int(pos_2) - 1] == char)
        for pos_1, pos_2, char, password in reg.findall(' '.join(
            read_file("02")))
    ])
def solve():
    input = read_file("04")
    start, end = [int(num) for num in input[0].split("-")]

    return sum(
        increases(num) and not all_digits_unique(num)
        for num in range(start, end + 1))
def solve():
    prog = read_file("05")[0].split(",")
    prog = [int(x) for x in prog]

    ip   = 0
    input = 1

    while prog[ip] != 99:
        op, modes = split_instruction(prog[ip])
        values = get_values(prog, ip, op, modes)
        
        if op == "01": # Addition
            prog[prog[ip+3]] = values[0] + values[1]
            ip += 4
    
        if op == "02": # Multiplication
            prog[prog[ip+3]] = values[0] * values[1]
            ip += 4
        
        if op == "03": # Read and Store prog
            prog[prog[ip+1]] = input
            ip += 2

        if op == "04": # Print Output
            print(values[0])
            ip += 2
Example #20
0
def solve():
    adapters = sorted([int(line) for line in read_file("10")])
    adapters = [0] + adapters + [adapters[-1] + 3]

    diffs = [adapters[index + 1] - adapters[index] for index in range(len(adapters) - 1)]
    
    return diffs.count(1) * diffs.count(3)
Example #21
0
def main ():
    f = aoc.read_file('09')
    preambleSize = 25
    numbers = getNumbers(f)

    res = [part1(numbers, preambleSize), part2(numbers, preambleSize)]
    print(f"Part 1 = {res[0]}\nPart 2 = {res[1]}")
    print("%s ms" % round((time.time() - start_time) * 1000))
def solve():
    input = read_file("09")[0].split(",")
    prog = create_program(input)

    booster = Booster(prog)
    booster = run_booster(1, booster)

    return (booster.output)
def solve():
    input        = read_file("18")
    dungeon      = Dungeon(input)
    keys         = create_keys(dungeon)
    keys_taken   = set(("@"))
    doors_opened = set()

    return fetch_keys(keys, keys_taken, doors_opened)
def solve():
    raw_input = read_file("24")
    flips_per_tile = defaultdict(int)
    
    for instruction in raw_input:
        flips_per_tile[normalize(instruction)] += 1
        
    return sum([flips % 2 for flips in flips_per_tile.values()])
def solve():
    input        = read_file("18")
    dungeon      = Dungeon(input)
    keys         = create_keys(dungeon)
    keys_taken   = set(str(bot_id) for bot_id in range(4))
    doors_opened = set()

    return fetch_keys(dungeon.key_pos, dungeon.bot_pos, keys, keys_taken, doors_opened)
Example #26
0
def solve():
    input   = read_file("08")
    input   = [int(x) for x in input[0]]

    size    = 25 * 6
    layers  = extract_layers(input, size)
    
    print_image(layers)
Example #27
0
def solve():
    boxes = read_file("02")
    doub, trip = 0, 0

    for box in boxes:
        doub, trip = update(box, doub, trip)

    return doub * trip
Example #28
0
def solve():
    raw_input = read_file("13")
    start = int(raw_input[0])
    ids = [int(id) for id in findall(r'\d+', raw_input[1])]

    wait_time = 0

    while 0 not in (diff := [(start + wait_time) % id for id in ids]):
        wait_time += 1
Example #29
0
def solve():
    seats = sorted(read_file("05"), key = lambda s: s[7:])
    seats = sorted(seats, key = lambda s: s[:7], reverse = True)

    for i in range(len(seats)):
        current_id = calc_seat_id(seats[i])
        if i and prev_id + 2 == current_id:
            return prev_id + 1
        prev_id = current_id
def solve():
    input = read_file("04") + [""]

    reg = re.compile('(\w*):([\w#]*)')
    all_fields = set()
    result = 0

    for line in input:
        if len(fields_of_line := reg.findall(line)):