예제 #1
0
    def run_part1(self, data: InputData) -> str:
        self.parse_input_data(data.input)

        invalidValues = self.get_invalid_ticket_values(self.otherTicketValuesList)
        result = sum(invalidValues)

        return helper.validate_result('What is your ticket scanning error rate?', result, data.expectedAnswer)
예제 #2
0
 def run_part2(self, data: InputData) -> str:
     chainsUnder: Dict[int, int] = {}
     adapters = sorted(data.input)
     
     result = self.count_adapterChains(0, adapters, chainsUnder)
     
     return helper.validate_result('What is the total number of distinct ways you can arrange the adapters to connect the charging outlet to your device?', result, data.expectedAnswer)
예제 #3
0
    def run_part(self, data: InputData) -> str:
        history: Dict[str, int] = {}
        turn = 0
        ls = LastSaid()
        initialSeq = data.input[0].split(",")
        for x in initialSeq:
            turn += 1
            history[x] = turn
            ls.value = x
            ls.onTurn = turn

        while turn < data.lastTurn:
            turn += 1

            if ls.prevTurn == 0:
                ls.value = "0"
                ls.onTurn = turn
            else:
                diff = ls.onTurn - ls.prevTurn
                ls.value = str(diff)
                ls.onTurn = turn

            if ls.value in history:
                ls.prevTurn = history[ls.value]
            else:
                ls.prevTurn = 0

            history[ls.value] = turn

        result = int(ls.value)
        return helper.validate_result(
            f'what will be the {data.lastTurn}th number spoken?', result,
            data.expectedAnswer)
예제 #4
0
 def run_part1(self, data: InputData) -> str:
     result = 0
     for bPass in data.input:
         seatId = self.get_seat_id(bPass)
         if seatId > result:
             result = seatId
     return helper.validate_result('What is the highest seat ID on a boarding pass?', result, data.expectedAnswer)
예제 #5
0
    def run_part2(self, data: InputData) -> str:
        self.go(data.player1Deck, data.player2Deck)
        winner = data.player1Deck or data.player2Deck
        result = sum((len(winner) - i) * x for i, x in enumerate(winner))

        return helper.validate_result("What is the winning player's score?",
                                      result, data.expectedAnswer)
예제 #6
0
 def run_part2(self, data: InputData) -> str:
     history: List[str] = []
     winner, winnerDeck = self.play_recursive_combat(
         data.player1Deck, data.player2Deck, history)
     result = self.calculate_score(winnerDeck, 1)
     return helper.validate_result("What is the winning player's score?",
                                   result, data.expectedAnswer)
예제 #7
0
    def run_part2(self, data: InputData) -> str:
        allergen_ingredients, ingredient_counter = self.process_food_lines(
            data.input)

        finished = False
        finalIngredients = set()
        while not finished:
            finished = True
            for allergen, ingredients in allergen_ingredients.items():
                if len(ingredients) != 1:
                    finished = False
                    continue

                ingredient = next(iter(ingredients))
                if ingredient not in finalIngredients:
                    finalIngredients.add(ingredient)

                    for a, i in allergen_ingredients.items():
                        if a != allergen:
                            i.discard(ingredient)

        result = [(k, *v) for k, v in allergen_ingredients.items()]
        result.sort(key=lambda x: x[0])
        result = ",".join(x[1] for x in result)

        return helper.validate_result(
            'What is your canonical dangerous ingredient list?', result,
            data.expectedAnswer)
예제 #8
0
    def run_part1(self, data: InputData) -> str:
        result = 0
        for line in data.input:
            total = self.evaluate(line)
            result += total
            helper.dprint(f"{total:-6} = {line}")

        return helper.validate_result('What is the sum of the resulting values?', result, data.expectedAnswer)
예제 #9
0
    def run_part2(self, data: InputData) -> str:
        result = 0
        for line in data.input:
            total = self.evaluate2(line)
            result += total
            helper.dprint(f"{total:-6} = {line}")

        return helper.validate_result('What do you get if you add up the results of evaluating the homework problems using these new rules?', result, data.expectedAnswer)
예제 #10
0
 def run_part1(self, data: InputData) -> str:
     tileList = self.create_all_tiles(data.input)
     cornerTiles = self.get_open_side_tiles(tileList, 2)
     result = 1
     for corner in cornerTiles:
         result *= corner.id
         helper.dprint(f"tile id: {corner.id}")
     return helper.validate_result('What do you get if you multiply together the IDs of the four corner tiles?', result, data.expectedAnswer)
예제 #11
0
 def run_part1(self, data: InputData) -> str:
     earliestTime = int(data.input[0])
     buses = data.input[1].split(",")
     bus = self.get_soonest_bus(earliestTime, buses)
     result = (bus.departureTime - earliestTime) * bus.busId
     return helper.validate_result(
         "What is the ID of the earliest bus you can take to the airport multiplied by the number of minutes you'll need to wait for that bus?",
         result, data.expectedAnswer)
