Exemplo n.º 1
0
def solve():
    """Advent Of Code 2017 - Day 02 Solution.

    :return: tuple(part_a_result[int], part_b_result[int])
    """

    part_a_result = 0
    part_b_result = 0

    INPUT_DELIMITER = "	"

    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "day_02_input.txt"):
        numbers_on_line = [
            int(number)
            for number in puzzle_input.rstrip().split(INPUT_DELIMITER)
        ]

        # Part-A
        part_a_result += max(numbers_on_line) - min(numbers_on_line)

        # Part-B
        part_b_result += sum(
            div_wo_rem[0] // div_wo_rem[1]
            for div_wo_rem in itertools.permutations(numbers_on_line, 2)
            if div_wo_rem[0] % div_wo_rem[1] == 0)

    return part_a_result, part_b_result
Exemplo n.º 2
0
def solve():
    """Advent Of Code 2017 - Day 01 Solution.

    :return: tuple(part_a_result[int], part_b_result[int])
    """
    def circular_buffer_position(length, offset, order):
        return (offset + order) % length

    # Read first line from the input file
    try:
        puzzle_input = read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "day_01_input.txt")[0]
    except IndexError:
        return -1, -1

    # Part-A
    part_a_result = sum(
        int(puzzle_input[i]) for i in range(len(puzzle_input))
        if puzzle_input[i] == puzzle_input[circular_buffer_position(
            len(puzzle_input), i, 1)])

    # Part-B
    part_b_result = sum(
        int(puzzle_input[i]) for i in range(len(puzzle_input))
        if puzzle_input[i] == puzzle_input[circular_buffer_position(
            len(puzzle_input), i,
            len(puzzle_input) // 2)])

    return part_a_result, part_b_result
Exemplo n.º 3
0
def solvePuzzle(carriers, visited_places):

    from puzzle_commons.puzzle_commons import read_puzzle_input
    import os


    for carrier in carriers:
        visitPoint(visited_places, carrier.current_position)

    for puzzle_input in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)),"puzzle_03_input.txt"):

        i = 0

        for direction in puzzle_input:

            current_carrier = carriers[i%len(carriers)]
            i += 1

            if direction == "<":
                current_carrier.moveW()
            elif direction == ">":
                current_carrier.moveE()
            elif direction == "^":
                current_carrier.moveN()
            else:
                current_carrier.moveS()

            visitPoint(visited_places, current_carrier.current_position)
Exemplo n.º 4
0
def solve():
    """Advent Of Code 2017 - Day 09 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """

    puzzle_input = read_puzzle_input(
        os.path.dirname(os.path.abspath(__file__)), "day_09_input.txt")[0]

    def solve_a():
        """Advent Of Code 2017 - Day 09 - Part A Solution.
        """
        total_score = 0
        score_multipler = 0
        inside_junk = False

        i = 0
        while i < len(puzzle_input):
            if not inside_junk:
                if puzzle_input[i] == "{":
                    score_multipler += 1

                elif puzzle_input[i] == "}":
                    total_score += score_multipler
                    score_multipler -= 1

                elif puzzle_input[i] == "<":
                    inside_junk = True

            elif inside_junk:
                if puzzle_input[i] == ">":
                    inside_junk = False

                elif puzzle_input[i] == "!":
                    i += 1
            i += 1
        return total_score

    def solve_b():
        """Advent Of Code 2017 - Day 10 - Part B Solution.
        """
        garbage_count = 0
        inside_junk = False

        i = 0
        while i < len(puzzle_input):
            if not inside_junk and puzzle_input[i] == "<":
                inside_junk = True
            elif inside_junk:
                if puzzle_input[i] == ">":
                    inside_junk = False

                elif puzzle_input[i] == "!":
                    i += 1

                else:
                    garbage_count += 1
            i += 1
        return garbage_count

    return solve_a(), solve_b()
