Beispiel #1
0
def get_buses():
    raw_table = ut.read_input().split(',')
    bus_table = []
    for index, bus in enumerate(raw_table):
        if not bus == 'x':
            bus_table.append((bus, index))
    return bus_table
Beispiel #2
0
def get_instructions():
    instructions = [line.split(' = ') for line in ut.read_input().splitlines()]
    for index, instruction in enumerate(instructions):
        operation = instruction[0]
        if operation[0:3] == 'mem':
            address = operation.split('mem[')[1].split(']')[0]
            instructions[index] = ['mem', (int(address), int(instruction[1]))]
    return instructions
Beispiel #3
0
def get_passports():
    passport_data = [line.split() for line in ut.read_input().split("\n\n")]
    passports = []
    for passport in passport_data:
        new_passport = {}
        for data in passport:
            data = data.split(":")
            new_passport[data[0]] = data[1]
        passports.append(new_passport)
    return passports
Beispiel #4
0
def get_puzzle_pieces():
    puzzle_pieces = []
    image_pieces = [[list(line) for line in el.splitlines()]
                    for el in ut.read_input().split('\n\n')]
    for image_piece in image_pieces:
        tile_id = ''.join(image_piece[0]).split()[1][0:-1]
        tile_image = image_piece[1:]
        new_piece = Piece(tile_id, tile_image)
        puzzle_pieces.append(new_piece)
    return puzzle_pieces
Beispiel #5
0
def get_initial_active(dimensions):
    initial_active = {}
    raw_map = ut.read_input().splitlines()
    for y in range(len(raw_map)):
        for x in range(len(raw_map[0])):

            if dimensions == 3:
                initial_active[(x, y, 0)] = raw_map[y][x]
            elif dimensions == 4:
                initial_active[(x, y, 0, 0)] = raw_map[y][x]

    return initial_active
Beispiel #6
0
def get_repaired_instructions():
    instructions = [line.split() for line in ut.read_input().splitlines()]
    repaired_instructions = []

    for index, instruction in enumerate(instructions):
        operation = instruction[0]
        arg = instruction[1]
        if operation == 'nop':
            repaired_instruction = instructions.copy()
            repaired_instruction[index] = ['jmp', arg]
            repaired_instructions.append(repaired_instruction)
        elif operation == 'jmp':
            repaired_instruction = instructions.copy()
            repaired_instruction[index] = ['nop', arg]
            repaired_instructions.append(repaired_instruction)

    return repaired_instructions
Beispiel #7
0
def get_train_data():
    train_data = [seg.splitlines() for seg in ut.read_input().split('\n\n')]

    # All ticket rules
    rules = []
    for rule in train_data[0]:
        rule = rule.split(': ')
        rule_name = rule[0]
        rule_ranges = rule[1].split(' or ')
        new_rule = TrainRule(rule_name, rule_ranges)
        rules.append(new_rule)

    your_ticket = [int(el) for el in train_data[1][1].split(',')]

    nearby_tickets = []
    for ticket in train_data[2][1:]:
        nearby_tickets.append([int(el) for el in ticket.split(',')])

    return rules, your_ticket, nearby_tickets
Beispiel #8
0
def get_instructions():
    raw_instructions = ut.read_input().splitlines()
    instructions = []
    for raw_instruction in raw_instructions:
        index = 0
        instruction = []
        while index < len(raw_instruction):
            char = raw_instruction[index]
            if index == len(raw_instruction) - 1:
                instruction.append(char)
            else:
                next_char = raw_instruction[index + 1]
                if char in ["e", "w"]:
                    instruction.append(char)
                else:
                    instruction.append(char + next_char)
                    index += 1
            index += 1
        instructions.append(instruction)
    return instructions
Beispiel #9
0
def get_food_data():
    food_data = [
        line.replace('(', '').replace(')', '').replace(',', '').split()
        for line in ut.read_input().splitlines()
    ]
    food = []
    for food_item in food_data:
        ingredients = []
        allergens = []
        is_allergen = False
        for item in food_item:
            if item == 'contains':
                is_allergen = True
                continue

            if not is_allergen:
                ingredients.append(item)
            else:
                allergens.append(item)
        food.append(Food(ingredients, allergens))
    return food
Beispiel #10
0
import ut

expressions = [line.replace(' ', '') for line in ut.read_input().splitlines()]


class ExpressionEvaluator:
    def __init__(self, expression):
        self.expr_index = 0
        self.expression = expression

    @staticmethod
    def evaluate_add_priority(expression):
        multiplication_terms = [eval(el) for el in expression.split('*')]
        evaluation = 1
        for mul_term in multiplication_terms:
            evaluation *= mul_term
        return str(evaluation)

    def evaluate_v2(self):
        evaluated_expression = ''
        while 0 <= self.expr_index < len(self.expression):
            char = self.expression[self.expr_index]
            if char == '(':
                self.expr_index += 1
                evaluated_expression += self.evaluate_v2()
            elif char == ')':
                return self.evaluate_add_priority(evaluated_expression)
            else:
                evaluated_expression += char
            self.expr_index += 1
        return self.evaluate_add_priority(evaluated_expression)
Beispiel #11
0
def part_one():
    instructions = [line.split() for line in ut.read_input().splitlines()]
    hgc = HandheldGameConsole(instructions)
    hgc.run()
    ut.print_answer(hgc.accumulator)
Beispiel #12
0
import ut


directions = [(1, -1), (1, 0), (1, 1), (0, -1), (0, 1), (-1, -1), (-1, 0), (-1, 1)]
seats = ut.read_input().splitlines()


