示例#1
0
from utils import inputfile_to_array
import math
actions = inputfile_to_array("inputs/input_day_12.txt")

heading_dict = {
    "N": 0,
    "E": 90,
    "S": 180,
    "W": 270,
}


def get_key_from_dict(val, the_dict):
    for key, value in the_dict.items():
        if val == value:
            return key
    return "key doesn't exist"


def change_heading(direction, turn_angle, original_heading):
    if direction == "L":
        turn_angle = -turn_angle
    naive_new_heading = heading_dict.get(original_heading) + turn_angle
    while naive_new_heading < 0:
        naive_new_heading += 360
    normalized_heading = naive_new_heading % 360
    return get_key_from_dict(normalized_heading, heading_dict)


def rotate_waypoint(direction, turn_angle, position):
    x_pos, y_pos = position
示例#2
0
import re
from utils import inputfile_to_array, remove_empty_lines_and_concat

passport_list_with_empty_lines = inputfile_to_array("inputs/input_day_4.txt")

codes = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid', 'cid']


def passport_element_to_dict(passport_string):
    '''
    Takes in a space separated string which is one passport and
    put them in a dictionary, with key=code and value=valie
    '''
    string_list = passport_string.split(" ")
    mydict = {}
    for element in string_list:
        code_and_value_list = element.split(":")
        if code_and_value_list[0]:
            mydict[code_and_value_list[0]] = code_and_value_list[1]
    return mydict


def get_number_of_passports_with_all_relevant_codes(passport_list, codes):
    '''
    Takes in passport list as returned by "remove_empty_lines_and_concat"
    Returns number of passports with all codes there. Uses
    the "all_relevant_codes_are_present" function.
    '''
    number_of_valid = 0
    for passport_string in passport_list:
        passport_dict = passport_element_to_dict(passport_string)
示例#3
0
from utils import inputfile_to_array

passwords_and_policy_list = inputfile_to_array("inputs/input_day_2.txt")


def extract_policy_and_password_from_string(passwords_and_policy_string):
    '''
    Takes in a string of the format "<n>-<N> <a>: <x>[x..]" where
    n: is the first number in the password policy
    N: is the second number in password policy
    a: is the letter
    x: is the password (can contain different characters)

    returns a tupple in the format:
    (n,N,a,x)

    '''
    string_list = passwords_and_policy_string.split(" ")
    letter_in_policy = string_list[1][:-1]
    policy_string = string_list[0].split("-")
    first_number = int(policy_string[0])
    second_number = int(policy_string[1])
    password = string_list[-1]

    return (first_number, second_number, letter_in_policy, password)


def count_letter_in_string(my_letter, my_string):
    '''
    Returns the number of occurences "my_letter" in "my_string"
    '''
示例#4
0
from utils import inputfile_to_array

seat_map = inputfile_to_array("inputs/input_day_11.txt")


def perform_seating(seat_map, seating_algorithm):
    if seating_algorithm == 1:
        occupied_set_threshold = 4
    else:
        occupied_set_threshold = 5
    out_map = seat_map[:]

    for i in range(len(seat_map)):
        for j in range(len(seat_map[0])):
            if seating_algorithm == 1:
                relevant_seats = get_adjacent_seats(seat_map, i, j)
            else:
                relevant_seats = get_visible_seats(seat_map, i, j)
            row_as_string = out_map[i]
            if seat_map[i][j] == "L":
                if num_ocupied_relevant_seats(seat_map, relevant_seats) == 0:
                    out_map[i] = row_as_string[:j] + "#" + row_as_string[j +
                                                                         1:]
            elif seat_map[i][j] == "#":
                if num_ocupied_relevant_seats(
                        seat_map, relevant_seats) >= occupied_set_threshold:
                    out_map[i] = row_as_string[:j] + "L" + row_as_string[j +
                                                                         1:]
    return out_map

示例#5
0
import re
from utils import inputfile_to_array, remove_empty_lines_and_concat
from math import floor, ceil
from statistics import mean 

luggage_rules = inputfile_to_array("inputs/input_day_7.txt")