Exemplo n.º 5
0
def solve():
    target_aunt_properties = """children: 3,
                                cats: 7,
                                samoyeds: 2,
                                pomeranians: 3,
                                akitas: 0,
                                vizslas: 0,
                                goldfish: 5,
                                trees: 3,
                                cars: 2,
                                perfumes: 1"""
    target_aunt_properties = unpack_properties(target_aunt_properties)

    puzzle_a_solution = None
    puzzle_b_solution = None

    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_16_input.txt"):
        incorrect_aunt = False

        aunt_name, properties = puzzle_input.split(":", maxsplit=1)
        properties = unpack_properties(properties)

        # Check if solution for Puzzle_A, if it has not been found already
        if puzzle_a_solution is None:
            if compare_aunts_puzzle_a(properties, target_aunt_properties):
                puzzle_a_solution = aunt_name

        # Check if solution for Puzzle_B, if it has not been found already
        if puzzle_b_solution is None:
            if compare_aunts_puzzle_b(properties, target_aunt_properties):
                puzzle_b_solution = aunt_name

    print("Puzzle16, part A:{}".format(puzzle_a_solution))
    print("Puzzle16, part B:{}".format(puzzle_b_solution))
Exemplo n.º 6
0
def solve():
    from puzzle_commons.puzzle_commons import read_puzzle_input
    import os

    import re

    puzzle_part_A = LightGrid(999,999)
    puzzle_part_B = DimmableLightGrid(999,999)

    grids_to_operate = (puzzle_part_A, puzzle_part_B)


    for puzzle_input in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "puzzle_06_input.txt"):

        lightInstructionMatcher = re.search(r"(toggle|(?<=turn.)on|off)\D+(\d+,\d+)\D+(\d+,\d+)", puzzle_input)

        if lightInstructionMatcher is not None:
            instruction = lightInstructionMatcher.group(1)
            (startX, startY) = [int(s) for s in lightInstructionMatcher.group(2).split(",")]
            (endX, endY) = [int(s) for s in lightInstructionMatcher.group(3).split(",")]


            for grid_to_operate in grids_to_operate:
                if instruction == "on":
                    grid_to_operate.turnRangeOn(startX, startY, endX, endY)
                elif instruction == "off":
                    grid_to_operate.turnRangeOff(startX, startY, endX, endY)
                elif instruction == "toggle":
                    grid_to_operate.toggleRange(startX, startY, endX, endY)

    print("Puzzle06, part A:{}".format(puzzle_part_A.getTotalBrightness()))
    print("Puzzle06, part B:{}".format(puzzle_part_B.getTotalBrightness()))
Exemplo n.º 7
0
def solve():
    from puzzle_commons.puzzle_commons import read_puzzle_input
    import os

    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_01_input.txt"):
        print("Puzzle01, part A:", count_floors(puzzle_input))
        print("Puzzle01, part B:", find_first_underground(puzzle_input) + 1)
Exemplo n.º 8
0
def solve():
    from puzzle_commons.puzzle_commons import read_puzzle_input
    import os

    for puzzle_input in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "puzzle_04_input.txt"):

        print("Puzzle04, part A:{}".format(getAdventCoin(puzzle_input, 5)))
        print("Puzzle04, part B:{}".format(getAdventCoin(puzzle_input, 6)))
