Example #1
0
from funcs import read_input
import re

messages = read_input('inputs/day19_test.txt')
rules = {
    int(i): r
    for i, r in [m.split(': ') for m in messages[:messages.index('')]]
}
messages = messages[messages.index('') + 1:]

for k, v in sorted(rules.items(), key=lambda x: x[0]):
    if re.search("[a-z]", v):
        rules[k] = re.search("[a-z]", v).group(0)
    # actually should do this AFTER
    elif '|' in v:
        rules[k] = [
            int(num)
            for num in [string.strip().split(' ') for string in v.split('|')]
        ]
    else:
        rules[k] = [v.strip()]
        rules[k] = [seq.split(' ') for seq in rules[k]]
    print(k, ": ", v)
    print(k, ": ", rules[k])


def count_nums_in_rule(rule):
    count_nums = 0
    for i in range(len(rule)):
        # each list within rules[0] is an allowed sequence
        for pos in rule[i]:
Example #2
0
            index_changed.append(temp_index)
            if self.temp_code[temp_index][0] == 'nop':
                if self.temp_code[temp_index][1] != 0:
                    self.temp_code[temp_index] = (
                        'jmp', self.temp_code[temp_index][1])
                else:
                    continue
            elif self.temp_code[temp_index][0] == 'jmp':
                self.temp_code[temp_index] = ('nop',
                                              self.temp_code[temp_index][1])
            code_fixed = self.test_code(self.temp_code)
        return self.acc


# run tests
test_program = Code(read_input('inputs/day8_test.txt'))
test_program.test_code(test_program.code)
assert test_program.acc == 5, f"Accumulator is {test_program.acc}, should be 5"
assert test_program.fix_code(
) == 8, f"Accumulator is {test_program.acc}, should be 8"
print("Tests complete\n\nDAY 8 SOLUTION")

# Part one - run the code until reaching a duplicate row, then print current value of accumulator
program = Code(read_input('inputs/day8.txt'))
program.test_code(program.code)
print(program.acc)

# Part two - keep tweaking the code until it runs to the last line.
fixed_acc = program.fix_code()
print(fixed_acc)
Example #3
0
from funcs import read_input

# Read input
expenses = read_input('inputs/day1.txt', True)


def find_solution():
    # loop through each entry and add to each other entry
    for i in range(len(expenses)):
        for j in range(len(expenses)):
            if i == j:
                continue
            #... until we find two that sum to 2020
            elif expenses[i] + expenses[j] == 2020:
                return expenses[i] * expenses[j]


print(find_solution())

# Part two


def find_solution_two():
    # loop through each entry and add to each other entry
    for i in range(len(expenses)):
        for j in range(len(expenses)):
            if i == j:
                continue
            for k in range(len(expenses)):
                if i == k or j == k:
                    continue
Example #4
0
        assert ticket.row_num == row, f"Ticket {ticket.boarding_pass} should have row {row}, returns {ticket.row_num}"
        assert ticket.col_num == col, f"Ticket {ticket.boarding_pass} should have column {col}, returns {ticket.col_num}"
        assert ticket_id == 8 * row + col, f"Ticket {ticket.boarding_pass} should have id {8*row + col}, returns {ticket.id}"


# check that tests pass
test_binary_converter()

# for part two - create grid of seats
plane = np.zeros((128, 8))
seat_ids = []
seats = []

# read input
first = True
for line in read_input('inputs/day5.txt'):
    ticket = Ticket(line)
    ticket_id = ticket.solve()
    seat_ids.append(ticket_id)
    plane[ticket.row_num, ticket.col_num] = 1

max_id = max(seat_ids)

print(f'The highest ticket ID is {max_id}')

# Part two: which seats are left?

your_seat = []

for i in range(0, plane.shape[0]):
    row = []
Example #5
0
# Day 13
from funcs import read_input

earliest, bus_numbers = read_input('inputs/day13.txt')
earliest = int(earliest)

class Bus:
    def __init__(self, id):
        self.depart_times = [0]
        self.id = id
        while self.depart_times[-1] < earliest:
            self.depart_times.append(self.depart_times[-1] + id)
        self.earliest_depart = self.depart_times[-1]