def bags_that_can_contain_directly(luggage_rules, bags_to_search_for):

    bags_that_can_contain_bag_to_search_for = set()
    for luggage_rule in luggage_rules:
        outer_bag = luggage_rule.split("contain")[0].strip().replace("bags","").strip()
        content   = luggage_rule.split("contain")[-1].strip()
        inner_bags_unsanitized = content.split(",")
        inner_bags = []
        for bag in inner_bags_unsanitized:
            inner_bags.append(bag.replace(".","").replace("bags","").replace("bag","").strip())
        for bag_to_search_for in bags_to_search_for:
            for inner_bag in inner_bags:
                if bag_to_search_for in inner_bag:
                    bags_that_can_contain_bag_to_search_for.add(outer_bag)
    return (bags_that_can_contain_bag_to_search_for)

def get_value_of_bag(luggage_rules, input_bag):
    '''
    Value is meant as how many bags it must contain (plus itself). Each individual bag adds 1 in value
    '''
    content_of_bag = get_content_of_bag(luggage_rules, input_bag)
    if content_of_bag:
        value = 1
        for i in content_of_bag:
示例#6
0
from utils import inputfile_to_array

number_list = [
    int(item) for item in inputfile_to_array("inputs/input_day_1.txt")
]


def task_1(number_list):
    for first_number in number_list:
        for second_number in number_list:
            sum_of_numbers = first_number + second_number
            if sum_of_numbers == 2020:
                print(first_number)
                print(second_number)
                return first_number * second_number


def task_2(number_list):
    for first_number in number_list:
        for second_number in number_list:
            for third_number in number_list:
                sum_of_numbers = first_number + second_number + third_number
                if sum_of_numbers == 2020:
                    print(first_number)
                    print(second_number)
                    print(third_number)
                    return first_number * second_number * third_number


print(task_1(number_list))
print(task_2(number_list))
示例#7
0
from utils import inputfile_to_array
import re
bus_table = inputfile_to_array("inputs/input_day_13.txt")


def get_timestamp_and_bus_list(bus_table):
    timestamp = int(bus_table[0])
    busses_raw = bus_table[1]

    bus_list = re.findall('[0-9]+', busses_raw)
    bus_list = [int(item) for item in bus_list]
    return timestamp, bus_list


def get_earliest_bus(timestamp, bus_list):
    earliest_bus = bus_list[0]
    time_to_arrival = 99999999999
    for bus_time in bus_list:
        new_time_to_arrival = int(bus_time) - (timestamp % bus_time)
        if new_time_to_arrival < time_to_arrival:
            time_to_arrival = new_time_to_arrival
            earliest_bus = bus_time
    return earliest_bus, time_to_arrival


def task_1(bus_table):
    timestamp, bus_list = get_timestamp_and_bus_list(bus_table)
    print(timestamp)
    print(bus_list)
    earliest_bus, time_to_arrival = get_earliest_bus(timestamp, bus_list)
    return (earliest_bus * time_to_arrival)
示例#8
0
from utils import inputfile_to_array

boot_code = inputfile_to_array("inputs/input_day_8.txt")


def perform_instruction(instruction, accumulator, i, sign, number):
    if instruction == "acc":
        i += 1
        if sign == "-":
            accumulator -= number
        elif sign == "+":
            accumulator += number
    elif instruction == "jmp":
        if sign == "-":
            i -= number
        elif sign == "+":
            i += number
        else:
            print("Sign is neither '-' nor '+' ")
    elif instruction == "nop":
        i += 1
    return (i, accumulator)


def get_all_nop_instruction_indexes(boot_code):
    indexes = []
    i = 0
    for line in boot_code:
        if "nop" in line:
            indexes.append(i)
        i += 1
示例#9
0
from utils import inputfile_to_array

map = inputfile_to_array("inputs/input_day_3.txt")

slope_list = [
    [1, 1],
    [3, 1],
    [5, 1],
    [7, 1],
    [1, 2],
]


def traverse_different_slopes(map, slope_list):
    tree_hits = 1  # Set to 1 because the answer is a product, so setting it to 0 would give 0 either way
    for slope in slope_list:
        current_tree_hits = traverse_slope(map, slope)
        tree_hits = tree_hits * current_tree_hits
    return tree_hits


def traverse_slope(map, slope=[3, 1]):
    x = 0
    tree_counter = 0
    width_of_map = len(map[0])
    right_steps = slope[0]
    down_steps = slope[1]
    for y, val in enumerate(map):
        if (y) % down_steps == 0 and y != 0:
            x = x + right_steps
            if x >= width_of_map:
示例#10
0
from utils import inputfile_to_array
import functools

joltage_list = sorted([int(item) for item in inputfile_to_array("inputs/input_day_10.txt")])

memo_dict = {}
def get_permutations(joltage_list, the_element_before):
    worklist = joltage_list[:]
    if worklist:
        usable_adapters_this_round = get_elements_with_small_enough_difference(worklist, the_element_before)
        permutations = 0
        for adapter in usable_adapters_this_round:
            list_to_pass_to_function = worklist[:]
            if adapter in memo_dict:
                permutations += memo_dict[adapter]
            else:
                list_to_pass_to_function = [x for x in worklist if x > adapter]
                permutations_from_this_run = int(get_permutations(list_to_pass_to_function, adapter))
                memo_dict[adapter] = permutations_from_this_run
                permutations = permutations + permutations_from_this_run
        return permutations
    return 1

def get_elements_with_small_enough_difference(joltage_list, element_to_compare_to):
    output_list = []
    for element in joltage_list:
        if abs(element-element_to_compare_to) <= 3:
            output_list.append(element)
    return output_list

def get_joltage_differences(joltage_list):
示例#11
0
import re
from utils import inputfile_to_array
from math import floor, ceil
from statistics import mean

seating_codes = inputfile_to_array("inputs/input_day_5.txt")


def get_seat_row(row_code):
    upper_limit = 127
    lower_limit = 0
    for character in row_code:
        if character == "F":
            upper_limit = floor(mean([lower_limit, upper_limit]))
        elif character == "B":
            lower_limit = ceil(mean([lower_limit, upper_limit]))
        else:
            print(
                " This should never happend, the row character is neither 'B' nor 'F"
            )
    return upper_limit  # Same as lower limit when function is returning


def get_seat_column(column_code):
    upper_limit = 7
    lower_limit = 0
    for character in column_code:
        if character == "L":
            upper_limit = floor(mean([lower_limit, upper_limit]))
        elif character == "R":
            lower_limit = ceil(mean([lower_limit, upper_limit]))
示例#12
0
from utils import inputfile_to_array, get_input_file
import re

get_input_file(14)
initialization_program = inputfile_to_array("inputs/input_day_14.txt")


def parse_input(initialization_program):
    mask_index = -1
    instruction_list = []
    mask_regex = r"mask = ([\dX]+)"
    mem_regex = r"mem\[([\d]+)\] = ([\d]+)"
    highest_address_seen = 1
    for line in initialization_program:
        mask_match = re.findall(mask_regex, line)
        mem_match = re.findall(mem_regex, line)
        if mask_match != []:
            instruction_list.append({"mask": mask_match[0], "mem_list": []})
            mask_index += 1
        elif mem_match != []:
            mem_list = instruction_list[mask_index].get("mem_list")
            memory_address, _ = mem_match[0]
            mem_list.append(mem_match[0])
            if int(memory_address) > int(highest_address_seen):
                highest_address_seen = int(memory_address)
            instruction_list[mask_index] = {
                "mask": instruction_list[mask_index].get("mask"),
                "mem_list": mem_list
            }
    return instruction_list, highest_address_seen
示例#13
0
import re
from utils import inputfile_to_array, remove_empty_lines_and_concat
from math import floor, ceil
from statistics import mean 

customs_form = inputfile_to_array("inputs/input_day_6.txt")

def count_unique_letters(the_string):
    the_set = set()
    for letter in the_string:
        the_set.add(letter)
    return len(the_set)        

def count_letters_in_all_people_of_group(one_groups_declarations):
    '''
    Returns the number of common letters i decleration across all persons in a groups
    '''
    the_set = set()
    one_groups_declarations_list = one_groups_declarations.split(" ")
    first_declaration = one_groups_declarations_list[0]
    for letter in first_declaration:
        the_set.add(letter)
    for decleration in one_groups_declarations_list:
        letters_to_be_removed = []
        for letter in the_set:
            if letter not in decleration:
                letters_to_be_removed.append(letter)
        for letter in letters_to_be_removed:
            the_set.remove(letter)
    return len(the_set)