Exemplo n.º 9
0
def solve_part(is_better):
    """Solves puzzle_09, based on given evaluation function.
    Returns best path according to evaluation function."""
    puzzle_map = distancesMap()  # Distances between cities
    node_queue = []  # Queue of solutions to be processed
    best_known_solution = None  # Best known solution

    # Load instructions
    for puzzle_input in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "puzzle_09_input.txt"):

        """Find instructions in format: (START_CITY) to (END_CITY) -> (DISTANCE)"""
        map_instruction = re.search(r"(\w+)\sto\s(\w+)\s=\s(\d+)", puzzle_input)

        if map_instruction is not None:
            puzzle_map.addDistance(map_instruction.group(1), map_instruction.group(2), map_instruction.group(3))

    """
    Add initial Path to get processed.
    At this stage, no city has been visited.
    """
    node_queue.append(Path())

    # Repeat, until there are no possible solutions to explored
    while len(node_queue) > 0:
        # Pick the first in queue
        current_path = node_queue.pop(0)

        """
        Check, whether explored path can be better (shorter/longer, depending on part A/B).
        If it's already worse then best known solution, it's not worth checking or exploring further.
        Example: If searching for shortest path, it's not worth visiting next place, if currently walked distance is already
            better then any existing solution.
        """
        # if best_known_solution is None or puzzle_map.getTotalDistance(
        #         current_path.getVisitedPlaces()) > puzzle_map.getTotalDistance(
        #     best_known_solution.getVisitedPlaces()):
        if best_known_solution is None or is_better(puzzle_map.getTotalDistance(current_path.getVisitedPlaces()),
                                                    puzzle_map.getTotalDistance(
                                                        best_known_solution.getVisitedPlaces())):

            # Check whether it's solution => all places have been visited
            if set(current_path.getVisitedPlaces()) == puzzle_map.getAllPoints():

                # Store as new best solution
                best_known_solution = current_path
            else:

                # Find which places need to be visited by substracting already visited from all places
                places_left_to_visit = (point for point in puzzle_map.getAllPoints() if
                                        point not in current_path.getVisitedPlaces())

                # Generate new possible solutions
                for place_to_visit in places_left_to_visit:
                    node_queue.append(Path(current_path.getVisitedPlaces(), place_to_visit))

    return best_known_solution, puzzle_map.getTotalDistance(best_known_solution.getVisitedPlaces())
Exemplo n.º 10
0
def solve():
    # Load instructions
    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_12_input.txt"):
        # Decode puzzle input into string
        decoded_json = json.loads(puzzle_input)
        # Get value, counting also "red" objects
        print("Puzzle12, part A:{}".format(solve_puzzle12(decoded_json,
                                                          False)))
        # Get value ignoring "red" objects
        print("Puzzle12, part B:{}".format(solve_puzzle12(decoded_json, True)))
Exemplo n.º 11
0
def solve_a():
    numbers = []
    # TEST INPUT
    # for puzzle_row in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "puzzle_24_test_input.txt"):
    #     numbers.append(int(puzzle_row.strip()))

    print(sum(numbers)/3)
    # ACTUAL INPUT
    for puzzle_row in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "puzzle_24_input.txt"):
        numbers.append(int(puzzle_row.strip()))

    enquantum = None
    first_length = None
    # puzzle - A
    for i in range(len(numbers)-2):
        groups = itertools.combinations(numbers, i)

        # 1st level
        for group in groups:

            if sum(group) == sum(numbers)/3:
                if first_length is None:
                    first_length = len(group)
                elif len(group) > first_length:
                    return

                from operator import mul
                import functools

                if enquantum is None:
                    enquantum = functools.reduce(mul, group, 1)
                    print(enquantum)
                elif functools.reduce(mul, group, 1) >= enquantum:
                    return


                # print(group)
                reduced_group = numbers[:]
                for group_member in group:
                    reduced_group.remove(group_member)

                #2nd level
                for i in range(len(reduced_group) - 1):
                    groups2nd = itertools.combinations(reduced_group, i)

                    for group2nd in groups2nd:
                        if sum(group2nd) == sum(reduced_group) / 2:
                            # print(group)
                            reduced_group2nd = reduced_group[:]
                            for group_member2nd in group2nd:
                                reduced_group2nd.remove(group_member2nd)

                            # print("{}, {}, {}".format(group, group2nd, reduced_group2nd))
    print("Equantum: {}".format(enquantum))