bus_numbers = [Bus(int(bus)) for bus in bus_numbers.split(',') if bus != 'x']

print("Part one")

earliest_bus = bus_numbers[-1].earliest_depart

for bus in bus_numbers:
    if bus.earliest_depart < earliest_bus:
        bus_to_take = bus
        
wait = bus_to_take.earliest_depart - earliest

print(f"Earliest departure is bus number {bus_to_take.id} at {bus_to_take.earliest_depart} so the wait is {wait}.")

print(f"Solution is {wait * bus_to_take.id}")
Example #6
0
# Day 6
from funcs import read_input

# read input
part_two_answers = read_input('inputs/day6.txt', sep = '\n\n')

# join individual answers together into a single string per group for part one
part_one_answers = [
        line.replace('\n', '') for line in 
        part_two_answers
    ]

# Part one solution

# count number of unique characters in each group string
total_answers = sum([len(set(group)) for group in part_one_answers])

print(total_answers)

#Part two solution

total_answered_by_all = 0

# loop through each group
for group in part_two_answers:
    # get unique characters for each group
    for q in set(group.replace('/n', '')):
        # if the number of occurences equals the number of people, add one to final count
        if group.count(q) == len(group.split('\n')):
            total_answered_by_all += 1
            
Example #7
0
from funcs import read_input


class RowOfTrees:
    def __init__(self, pattern):
        self.pattern = pattern

    def extend(self):
        # repeat the pattern as many times as needed
        self.pattern += self.pattern


# get input
patterns = read_input('inputs/day3.txt')


def count_trees(input_strings, right, down):
    # list of RowOfTrees objects
    rows_of_trees = []
    for pattern in input_strings:
        rows_of_trees.append(RowOfTrees(pattern))

    # starting position
    pos = [0, 0]

    # tree counter
    trees = 0

    # loop through rows
    while pos[0] < len(rows_of_trees):  # start at position 0
        # is it a tree?
Example #8
0
# DAY 9
from funcs import read_input

# switch between test data and real data
test = False

# set filename and length of preamble list
if test:
    file = 'inputs/day9_test.txt'
    preamble_len = 5
else:
    file = 'inputs/day9.txt'
    preamble_len = 25

# read input data
data = read_input(file, '\n', True)

# get preamble numbers
preamble = []

# initiate preamble
for i in range(preamble_len):
    preamble.append(data.pop(0))

# continuously shift numbers from data to preamble and
# look for numbers in the preamble that sum to the first number in data
while True:
    target = data[0]
    for i, num in enumerate(preamble[:-1]):
        diff = target - num
        if diff == target and preamble.count(diff) < 2:
Example #9
0
from funcs import read_input
import re

ingredients_allergens = read_input('inputs/day21_test.txt')

ingredients = [line.split(' (')[0] for line in ingredients_allergens]
allergens = [
    re.search('\(.+\)', line).group(0)[10:-1] for line in ingredients_allergens
]

print(ingredients)
print(allergens)
Example #10
0
        if partnum == 2:
            print(line)
            print(do_math(line, partnum))
        total += do_math(line, partnum)
    return total


def run_tests():
    test_inputs = [
        "1 + (2 * 3) + (4 * (5 + 6))", "2 * 3 + (4 * 5)",
        "5 + (8 * 3 + 9 + 3 * 4 * 3)",
        "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))",
        "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"
    ]
    solutions_1 = [51, 26, 437, 12240, 13632]
    solutions_2 = [51, 46, 1445, 669060, 23340]
    for i in range(len(test_inputs)):
        assert do_math(test_inputs[i], 1) == solutions_1[
            i], f"Part one: {test_inputs[i]} should evaluate to {solutions_1[i]}"
        assert do_math(test_inputs[i], 2) == solutions_2[
            i], f"Part two: {test_inputs[i]} should evaluate to {solutions_2[i]}"
    print("Tests passed")


