def setUp(self) -> None: input_lines = [line.split(':') for line in load_input_file(os.getcwd(), 'input_test.txt')] self.given_correct_answers_2020 = {} for starting_numbers, solution in input_lines: self.given_correct_answers_2020[int(solution)] = [int(i) for i in starting_numbers.split(',')] input_lines = [line.split(':') for line in load_input_file(os.getcwd(), 'input_test_30much.txt')] self.given_correct_answers_30much = {} for starting_numbers, solution in input_lines: self.given_correct_answers_30much[int(solution)] = [int(i) for i in starting_numbers.split(',')]
def setUp(self) -> None: self.input_lines = [line.split('(contains ') for line in load_input_file(os.getcwd(), 'test_input.txt')]
def test_part_two(self): my_sim_sat = SateliteSimulation( load_input_file(os.getcwd(), 'test_input.txt'), 4) self.assertEqual(my_sim_sat.boot_up_(), SOLUTION_TEST_PART_TWO)
""" import os from common import load_input_file from typing import List def line_split(line): rule, password = line.split(': ') letter_for_rule = rule.split(' ')[-1] min_rule, max_rule = [int(e) for e in rule.split(' ')[0].split('-')] return (min_rule, max_rule, letter_for_rule, password) if __name__ == "__main__": print("Welcome to password_checker.py") input_list = load_input_file(folder=os.getcwd()) check_pw_part_one: List[bool] = [] for min_rule, max_rule, letter_for_rule, password in [ line_split(e) for e in input_list ]: # print(f'{min_rule}, {max_rule}, {letter_for_rule}, {password}') letter_account = sum([1 for e in password if e == letter_for_rule]) password_valid = (min_rule <= letter_account <= max_rule) # print(password_valid) check_pw_part_one.append(password_valid) print( f'Part one: Number of Valid Passwords: {len([e for e in check_pw_part_one if e])}' ) check_pw_part_two: List[bool] = []
]) col_val = sum([ pow(2, counter) for counter, val in enumerate(reversed(line_input[7:])) if val == 'R' ]) return row_val, col_val def get_seat_id(row_col): return row_col[0] * 8 + row_col[1] if __name__ == "__main__": print("Welcome to seat_decipher.py") input_lines = load_input_file(os.getcwd()) '''# check from given examples #input_lines.extend(['BFFFBBFRRR', 'FFFBBBFRRR', 'BBFFBBFRLL']) #print(input_lines) # for debugging for line in input_lines: (row, col) = decipher_line(line) print(f'{line[:7]} and {line[7:]}: ', end='') print(f'This is row {row} and col {col}. ', end='') print(f'This is seat ID {get_seat_id((row, col))}')''' list_of_seats = sorted( [get_seat_id(decipher_line(line)) for line in input_lines]) print(max(list_of_seats)) for counter, e in enumerate(list_of_seats): if e + 1 == list_of_seats[counter + 1]: continue
for part in input_parts: splitted_parts = part.split(':') tile_id = int(splitted_parts[0].split(' ')[1]) tile = splitted_parts[1].lstrip().split('\n') act_part = PuzzlePiece(tile_id, tile) self.part_dict[act_part] = [] def find_matches(self): pass def load_input(filename='input.txt', folder=os.getcwd()): with open(os.path.join(folder, filename)) as f: input = f.read() return input.split('\n\n') def solve_puzzle(puzzle_dict: Dict): pass def create_puzzle_dict(input_lines: List[str]) -> Dict: pass if __name__ == "__main__": print("Welcome to puzzle_solver.py") parts = load_input() my_puzzle = Puzzle(parts) print(solve_puzzle(create_puzzle_dict(load_input_file(os.getcwd()))))
continue else: invalid_numbers.append(field_num) return sum(invalid_numbers) def match_rule(rule, value) -> bool: return rule[0][0] <= value <= rule[0][1] or rule[1][0] <= value <= rule[1][ 1] if __name__ == "__main__": print("Welcome to train_ticket_checker.py") # part one print(check_error_codes(load_input_file(os.getcwd()))) # part two rules, my_ticket, nearby_tickets = get_input_fields( load_input_file(os.getcwd())) valid_numbers = get_valid_numbers(rules) rules_dict = get_rule_dict(rules) valid_tickets = [ ticket for ticket in nearby_tickets if ticket_is_valid(valid_numbers, ticket) ] # initialize possible fields valid_fields = { i: [key for key in rules_dict.keys()] for i in range(len(my_ticket))
# -*- coding:utf-8 -*- """ Created on 01/12/2020 08:56 @author: Sebastian get_multiple_of_2020.py is a script for advent of code 01/01 """ import os import copy from common import load_input_file FIXED_MULTIPLE = 2020 if __name__ == "__main__": print("Welcome to get_multiple_of_2020.py") input_list = load_input_file(os.getcwd()) print(len(input_list)) remainder_list = copy.copy(input_list) for number in input_list: rest = FIXED_MULTIPLE-number if rest < 0 or rest not in remainder_list: remainder_list.remove(number) continue print(f'Found sum of 2020 with {number} and {rest}') print(f'Multiple is {number*rest}') break break_flag = False for number in input_list: for sec_number in [e for e in input_list if not e == number]: if number+sec_number > FIXED_MULTIPLE:
# -*- coding:utf-8 -*- """ Created on 06/12/2020 10:50 @author: Sebastian costoums_form_checker.py is a script for advent of code day 6 """ import os from common import load_input_file from string import ascii_lowercase if __name__ == "__main__": print("Welcome to costoums_form_checker.py") input_lines = '\n'.join(load_input_file(os.getcwd())).split('\n\n') answers_per_group = [] #part one for line in input_lines: group_answers = { e for person_answer in line.split('\n') for e in person_answer } answers_per_group.append(len(group_answers)) print(sum(answers_per_group)) #part two group_all_yes_answers = [] for line in input_lines: group_answers = set(ascii_lowercase) for person_answer in line.split('\n'):
print('Player one wins game!') return player_one, True print('Player two wins game!') return player_two, False def get_score(winning_deck: List[int]) -> int: return sum([(counter + 1) * value for counter, value in enumerate(reversed(winning_deck))]) def deal_hands(input_lines: List[str]) -> (List[int], List[int]): for counter, value in enumerate(input_lines): if value != '': continue player_one = [int(val) for val in input_lines[1:counter]] player_two = [int(val) for val in input_lines[counter + 2:]] return player_one, player_two if __name__ == "__main__": print("Welcome to crab_combat.py") player_one, player_two = deal_hands(load_input_file(os.getcwd())) winning_deck = play_crab_combat(player_one, player_two) print(get_score(winning_deck)) player_one, player_two = deal_hands(load_input_file(os.getcwd())) winning_deck_part_two, player_one_won = play_recursive_crab_combat( player_one, player_two) print(player_one_won) print(get_score(winning_deck_part_two))
return [int_from_str_bit(i) for i in get_all_combinations([new_value])] def write_new_value(self, address, value): # new_value = self.apply_mask(value) for address in self.apply_mask_v2(address): self.memory[address] = int(value) def sum_all_up(self): return sum([v for v in self.memory.values()]) def sum_all_up_v2(self): pass if __name__ == "__main__": print("Welcome to ferry_docking.py") input_lines_splitted = [ s.split(' = ') for s in load_input_file(os.getcwd()) ] my_memory = MemoryWriter() for command, value in input_lines_splitted: if command == 'mask': my_memory.set_mask(value) continue # better use re next time mem_address = int(command[4:-1]) my_memory.write_new_value(mem_address, value) print(my_memory.sum_all_up())
] def check_pid(self) -> bool: """pid (Passport ID) - a nine-digit number, including leading zeroes.""" if pid_re.match(self.passport_vals['pid']): return True return False def check_cid(self) -> bool: """cid (Country ID) - ignored, missing or not.""" return True if __name__ == "__main__": print("Welcome to passport_checking.py") flat_split_input = '\n'.join(load_input_file(os.getcwd())).split('\n\n') list_of_valid_passports: List[Passport] = [] for line in flat_split_input: line = line.replace('\n', ' ').split(' ') if len(line) not in [7, 8]: continue act_passport = Passport(input_line=line) if act_passport.is_valid(): list_of_valid_passports.append(act_passport) print( f'Found {sum([1 for e in list_of_valid_passports if e.is_valid()])} valid Passports by ' f'simple field check') print( f'Rechecking values found {sum([1 for e in list_of_valid_passports if e.check_all() and e.is_valid()])} valid Passports.'
def test_part_1(self): input = load_input_file(os.getcwd(), 'test_input.txt') self.assertEqual(check_error_codes(input), 71)
if line_counter in list_of_executed_lines: print( f'Found first line visted twice! {line_counter} after {len(list_of_executed_lines)} operations' ) print(f'Accumulator value is {accumulator_value["act_val"]}') return False, accumulator_value else: list_of_executed_lines.append(line_counter) if line_counter == last_instruction: print('Found end of programm!') return True, accumulator_value if __name__ == "__main__": print("Welcome to assembler.py") input_lines = [line.split(' ') for line in load_input_file(os.getcwd())] # part 1 _, acc_value = check_execution(programm=input_lines) print(acc_value) # part 2 for counter, (command, value) in enumerate(input_lines): replace_command = command if command == 'acc': continue if command == 'jmp': replace_command = 'nop' if command == 'nop': replace_command = 'jmp' next_program = copy(input_lines) next_program[counter] = (replace_command, value)
def setUp(self) -> None: self.input_lines = load_input_file(os.getcwd(), 'test_input.txt') self.starting_dict = flipping_tiles_from_line(self.input_lines)
def setUp(self) -> None: input_lines = load_input_file(os.getcwd(), 'test_input.txt') self.player_one, self.player_two = deal_hands(input_lines)
def test_part_one(self): self.assertEqual(10, part_one(self.input_lines)) real_input = load_input_file(os.path.join(os.getcwd(), '..')) self.assertEqual(485, part_one(real_input))
return 1 if n == 2: return 2 if n == 3: return 4 if n == 4: return 7 if n == 5: return 13 raise ValueError if __name__ == "__main__": print("Welcome to jotage_adpaters.py") input_number_sorted = [int(i) for i in load_input_file(os.getcwd(), file='input.txt')] input_number_sorted.append(0) input_number_sorted.append(max(input_number_sorted) + 3) input_number_sorted.sort() differences = [input_number_sorted[counter + 1] - input_number_sorted[counter] for counter in range(len(input_number_sorted) - 1)] eins_jolt_diff = len([i for i in differences if i == 1]) drei_jolt_diff = len([i for i in differences if i == 3]) print(f'Found 1 jolt differences {eins_jolt_diff}, 3 jolt differences {drei_jolt_diff}, ' f'Product {eins_jolt_diff * drei_jolt_diff}') # in the set of differences, find sequence pattern list_of_kombination = [get_kombinations(find_next_drei(0, differences)+1)] for counter, diff in enumerate(differences): if diff == 1: continue if diff == 3:
return OCCUPIED_SEAT return square_val[4] def convert_to_empty(square_val): surround = surrounding(square_val) if square_val[4] == OCCUPIED_SEAT and sum( [1 for i in surround if i == OCCUPIED_SEAT]) >= OCCUPIED_TOLERANCE: return EMPTY_SEAT return square_val[4] if __name__ == "__main__": print("Welcome to ising_model_seats.py") input_vals = [ bytearray(line, 'utf-8') for line in load_input_file(os.getcwd()) ] # print(input_lines) same_occupation = True max_depth = len(input_vals) max_line = len(input_vals[0]) iter_counter = 0 new_vals = deepcopy(input_vals) while same_occupation: previous_occupied = get_all_occ_seats(input_vals) for x in range(max_depth): for y in range(max_line): new_vals[x][y] = convert_to_occupied( get_surrounds(input_vals, x, y)) for x in range(max_depth):
def setUp(self) -> None: self.rules, self.messages = split_rules( load_input_file(os.getcwd(), 'test_input.txt'))
subrules = implicit_rule.split(' | ') final_rule = [] for subrule in subrules: if len(subrule) == 1: return rules_dict[subrules[0]].replace('"', '') sub_final_rule = [] for subrule in number_matching.findall(subrule): rule_implicit = True adapted_rule = subrule while rule_implicit: adapted_rule = make_rule_explicit(adapted_rule, rules_dict) rule_implicit = any([number_matching.match(part) for part in adapted_rule]) sub_final_rule.append(adapted_rule) if len(sub_final_rule) > 1 and any([True for r in sub_final_rule if '|' in r]): # print('simething') sub_split = [r.split('|') for r in sub_final_rule] sub_final_rule = [''.join(i) for i in product(*sub_split)] final_rule.append(sub_final_rule) print(final_rule) # resolve final rules with more then one "" (double) return '|'.join(''.join(line) for line in final_rule) if __name__ == "__main__": print("Welcome to pattern_matching.py") rules, messages = split_rules(load_input_file(os.getcwd())) print(part_one(rules, messages))
from common import load_input_file SUBSET_LENGTH = 25 def find_sum_of_two(number: int, subset: List[int]): if len(subset) != SUBSET_LENGTH: print('INVALID SUBSET GIVEN: LENGTH!') return [summand for summand in subset if number - summand in subset] if __name__ == "__main__": print("Welcome to XMAS_decipher.py") input_numbers = [int(i) for i in load_input_file(os.getcwd())] max_iter_val = len(input_numbers) - SUBSET_LENGTH - 1 for counter in range(max_iter_val): findings = find_sum_of_two(number=input_numbers[counter + SUBSET_LENGTH], subset=input_numbers[counter:SUBSET_LENGTH + counter]) if not findings: weakness_value = input_numbers[counter + SUBSET_LENGTH] print(weakness_value) break for low_counter in range(max_iter_val): found_set = [] for up_counter in range(low_counter + 1, max_iter_val, 1): cur_sum = sum(input_numbers[low_counter:up_counter]) if cur_sum < weakness_value: continue
loop_counter += 1 return loop_counter def get_encryption_key(public_key: int, loop_number: int) -> int: encryption_key = public_key # key_list = [public_key] for counter in range(1, loop_number): encryption_key = subject_number(encryption_key, public_key) # key_list.append(encryption_key) return encryption_key if __name__ == "__main__": print("Welcome to fun_with_encryptions.py") public_keys = [int(i) for i in load_input_file(os.getcwd())] door_public = public_keys[0] card_public = public_keys[1] door_loop_number = get_loop_number(door_public) card_loop_number = get_loop_number(card_public) encryption_door = get_encryption_key(door_public, card_loop_number) encryption_card = get_encryption_key(card_public, door_loop_number) if encryption_card == encryption_door: print(f'encryption succeeded! {encryption_door}') else: print(f'failure during encryption: {encryption_door} {encryption_card}')
def setUp(self) -> None: input_lines = load_input_file(os.getcwd(), 'test_input.txt') self.puzzle_dict = create_puzzle_dict(input_lines)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ Created on 13/12/2020 12:30 @author: Sebastian Lehrack bus_terminal.py is a script for advent of code day 13 """ import os from common import load_input_file BUS_LINE_OFFSET = [(counter, int(value)) for counter, value in enumerate(load_input_file(os.getcwd())[1].split(',')) if value != 'x'] def check_bus_line(time, offset_val): for offset, bus_line in offset_val: if (time + offset) % bus_line != 0: return 0 return time if __name__ == "__main__": print("Welcome to bus_terminal.py") input_lines = load_input_file(os.getcwd())