예제 #12
0
    def run_part1(self, data: InputData) -> str:
        adapters = sorted(data.input)
        adapters.append(max(adapters) + 3)

        diffCounts = self.get_jolt_differences(adapters)
        result = diffCounts[1] * diffCounts[3]

        return helper.validate_result('What is the number of 1-jolt differences multiplied by the number of 3-jolt differences?', result, data.expectedAnswer)
예제 #13
0
 def run_part1(self, data: InputData) -> str:
     rules = self.parse_rules(data.input)
     foundBags: List[str] = []
     self.count_bags_containing(rules, "shiny gold", foundBags)
     result = len(foundBags)
     return helper.validate_result(
         'How many bag colors can eventually contain at least one shiny gold bag?',
         result, data.expectedAnswer)
예제 #14
0
    def run_part1(self, data: InputData) -> str:
        cupLinks = self.int_list_to_dict_links(data.input)

        game = CrabCups(cupLinks, data.input[0], data.numMoves)
        while game.perform_move():
            pass
        result = game.get_cups_after_1()
        return helper.validate_result(
            'What are the labels on the cups after cup 1?', result,
            data.expectedAnswer)
예제 #15
0
    def run_part1(self, data: InputData) -> str:
        end = data.input.index("")
        rules = self.build_rule_dict(data.input[:end])
        rules = self.convert_to_regex_rules(rules)

        images = data.input[end+1:]

        regex = self.convert_to_regex(rules[0])
        result = self.count_valid_images(images, regex)

        return helper.validate_result('How many messages completely match rule 0?', result, data.expectedAnswer)
예제 #16
0
    def run_part(self, data: InputData) -> str:
        cc = ConwayCube(data.input, data.numDimensions)

        cycle = 1
        while cycle <= 6:
            cc.apply_rules()
            cycle += 1

        result = cc.get_num_active_cubes()
        return helper.validate_result(
            'How many cubes are left in the active state after the sixth cycle?',
            result, data.expectedAnswer)
예제 #17
0
    def run_part2(self, data: InputData) -> str:
        tmp = range(max(data.input) + 1, 1000001, 1)
        data.input.extend(tmp)
        cupLinks = self.int_list_to_dict_links(data.input)

        game = CrabCups(cupLinks, data.input[0], data.numMoves)
        while game.perform_move():
            pass
        values = game.get_cups_after_1b()
        result = values[0] * values[1]
        return helper.validate_result(
            'What do you get if you multiply their labels together?', result,
            data.expectedAnswer)
예제 #18
0
    def run_part(self, data: InputData, rules: Dict) -> str:
        seats = self.input_list_to_table(data.input)

        numChanges = -1
        numPasses = 0

        while (numChanges != 0):
            numPasses += 1
            numChanges = self.apply_rules_to_seats(seats, rules)

        result = self.count_occupied_seats(seats)
        return helper.validate_result('How many seats end up occupied?',
                                      result, data.expectedAnswer)
예제 #19
0
    def run_part1(self, data: InputData) -> str:
        allergen_ingredients, ingredient_counter = self.process_food_lines(
            data.input)

        without_allergens = self.get_ingredients_without_allergens(
            allergen_ingredients, ingredient_counter)
        result = sum(ingredient_counter[ingredient]
                     for ingredient in without_allergens)
        result = str(result)

        return helper.validate_result(
            'How many times do any of those ingredients appear?', result,
            data.expectedAnswer)
예제 #20
0
    def run_part2(self, data: InputData) -> str:
        tileFloor = self.build_tile_floor(data.input)
        day = 0
        result = self.count_black_tiles([x for x in tileFloor.values()])
        helper.dprint(f"Initial: {result} black tiles")
        while day < 100:
            day += 1
            self.update_floor_tiles(tileFloor)
            result = self.count_black_tiles([x for x in tileFloor.values()])
            helper.dprint(f"Day {day}: {result}")

        return helper.validate_result(
            "How many tiles will be black after 100 days?", result,
            data.expectedAnswer)
예제 #21
0
    def run_part1(self, data: InputData) -> str:
        currentPos = Position(0, 0, "E")
        path: List[Position] = []
        path.append(currentPos)

        for line in data.input:
            code = line[0]
            num = int(line[1:])
            currentPos = self.move_ship(currentPos, code, num, path)

        result = self.calc_manhattan_distance(currentPos.x, currentPos.y)
        return helper.validate_result(
            'What is the Manhattan distance between that location and the ship'
            's starting position?', result, data.expectedAnswer)
예제 #22
0
    def run_part(self, data: InputData, process: Callable[[List[str]], int]) -> str:
        result = 0
        groupStart = 0
        groupEnd = 0
        while groupStart < len(data.input):
            try:
                groupEnd = data.input.index("", groupStart)
            except:
                groupEnd = len(data.input)

            lines = data.input[groupStart:groupEnd]
            result += process(lines)

            groupStart = groupEnd + 1

        return helper.validate_result('What is the sum of those counts?', result, data.expectedAnswer)