math_homework = read_input('inputs/day18.txt')
run_tests()
part_one = do_my_homework(math_homework, 1)
print("Part one solution: ", part_one)
part_two = do_my_homework(math_homework, 2)
print("Part two solution: ", part_two)
Example #11
0
            for pair in replacements:
                address[pair[0]] = pair[1]
            addresses.append(''.join(address))
        return addresses

    def set_memory(self, pos, dec_num):
        memory_locations = self.apply_mask(pos)
        for loc in memory_locations:
            self.memory_used[loc] = int(
                dec_num)  # self.binary_converter(bin_num)

    def calculate_memory_total(self):
        print(sum(self.memory_used.values()))


instructions = [line.split(" = ") for line in read_input('inputs/day14.txt')]

memory = Memory()

for line in instructions:
    if line[0] == 'mask':
        memory.mask = line[1]
    else:
        position = re.search('\d+', line[0]).group(0)
        memory.set_memory(position, line[1])

for k, v in memory.memory_used.items():
    print(f'{k}:\t{v}')

memory.calculate_memory_total()
Example #12
0
from funcs import read_input
# Day 2 - Password Philosphy

# read input file
policy_passwords = [line.split(': ') for line in read_input('inputs/day2.txt')]

# Part one - count valid passwords based on policy being number of given letter allowed.
valid_pws = 0

# iterate through lists
for [pol, pw] in policy_passwords:
    count, letter = pol.split(' ')
    [min_count, max_count] = [int(x) for x in count.split('-')]
    # count occurence of letter in password
    counter = pw.count(letter)
    if counter >= min_count and counter <= max_count:
        valid_pws += 1

print(valid_pws)

# Part two - policy now describes index of letter (one index is allowed to hold letter)
# indexing starts at 1!!!!!!!!!!!

valid_pws = 0

for [pol, pw] in policy_passwords:
    count, letter = pol.split(' ')
    [min_index, max_index] = [int(x) - 1 for x in count.split('-')]
    # if only one of the indices is the letter, add 1 to valid password count
    if (pw[min_index] == letter) is not (pw[max_index] == letter):
        valid_pws += 1
        self.waypoint_pos = new_waypoint_dir

    def move(self, direction_in_instructions: str, distance: int):
        if direction_in_instructions == 'F':
            for key in self.waypoint_pos.keys():
                self.position[key] += self.waypoint_pos[key] * distance
        else:
            movement_dir = self.direction_map[direction_in_instructions]
            self.waypoint_pos[movement_dir] += distance

    def update_position(self):
        self.x_pos.append(self.position[180] - self.position[0])
        self.y_pos.append(self.position[270] - self.position[90])


instructions = read_input('inputs/day12.txt')

ship = ShipWithWaypoint()
print("Ship position: ", end='\t\t')
print(ship.position)
print("Waypoint position: ", end='\t')
print(ship.waypoint_pos)
print()

i = 0
for step in instructions:
    if i < 10:
        print(step)
    ship.read_instruction(step)
    if i < 10:
        print("Ship position: ", end='\t\t')
Example #14
0
from funcs import read_input

adapters = sorted(read_input('inputs/day10.txt', convert_to_int=True))

socket = 0
diffs = []

for a in adapters:
    diffs.append(a - socket)
    socket = a

diffs.append(3)

print(diffs.count(1) * diffs.count(3))
Example #15
0
def list_contents(color: str, bag_contents: Dict, count=1, recur=False) -> Set:
    inside_color = set([(col[0], col[1] * count)
                        for col in bag_contents[color]])
    if recur:
        print("Recursion time!\t", f"count = {count}\tColor is {color}")
    for bag, count in inside_color:
        print(bag, count)
    print(' ')
    for col, n in inside_color:
        inside_color = inside_color.union(
            list_contents(col, bag_contents, n, True))
    return inside_color


lines = [
    line for line in read_input('inputs/day7.txt')
    if not re.search("no other bags", line)
]

print('How many bags can hold the shiny gold bag?')
bag_holders = sort_bags(lines)
print(len(list_holders('shiny gold', bag_holders)))

contents = sort_bags(lines, True)

print("How many bags are inside the shiny gold bag?")

group_bags = {}

for bag, count in list_contents('shiny gold', contents):
    print(bag, count)