def get_seat_map():
    seat_map = {}
    for row in range(len(seats)):
        for col in range(len(seats[0])):
            seat_map[(row, col)] = seats[row][col]
    return seat_map


def print_map(grid):
    for row in range(10):
        for col in range(10):
            print(grid[(row, col)], end='')
        print()
    print()


def get_neighbours(pos):
    return [ut.pos_add(pos, direction) for direction in directions]


def in_bounds(pos):
    return 0 <= pos[0] < len(seats) and 0 <= pos[1] < len(seats[0])

Beispiel #13
0
import ut

boarding_passes = ut.read_input().splitlines()


def get_row_col(seat, high_bound):
    low = 0
    high = high_bound

    for char in seat:
        half = ((high - low) / 2)
        if char in ["B", "R"]:
            low += half
        elif char in ["F", "L"]:
            high -= half
    return int(high) - 1


def get_seat_id(boarding_pass):
    row, col = get_seat(boarding_pass)
    seat_id = row * 8 + col
    return seat_id


def get_seat(boarding_pass):
    row = get_row_col(boarding_pass[0:7], 128)
    col = get_row_col(boarding_pass[7:], 8)
    return row, col


def part_one():
Beispiel #14
0
import ut

adapters = [int(line) for line in ut.read_input().splitlines()]
adapters.append(max(adapters) + 3)
adapters.append(0)
adapters.sort()


def part_one():
    jolt_diff = []
    jolt = 0

    for adapter in adapters:
        jolt_diff.append(adapter - jolt)
        jolt = adapter
    one_diff_count = jolt_diff.count(1)
    three_diff_count = jolt_diff.count(3)

    ut.print_answer(one_diff_count * three_diff_count)


def count_arrangements():
    paths = dict.fromkeys(adapters, 0)
    paths[0] = 1

    for index, adapter in enumerate(adapters[0:-1]):
        i = index + 1
        while i < len(adapters) and adapters[i] - adapter <= 3:
            paths[adapters[i]] += paths[adapter]
            i += 1
    return paths[adapters[-1]]
Beispiel #15
0
import ut

decks = [[int(el) for el in deck.splitlines()]
         for deck in ut.read_input().split("\n\n")]
deck1 = decks[0]
deck2 = decks[1]


class CombatGame:
    def __init__(self, deck1, deck2):
        self.deck1 = deck1
        self.deck2 = deck2

    def play_turn(self):
        card_1 = self.deck1[0]
        card_2 = self.deck2[0]

        if card_1 > card_2:
            self.deck1 = self.deck1[1:] + [card_1] + [card_2]
            self.deck2 = self.deck2[1:]
        elif card_2 > card_1:
            self.deck2 = self.deck2[1:] + [card_2] + [card_1]
            self.deck1 = self.deck1[1:]

    def calc_score(self):
        winning_deck = self.deck1 if self.deck1 else self.deck2
        winning_deck.reverse()
        return sum(
            [winning_deck[i] * (i + 1) for i in range(len(winning_deck))])

    def play(self):
Beispiel #16
0
import ut

boat_instructions = ut.read_input().splitlines()


class Boat:
    def __init__(self):
        self.start_pos = (0, 0)
        self.current_pos = (0, 0)
        self.facing = ('E', 1)
        self.directions = ['N', 'E', 'S', 'W']
        self.delta_directions = {
            'N': (0, 1),
            'E': (1, 0),
            'S': (0, -1),
            'W': (-1, 0)
        }
        self.navigation = {
            'N': self.N,
            'E': self.E,
            'S': self.S,
            'W': self.W,
            'R': self.R,
            'L': self.L,
            'F': self.F
        }

    def N(self, units):
        delta_pos = ut.pos_mul(self.delta_directions['N'], units)
        self.current_pos = ut.pos_add(self.current_pos, delta_pos)
Beispiel #17
0
import ut

input_data = ut.read_input().split('\n\n')
messages = input_data[1].splitlines()


def gen_rules():
    raw_rules = input_data[0].splitlines()
    all_rules = {}
    for rule in raw_rules:
        rule = rule.split(': ')
        rule_no = rule[0]
        rule_branches = []
        for rule_branch in rule[1].split(' | '):
            rule_branches.append(rule_branch.split())
        all_rules[rule_no] = rule_branches
    return all_rules


rules = gen_rules()


def get_valid_messages(rule_no):
    valid_messages = []

    for branch in rules[rule_no]:
        valid_messages_branch = []
        for el in branch:

            if str.isnumeric(el):
                branch_messages = get_valid_messages(el)
Beispiel #18
0
import ut

forest = ut.read_input().splitlines()


def is_tree(pos):
    col = pos[0] % len(forest[0])
    row = pos[1]
    return forest[row][col] == '#'


def ride(slope):
    pos = (0, 0)
    trees = 0

    while pos[1] < len(forest) - 1:
        pos = ut.pos_add(pos, slope)
        if is_tree(pos):
            trees += 1

    return trees


def part_one():
    slope = (3, 1)
    trees = ride(slope)
    ut.print_answer(trees)


def part_two():
    slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
Beispiel #19
0
import ut

group_answers = ut.read_input().split("\n\n")


def count_answers(group):
    group = "".join(group.split("\n"))
    return len(dict.fromkeys(list(group)).keys())


def count_answers_v2(group):
    group_size = len(group.split("\n"))
    answers = {}
    for char in "".join(group.split("\n")):
        val = answers.get(char, 0)
        answers[char] = 1 + val

    count = 0
    for val in answers.values():
        if val == group_size:
            count += 1
    return count


def part_one():
    answer = sum([count_answers(group) for group in group_answers])
    ut.print_answer(answer)


def part_two():
    answer = sum([count_answers_v2(group) for group in group_answers])