Exemplo n.º 12
0
def solve():
    """Advent Of Code 2017 - Day 15 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """
    def generate_value_with_criteria(initial_value, factor, criteria=1):
        """Gets next value for iterator, which fits condition new_value%criteria == 0.
        """
        # Repeat, until suitable value is found
        while True:
            initial_value = (initial_value * factor) % 2147483647

            if (initial_value % criteria) == 0:
                return initial_value

    def solve_puzzle(generator_one, generator_two, iterations):
        matches_found = 0

        for i in range(iterations):
            # Compare last 16 bits of each generator
            if generator_one[0] & 0xFFFF == generator_two[0] & 0xFFFF:
                matches_found += 1

            generator_one[0] = generate_value_with_criteria(*generator_one)
            generator_two[0] = generate_value_with_criteria(*generator_two)

        return matches_found

    # Read puzzle input
    generator_initial_values = [
        int(initial_value[24:]) for initial_value in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "day_15_input.txt")
    ]
    generator_one = [generator_initial_values[0]] + [
        16807
    ]  # Value read from input + step size from requirements
    generator_two = [generator_initial_values[1]] + [
        48271
    ]  # Value read from input + step size from requirements

    def solve_a():
        """Advent Of Code 2017 - Day 15 - Part A Solution.
        """
        puzzle_a_generators = (generator_one[:], generator_two[:]
                               )  # Copy generators read from puzzle
        return solve_puzzle(*puzzle_a_generators, 40000000)

    def solve_b():
        """Advent Of Code 2017 - Day 15 - Part B Solution.
        """
        # Copy generators read from puzzle input and add conditions given by requirements
        puzzle_b_generators = (generator_one[:] + [4], generator_two[:] + [8])
        return solve_puzzle(*puzzle_b_generators, 5000000)

    return solve_a(), solve_b()
Exemplo n.º 13
0
def solve():
    """Advent Of Code 2017 - Day 17 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """
    puzzle_input = int(
        read_puzzle_input(os.path.dirname(os.path.abspath(__file__)),
                          "day_17_input.txt")[0])

    def solve_a():
        """Advent Of Code 2017 - Day 17 - Part A Solution.
        """
        buffer = [0]
        current_position = 0
        loop_times = 2017

        part_a_result = 0

        # Calculate all values in buffer
        for i in range(1, loop_times + 1):
            current_position = (
                (current_position + puzzle_input) % len(buffer)) + 1
            buffer.insert(current_position, i)

        # Get value immediate following one, which has been populated last
        for j in range(len(buffer)):
            if buffer[j] == loop_times:
                part_a_result = buffer[j + 1]
                break

        return part_a_result

    def solve_b():
        """Advent Of Code 2017 - Day 17 - Part B Solution.
        """
        current_position = 0
        buffer_length = 1
        loop_times = 50000000

        part_b_result = 0

        # Calculated values are not stored, since we are interested in one on 1st position only
        for i in range(1, loop_times + 1):
            current_position = (
                (current_position + puzzle_input) % buffer_length) + 1
            buffer_length += 1

            # Remember iteration, which caused value to be written to position 1
            if current_position == 1:
                part_b_result = i

        return part_b_result

    return solve_a(), solve_b()
Exemplo n.º 14
0
    def solve_a():
        """Advent Of Code 2017 - Day 11 - Part A Solution.
        """
        target_point = initial_point[:]

        for direction in read_puzzle_input(
                os.path.dirname(os.path.abspath(__file__)),
                "day_11_input.txt")[0].split(","):
            target_point = tuple(
                a + b for a, b in zip(target_point, directions[direction]))

        return hexagrid_distance(target_point, initial_point)
Exemplo n.º 15
0
def solve():
    """Advent Of Code 2017 - Day 13 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """
    scanners = {}

    for puzzle_input in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "day_13_input.txt"):
        # Strip whitespace, split by ": ", cast to integer
        scanner_depth, scanner_range = (int(param) for param in puzzle_input.strip().split(": "))

        scanners[scanner_depth] = scanner_range

    # Sort scanner levels
    # 1) Just in case, they came unsorted in input
    # 2) Python doesn't guarantee order of keys()
    scanner_levels = list(scanners.keys())
    scanner_levels.sort()

    def solve_a():

        severity = 0

        for scanner_level in scanner_levels:
            # Packet is falling through 0th position. If it meets with scanner, increase severity.
            if get_scanner_position(scanners[scanner_level], scanner_level) == 0:
                # add up depth * range
                severity += (scanner_level * scanners[scanner_level])

        return severity

    def solve_b():

        initial_delay = 0  # Set initial delay 0

        # Try passing the firewall, until the solution is found
        while True:
            firewall_passed = True

            for scanner in scanner_levels:
                # If the packet is blocked by firewall, increase initial delay and try again
                if get_scanner_position(scanners[scanner], scanner + initial_delay) == 0:
                    initial_delay += 1
                    firewall_passed = False
                    break

            # Break out of outer loop, when the firewall has been passed
            if firewall_passed:
                break

        return initial_delay

    return solve_a(), solve_b()