예제 #23
0
    def run_part1(self, data: InputData) -> str:
        while data.player1Deck and data.player2Deck:
            card1 = data.player1Deck.popleft()
            card2 = data.player2Deck.popleft()
            if card1 < card2:
                data.player2Deck.append(card2)
                data.player2Deck.append(card1)
            else:
                data.player1Deck.append(card1)
                data.player1Deck.append(card2)
        winner = data.player1Deck or data.player2Deck

        result = sum((len(winner) - i) * x for i, x in enumerate(winner))

        return helper.validate_result("What is the winning player's score?",
                                      result, data.expectedAnswer)
예제 #24
0
    def run_part2(self, data: InputData) -> str:
        seats = []
        for x in range(1024):
            seats.append(x)
        
        for bPass in data.input:
            seatId = self.get_seat_id(bPass)
            seats[seatId] = 0

        result = -1

        for x in seats[1:-1]:
            if x != 0 and seats[x - 1] == 0 and seats[x + 1] == 0:
                result = x
                break

        return helper.validate_result('What is the ID of your seat?', result, data.expectedAnswer)
예제 #25
0
 def run_part2(self, data: InputData) -> str:
     buses = data.input[1].split(",")
     increment = 0
     lcmValue = 1
     time = 0
     i = 0
     while i < len(buses):
         if buses[i] != "x":
             busId = int(buses[i])
             if increment == 0:
                 increment = 1
             time = self.get_next_matching_time(time, busId, increment, i)
             lcmValue = helper.get_lcm(lcmValue, busId)
             increment = lcmValue
         i += 1
     return helper.validate_result(
         "What is the earliest timestamp such that all of the listed bus IDs depart at offsets matching their positions in the list?",
         time, data.expectedAnswer)
예제 #26
0
    def run_part2(self, data: InputData) -> str:
        comp = AccumulatorProcessor(data.input)
        comp.run()

        firstCallStack = comp.callStack.copy()
        while len(firstCallStack) > 0:
            lastIdx = firstCallStack.pop()
            if data.input[lastIdx].startswith("acc"):
                continue

            newInput = self.flip_instruction(lastIdx, data.input.copy())

            comp = AccumulatorProcessor(newInput)
            reachedEnd = comp.run()
            if reachedEnd:
                break

        return helper.validate_result('The value in the accumulator is:', comp.accValue, data.expectedAnswer)
예제 #27
0
    def run_part2(self, data: InputData) -> str:
        self.memory.clear()

        actions = {
            "mas" : self.set_mask,
            "mem" : self.set_memory_v2
        }

        for line in data.input:
            key = line[:3]
            actions[key](line)

        result = 0
        for key in self.memory:
            result += self.memory[key]
            pass

        return helper.validate_result('What is the sum of all values left in memory after it completes?', result, data.expectedAnswer)
예제 #28
0
    def run_part1(self, data: InputData) -> str:
        cardPublicKey = data.input[0]
        doorPublicKey = data.input[1]

        cardLoopSize = self.find_loop_size(cardPublicKey)
        doorLoopSize = self.find_loop_size(doorPublicKey)
        helper.dprint(f"card key: {cardPublicKey}   loop size: {cardLoopSize}")
        helper.dprint(f"door key: {doorPublicKey}   loop size: {doorLoopSize}")

        result1 = self.calculate_encryption_key(cardPublicKey, doorLoopSize)
        result2 = self.calculate_encryption_key(doorPublicKey, cardLoopSize)

        if result1 == result2:
            helper.dprint("    KEY MATCH")
        helper.dprint(f"key: {result1} - {result2}")

        return helper.validate_result(
            'What encryption key is the handshake trying to establish?',
            result1, data.expectedAnswer)
예제 #29
0
    def run_part2(self, data: InputData) -> str:
        self.parse_input_data(data.input)

        self.discard_invalid_tickets()
        self.init_field_order_list()
        self.identify_fields()

        indexes: List[int] = []
        for i in self.fieldOrderDict:
            field = self.fieldOrderDict[i][0]
            if field.startswith("departure"):
                indexes.append(i)

        result = 1
        myTicketIntValues = self.get_ticket_values(self.myTicketValues)
        for i in indexes:
            result *= myTicketIntValues[i]

        return helper.validate_result('What do you get if you multiply those six values together?', result, data.expectedAnswer)
예제 #30
0
    def run_part2(self, data: InputData) -> str:
        end = data.input.index("")
        rules = self.build_rule_dict(data.input[:end])

        rules[8] = [[42], [42, 8]]
        rules[11] = [[42, 31], [42, 11, 31]]

        rules = self.convert_to_regex_rules(rules)

        rx42 = rules[8][0][0]
        rx31 = rules[11][0][1]
        rx8 = f"{rx42}+"
        parts = []
        for n in range(1, 6):
            val = f"{rx42}{{{n}}}{rx31}{{{n}}}"
            parts.append(val)
        rx11 = "(" + "|".join(parts) + ")"
        regex = rx8 + rx11

        images = data.input[end+1:]

        result = self.count_valid_images(images, regex)
        
        return helper.validate_result('After updating rules 8 and 11, how many messages completely match rule 0?', result, data.expectedAnswer)