Exemplo n.º 16
0
def solve():
    """Advent Of Code 2017 - Day 06 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """
    puzzle_input = [int(puzzle_input) for puzzle_input in
                          read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "day_06_input.txt")[0].split("	")]

    class MemoryBank:
        def __init__(self, memory_bank_state):
            self.memory_bank_state = memory_bank_state[:]
            self.seen_states = []

        def redistribute_fullest_block(self):
            fullest_block_index = None

            # Find fullest memory block
            for i in range(len(self.memory_bank_state)):
                if fullest_block_index is None or self.memory_bank_state[i] > self.memory_bank_state[fullest_block_index]:
                    fullest_block_index = i

            # Clear out fullest block
            amount_to_redistribute = self.memory_bank_state[fullest_block_index]
            self.memory_bank_state[fullest_block_index] = 0

            # Redistribute amount to other blocks
            next_register_index = fullest_block_index + 1

            while amount_to_redistribute > 0:
                self.memory_bank_state[next_register_index%len(self.memory_bank_state)] += 1
                next_register_index += 1
                amount_to_redistribute -= 1

        def reallocate(self):
            total_steps = 0

            while tuple(self.memory_bank_state) not in self.seen_states:
                self.seen_states.append(tuple(self.memory_bank_state))
                self.redistribute_fullest_block()
                total_steps += 1

            return total_steps

        def distance_from_state_to_state(self):

            return len(self.seen_states) - self.seen_states.index(tuple(self.memory_bank_state))

    memory_bank_one = MemoryBank(puzzle_input)

    return memory_bank_one.reallocate(), memory_bank_one.distance_from_state_to_state()
Exemplo n.º 17
0
def solve():
    puzzle_a_result = 0
    puzzle_b_result = 0

    # Load instructions
    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_08_input.txt"):
        # Total length + length of original input - length of string without quotes
        puzzle_a_result = puzzle_a_result + len(puzzle_input) - len(
            part_a(puzzle_input))
        puzzle_b_result = puzzle_b_result + len(
            part_b(puzzle_input)) - len(puzzle_input) + 2

    print("Puzzle08, part A:{}".format(puzzle_a_result))
    print("Puzzle08, part B:{}".format(puzzle_b_result))
Exemplo n.º 18
0
def solve():
    from puzzle_commons.puzzle_commons import read_puzzle_input
    import os

    partACount = 0
    partBCount = 0

    for puzzle_input in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "puzzle_05_input.txt"):

        if isPartAValid(puzzle_input):
            partACount += 1

        if isPartBValid(puzzle_input):
            partBCount += 1

    print("Puzzle05, part A:{}".format(partACount))
    print("Puzzle05, part B:{}".format(partBCount))
Exemplo n.º 19
0
def load_puzzle_input():
    global initial_molecule

    for puzzle_row in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_19_input.txt"):
        if "=>" in puzzle_row:
            replace_from, replace_to = puzzle_row.split(" => ")
            replace_from.strip()
            replace_to = replace_to.strip()
            # print("{} to {}".format(replace_from, replace_to))

            mappings = replacements.get(replace_from, [])
            mappings = mappings + [replace_to]

            replacements[replace_from] = mappings
        else:
            initial_molecule = puzzle_row
Exemplo n.º 20
0
def solve():
    computer_instructions = []

    # TEST INPUT
    # for puzzle_row in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "puzzle_23_test_input.txt"):

    # ACTUAL INPUT
    for puzzle_row in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_23_input.txt"):
        computer_instructions.append(puzzle_row.strip())

    puzzle_a = SimpleComputer(computer_instructions)
    puzzle_a.process_instructions()
    print("Day-23 puzzle-A solution: {}".format(puzzle_a.get_registers()["b"]))

    puzzle_b = SimpleComputerPB(computer_instructions)
    puzzle_b.process_instructions()
    print("Day-23 puzzle-B solution: {}".format(puzzle_b.get_registers()["b"]))
Exemplo n.º 21
0
def solve():
    # Load instructions
    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_10_input.txt"):
        part_a_result = puzzle_input
        part_b_result = puzzle_input

        # Puzzle10 - part A
        for i in range(40):
            part_a_result = look_and_say(part_a_result)

        print("Puzzle10, part A:{}".format(len(part_a_result)))

        # Puzzle10 - part B
        # Note: runs very long
        for i in range(50):
            part_b_result = look_and_say(part_b_result)

        print("Puzzle10, part B:{}".format(len(part_b_result)))
Exemplo n.º 22
0
def solve():
    """"Prints solution for the Puzzle02"""
    from puzzle_commons.puzzle_commons import read_puzzle_input
    import os

    wrap_total = 0
    ribbon_total = 0

    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_02_input.txt"):
        dimensions = puzzle_input.split("x")
        current_present = Present(int(dimensions[0]), int(dimensions[1]),
                                  int(dimensions[2]))

        wrap_total += current_present.get_wrap()
        ribbon_total += current_present.get_ribbon()

    print("Puzzle02, part A:", wrap_total)
    print("Puzzle02, part B:", ribbon_total)
Exemplo n.º 23
0
    def solve_b():
        """Advent Of Code 2017 - Day 11 - Part B Solution.
        """
        target_point = initial_point[:]
        furthest_from_init = 0

        for direction in read_puzzle_input(
                os.path.dirname(os.path.abspath(__file__)),
                "day_11_input.txt")[0].split(","):
            target_point = tuple(
                a + b for a, b in zip(target_point, directions[direction]))

            distance_from_start = hexagrid_distance(target_point,
                                                    initial_point)
            # Remember distance, if we're further from init than before
            if distance_from_start > furthest_from_init:
                furthest_from_init = distance_from_start

        return furthest_from_init
Exemplo n.º 24
0
def solve():
    global gates
    global gates_cache

    # Load instructions
    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle_07_input.txt"):
        """Regexp explanation:
        (?:([a-z0-9]+)\s){0,1} - optional group(1) of small letters/numbers - left operand
        (?:(OR|AND|LSHIFT|RSHIFT|NOT)\s){0,1}- optional operator - group(2)
        ([a-z0-9]+) - always present group(3) of small letters/numbers - right operand
        \s->\s - assignment notation (not captured in a group)
        (\w+) - group(4) - register name"""
        instruction_matcher = re.search(
            r"(?:([a-z0-9]+)\s){0,1}(?:(OR|AND|LSHIFT|RSHIFT|NOT)\s){0,1}([a-z0-9]+)\s->\s(\w+)",
            puzzle_input)

        # Check, whether line loaded from file is valid register operation
        if instruction_matcher is not None:
            gates[instruction_matcher.group(4)] = {
                "leftOperand": instruction_matcher.group(1),
                "operator": instruction_matcher.group(2),
                "rightOperand": instruction_matcher.group(3)
            }

    # PUZZLE07 - part A
    puzzle07_part_a = resolveGate("a")
    print("Puzzle07, part A:{}".format(puzzle07_part_a))

    # PUZZLE07 - part B
    # Add new instruction - assign solution from part A to wire-B
    gates["b"] = {
        "leftOperand": None,
        "operator": None,
        "rightOperand": str(puzzle07_part_a)
    }

    # Flush gates cache
    gates_cache = {}

    puzzle07_part_b = resolveGate("a")
    print("Puzzle07, part B:{}".format(puzzle07_part_b))
Exemplo n.º 25
0
def solve():
    numbers = []
    # Load test puzzle input
    for puzzle_row in read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "puzzle_24_test_input.txt"):
        numbers.append(int(puzzle_row.strip()))

    def split_in_equal_parts(list_of_numbers, parts):

        # Find all combinations of length 1 - (list_of_numbers-parts+1)
        ## e.g: there are 5 numbers to split in 3 groups;
        ### find combinations of 'up to 3' (5-3+1) = 3
        ### each group must contain at least 1 number
        max_comb_length = len(list_of_numbers)-parts+1

        for comb_length in range(1, max_comb_length):

            all_combinations = itertools.combinations(numbers, comb_length)

            # Check each combination, whether it gives sum of sum(list_of_numbers/parts)
            for tested_combination in all_combinations:
                if sum(tested_combination) == sum(list_of_numbers)/parts:
Exemplo n.º 26
0
def solve():
    """Advent Of Code 2017 - Day 05 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """

    # Read puzzle input, cast to integer and store in list
    input_instructions = [
        int(puzzle_input) for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "day_05_input.txt")
    ]

    def steps_required_to_reach_exit(jump_instructions, offset_adjustment_fn):
        """Returns number of steps required to exit from list of offset / instructions.
        :param jump_instructions: list([integer]) list of instructions / offsets
        :param offset_adjustment_fn: function accepting single [integer] offset, returning [integer] value to be added to index in each step
        :return: [integer] number of instructions
        """
        # Create copy of instructions list in order to avoid modifying input list directly
        jump_instructions = jump_instructions[:]

        steps_to_exit_instructions = 0
        i = 0

        # Loop until instruction index is inside range of instructions
        while i < len(jump_instructions):
            # Load this instruction / offset
            offset = jump_instructions[i]

            # Modify current offset using the offset adjustment function
            jump_instructions[i] += offset_adjustment_fn(offset)

            # Adjust index by current offset
            i += offset

            steps_to_exit_instructions += 1

        return steps_to_exit_instructions

    return steps_required_to_reach_exit(input_instructions, lambda x: 1), \
           steps_required_to_reach_exit(input_instructions, lambda x: -1 if x >= 3 else 1)
Exemplo n.º 27
0
def solve():
    """Advent Of Code 2017 - Day 10 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """
    puzzle_input = read_puzzle_input(
        os.path.dirname(os.path.abspath(__file__)),
        "day_10_input.txt")[0].strip()
    puzzle_knots = [i for i in range(256)]

    part_a_input = tuple(
        int(input_number) for input_number in puzzle_input.split(","))
    part_a_hashed = knot_hash_n_times(puzzle_knots, part_a_input, 1)
    part_a_result = part_a_hashed[0] * part_a_hashed[1]

    part_b_lengths = tuple(ord(char)
                           for char in puzzle_input) + (17, 31, 73, 47, 23)
    part_b_knot_hash = knot_hash_n_times(puzzle_knots, part_b_lengths, 64)
    part_b_dense_hash = dense_hash(part_b_knot_hash, 16)
    part_b_result = ''.join(
        ['{:02x}'.format(num_to_hex) for num_to_hex in part_b_dense_hash])

    return part_a_result, part_b_result
Exemplo n.º 28
0
def solve():
    """Advent Of Code 2017 - Day 16 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """
    def dance_n_times(dance_moves, times):
        programs_init = [char for char in char_range('a', 'p')]
        seen_states = []

        dlist = DancingList(programs_init)

        for time in range(times):

            seen_hash = ''.join(dlist.get_values())

            if seen_hash in seen_states:
                return (seen_states[times % time])
            seen_states.append(seen_hash)

            for dance_move in dance_moves:
                if dance_move.startswith("s"):
                    dance_move = dance_move[1:]
                    dlist.spin(int(dance_move))

                elif dance_move.startswith("x"):
                    dance_move = dance_move[1:]
                    idx_a, idx_b = map(int, dance_move.split("/"))
                    dlist.swap_index(idx_a, idx_b)

                elif dance_move.startswith("p"):
                    dance_move = dance_move[1:]
                    member_a, member_b = dance_move.split("/")
                    dlist.swap_member(member_a, member_b)

        return ''.join(dlist.get_values())

    puzzle_input = read_puzzle_input(os.path.dirname(os.path.abspath(__file__)), "day_16_input.txt")[0].split(",")

    return dance_n_times(puzzle_input, 1), dance_n_times(puzzle_input, 1000000000)
Exemplo n.º 29
0
def solve():
    """Advent Of Code 2017 - Day 14 Solution.
    :return: tuple(part_a_result[int], part_b_result[int])
    """
    puzzle_input = read_puzzle_input(
        os.path.dirname(os.path.abspath(__file__)), "day_14_input.txt")[0]

    C_FULL = "1"  # Constant for full disk block
    C_EMPTY = "0"  # Constant for empty disk block

    def get_knot_hash(input_string):
        # Initialize 256 knots, just like on day_10 part-B
        puzzle_knots = [i for i in range(256)]

        # Calculate lengths based on input + (17, 31, 73, 47, 23), just like on day_10 part-B
        lengths = tuple(ord(char)
                        for char in input_string) + (17, 31, 73, 47, 23)

        # Get knot hash, by applying 64 transformations, just like on day_10 part-B
        knot_hash = day_10.knot_hash_n_times(puzzle_knots, lengths, 64)

        # Get dense hash of length 16, just like on day_10 part-B
        dense_hash = day_10.dense_hash(knot_hash, 16)

        # Transform dense hash into string of hexadecimal characters, just like on day_10 part-B
        hex_hash = ''.join(
            ['{:02x}'.format(num_to_hex) for num_to_hex in dense_hash])

        return hex_hash

    def convert_hex_to_bin(hash_hex):
        binary_string = ""

        for char in hash_hex:
            binary_string += "{:04b}".format(int(char, base=16))

        return binary_string

    # Store disk representation in memory
    disk = []

    for row in range(0, 128):
        current_row_hash = get_knot_hash(puzzle_input + "-" + str(row))
        current_row_bin = convert_hex_to_bin(current_row_hash)
        disk.append(list(current_row_bin))

    def solve_a():
        """Advent Of Code 2017 - Day 14 - Part A Solution.
        """
        space_used = 0  # Answer for part-A

        for row in range(len(disk)):
            for col in range(len(disk[row])):
                if disk[row][col] == C_FULL:
                    space_used += 1

        return space_used

    def solve_b():
        """Advent Of Code 2017 - Day 14 - Part B Solution.
        """
        regions = 0  # Answer for part-B

        def clean_block(row, col):
            # Empty out current block and all adjacent blocks (if current block isn't empty)
            if disk[row][col] == C_FULL:
                disk[row][col] = C_EMPTY

                # Empty out block on same Y-position, on previous row (if we're not at top edge)
                if row > 0:
                    clean_block(row - 1, col)

                # Empty out block on same Y-position, on following row (if we're not at bottom edge)
                if row < len(disk) - 1:
                    clean_block(row + 1, col)

                # Empty out block on X-1 position of the same row (if we're not at left edge)
                if col > 0:
                    clean_block(row, col - 1)

                # Empty out block on X+1 position of the same row (if we're not at right edge)
                if col < len(disk[row]) - 1:
                    clean_block(row, col + 1)

        for row in range(len(disk)):
            for col in range(len(disk[row])):
                # If the block is full, increase number of regions and nuke the whole region
                if disk[row][col] == C_FULL:
                    regions += 1
                    clean_block(row, col)

        return regions

    return solve_a(), solve_b()
Exemplo n.º 30
0
def solve():
    # Load instructions
    for puzzle_input in read_puzzle_input(
            os.path.dirname(os.path.abspath(__file__)), "puzzle11_input.txt"):
        print("Puzzle11, part A:{}".format(solve_a(puzzle_input)))
        print("Puzzle11, part B:{}".format(solve_a(solve_a(puzzle_input))))