def test_input_per_line_numeric(): entries = parse_input.input_per_line("numeric_per_line_input.txt") assert entries[0] == "234234" assert entries[1] == "54565677" assert entries[2] == "23452345345456" assert entries[3] == "23423453454" assert entries[4] == "233232"
number = f'-{matches[0][2]}' if matches[0][1] == "lose" else matches[0][2] if matches[0][0] not in seating_dictionary: seating_dictionary[matches[0][0]] = {} seating_dictionary[matches[0][0]][matches[0][3]] = number return seating_dictionary def create_graph(input_dictionary): index_dictionary = {index: key for index, key in enumerate(input_dictionary.keys())} matrix = [] for number in range(len(index_dictionary)): temp_internal_list = [] person = index_dictionary[number] for another_number in range(len(index_dictionary)): if another_number == number: temp_internal_list.append(0) else: temp_internal_list.append(int(input_dictionary[person][index_dictionary[another_number]])) temp_internal_list.append(0) matrix.append(temp_internal_list) final_zeroes = [0] * (len(index_dictionary) + 1) matrix.append(final_zeroes) return matrix if __name__ == "__main__": guest_list = parse_input.input_per_line('../input.txt') guest_dictionary = create_dictionary(guest_list) guest_matrix = create_graph(guest_dictionary) final_happiness_level = happy_seating_genetic_algorithm(guest_matrix, 0, len(guest_matrix)) print(f"The greatest happiness level with the best seating arrangement is {final_happiness_level}")
""" dimensions_as_strings = dimensions.split('x') return [int(number) for number in dimensions_as_strings] def determine_areas(dimension): """Take a list with numbers and find out the area of the box plus the extra area needed.""" smallest_side_area = sorted(dimension)[0] * sorted(dimension)[1] box_area = 2 * dimension[0] * dimension[1] + 2 * dimension[1] * dimension[ 2] + 2 * dimension[2] * dimension[0] return smallest_side_area, box_area def full_area(two_areas): """Take the tuple with the box area and the small area and combine them.""" return two_areas[0] + two_areas[1] def add_up_all_boxes(box_dimension_list): """Take a list of areas and add them all up.""" all_areas = [ full_area(determine_areas(get_dimensions(box))) for box in box_dimension_list ] return reduce(lambda a, b: a + b, all_areas) if __name__ == "__main__": box_dimensions = parse_input.input_per_line('../input.txt') print(add_up_all_boxes(box_dimensions))
from sys import path path.insert(0, '../../input_parsing') import parse_input if __name__ == "__main__": assembly = parse_input.input_per_line('../input.txt') pointer = 0 register_a = 1 register_b = 0 while pointer < len(assembly): current_instruction = assembly[pointer].split() if len(current_instruction) == 2: if current_instruction[0] == "hlf": if current_instruction[1] == "a": register_a = register_a / 2 else: register_b = register_b / 2 pointer += 1 elif current_instruction[0] == "tpl": if current_instruction[1] == "a": register_a *= 3 else: register_b *= 3 pointer += 1 elif current_instruction[0] == "inc": if current_instruction[1] == "a": register_a += 1 else: register_b += 1 pointer += 1 elif current_instruction[0] == "jmp":
from itertools import combinations, permutations from math import prod from statistics import mean from sys import path path.insert(0, '../../input_parsing') import parse_input if __name__ == "__main__": packages = parse_input.input_per_line('../input.txt') packages = [int(x) for x in packages] # test # packages = [1,2,3,4,5,7,8,9,10,11] weight_per_section = sum(packages) / 3 print(f"{weight_per_section=}") package_combinations = [ element for size in range(1, len(packages)) for element in combinations(packages, size) if sum(element) == weight_per_section ] # print(package_combinations) # figure out smallest group 1 size santa_leg_room_packages = 100000000000000000 for combination in package_combinations: if len(combination) < santa_leg_room_packages: santa_leg_room_packages = len(combination) group_1_contenders = [ combination for combination in package_combinations if len(combination) == santa_leg_room_packages ] print(group_1_contenders) if len(group_1_contenders) == 1:
return bag_dict @lru_cache() def find_gold_bag_carriers(bag_key: str) -> int: """Take a key for the dictionary of bag rules and figure out if it can eventually hold a gold bag. Return how many can eventually contain a gold bag. """ shiny_count = 0 for bag_tuple in bag_dict[bag_key]: if bag_tuple[1] == "shiny gold": shiny_count = 1 elif bag_tuple[1] == "no other": shiny_count += 0 else: shiny_count += find_gold_bag_carriers(bag_tuple[1]) if shiny_count > 0: break return shiny_count if __name__ == "__main__": bag_guidelines = parse_input.input_per_line("../input") bag_dict = create_bag_dictionary(bag_guidelines) gold_bag_carrier_count = sum( find_gold_bag_carriers(bag) for bag in bag_dict.keys()) print( f"{gold_bag_carrier_count} bags eventually can contain at least one shiny gold bag" )
if "red" in elf_json.values(): return 0 elif isinstance(value, int): summation += value elif isinstance(value, list): summation += find_numbers(value) elif isinstance(value, dict): summation += find_numbers(value) else: # this is a color string summation += 0 # this used to be a print statement return summation if __name__ == "__main__": json_string = parse_input.input_per_line('../input.txt') total = json.loads(json_string[0]) print( f"The sum of all numbers in the document (unless it's got a red property) is {find_numbers(total)}" ) # 144587 is too high # 1049 is too low # 142062 is too high # 129639 is not the answer # 138826 is not the answer # 134100 is not the answer # 142186 is not the answer # 24486 is not the answer # 15364 is not the answer # 28792 is not the answer
del potential_aunts_2[key] elif values.get('cats') is not None and values.get("cats") <= 7: del potential_aunts_2[key] elif values.get("samoyeds") not in [2, None]: del potential_aunts_2[key] elif values.get( 'pomeranians') is not None and values.get("pomeranians") >= 3: del potential_aunts_2[key] elif values.get("akitas") not in [0, None]: del potential_aunts_2[key] elif values.get("vizslas") not in [0, None]: del potential_aunts_2[key] elif values.get( 'goldfish') is not None and values.get("goldfish") >= 5: del potential_aunts_2[key] elif values.get('trees') is not None and values.get("trees") <= 3: del potential_aunts_2[key] elif values.get("cars") not in [2, None]: del potential_aunts_2[key] elif values.get("perfumes") not in [1, None]: del potential_aunts_2[key] return potential_aunts_2 if __name__ == "__main__": all_the_aunts = parse_input.input_per_line('../input.txt') aunt_sue_dictionary = create_aunt_sue_dictionary(all_the_aunts) print( f"The Aunt Sue who sent the present is {find_the_aunt(aunt_sue_dictionary)}" )
def test_input_per_line_alpha(): entries = parse_input.input_per_line("alpha_per_line_input.txt") assert entries[0] == "asdfasdf" assert entries[1] == "woeruwoer" assert entries[2] == "asdfasdf" assert entries[3] == "rufndnd dasdf"
def test_input_per_line_alpha_numeric_symbols(): entries = parse_input.input_per_line( "alpha_numeric_symbols_per_line_input.txt") assert entries[0] == "dh#$liu\][asd" assert entries[1] == "lkhlh!@#*(&^@$%)<>?/\\"
import re import sys sys.path.insert(0, '../../input_parsing') import parse_input def rule_one(string_to_eval): """Test if a string contains a pair of letters that appear at least twice, but don't overlap.""" letter_pair = re.compile(r'(\w\w)\w*\1') return bool(re.findall(letter_pair, string_to_eval)) def rule_two(string_to_eval): """Test if a letter is repeated with exactly one letter between them.""" regex = re.compile(r'(\w).\1') return bool(re.search(regex, string_to_eval)) def naughty_or_nice(string_to_eval): """Evaluate a string against all three rules.""" return rule_one(string_to_eval) and rule_two(string_to_eval) if __name__ == "__main__": naughty_nice_list = parse_input.input_per_line('../input.txt') nice_entries = [1 for entry in naughty_nice_list if naughty_or_nice(entry)] print(f"There are {sum(nice_entries)} nice strings in the list.")
""" match = re.finditer(string_to_replace, molecule) return [ molecule[0:m.start()] + replace_with_string + molecule[m.end():] for m in match ] def generate_molecule_tuple(list_of_molecules: list): regex = re.compile(r'(\w+) => (\w+)') molecule_tuple_list = [] for item in list_of_molecules: molecules = re.findall(regex, item) molecule_tuple_list.append((molecules[0][0], molecules[0][1])) return molecule_tuple_list if __name__ == "__main__": rudy_medicine_molecules = parse_input.input_per_line('../input.txt') molecule_to_change = rudy_medicine_molecules.pop() # one more pop for the newline between the list of molecules and the one to change rudy_medicine_molecules.pop() molecule_tuples = generate_molecule_tuple(rudy_medicine_molecules) distinct_molecules = set() for item in molecule_tuples: list_of_potential_replacements = generate_replacements( item[0], item[1], molecule_to_change) for potential_replacement in list_of_potential_replacements: distinct_molecules.add(potential_replacement) print(f"We have {len(distinct_molecules)} distinct molecules.")
else: flown_distance += speed * remaining_time remaining_time = 0 if remaining_time >= resting_time: remaining_time -= resting_time else: remaining_time = 0 return flown_distance def figure_out_reindeer_specs(line): regex = re.compile( r'(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.' ) results = re.findall(regex, line) reindeer_name, speed, fly_time, rest_time = results[0][0], results[0][ 1], results[0][2], results[0][3] return reindeer_name, int(speed), int(fly_time), int(rest_time) if __name__ == "__main__": reindeer_list = parse_input.input_per_line('../input.txt') top_distance = 0 for reindeer in reindeer_list: reindeer_name, speed, fly_time, rest_time = figure_out_reindeer_specs( reindeer) distance_flown = reindeer_distance(speed, fly_time, rest_time, 2503) if distance_flown > top_distance: top_distance = distance_flown print(f"The top-flying reindeer flew {top_distance} km.")
] def count_calories(teaspoon_list, ingredient_list): return sum(teaspoon_list[x] * int(ingredient_list[x][-1]) for x in range(len(ingredient_list))) def brute_force_cookie_score(ingredient_list): ingredient_combos = [ element for element in permutations(range(1, 100), len(ingredient_list)) if sum(element) == 100 ] score = 0 for ingredient_combination in ingredient_combos: combo_score = ingredient_score(ingredient_combination, ingredient_list) calorie_score = count_calories(ingredient_combination, ingredient_list) if combo_score > score and calorie_score == 500: score = combo_score return score if __name__ == "__main__": cookie_list = parse_input.input_per_line('../input.txt') ingredients = parse_ingredients(cookie_list) cookie_score = brute_force_cookie_score(ingredients) print(f"The cookie score is {cookie_score}") # 19150560 is too low
operand_left = find_value_on_line(equation[0]) if equation[2].isnumeric(): operand_right = int(equation[2]) else: operand_right = find_value_on_line(equation[2]) operation = equation[1] if operation == "AND": return operand_left & operand_right elif operation == "LSHIFT": return operand_left << operand_right elif operation == "OR": return operand_left | operand_right elif operation == "RSHIFT": return operand_left >> operand_right elif len(equation) == 2: return find_value_on_line(equation[1]) ^ 65535 else: return find_value_on_line(equation[0]) if __name__ == "__main__": print(f"Starting at {datetime.now().strftime('%d-%b-%Y %H:%M:%S')}") bobby_instructions = parse_input.input_per_line('../input.txt') all_wires = create_dictionary(bobby_instructions) all_wires['b'] = "956" wire_a = find_value_on_line('a') print(f"The value on wire a is {wire_a}") print(f"Ended at {datetime.now().strftime('%d-%b-%Y %H:%M:%S')}") # the answer is not -7074 # 58462 is too high
regex = re.compile(r'(\\\\)|(\\["])|(\\x[0-9a-f]{2})') regex_backspace = re.compile(r'(\\\\)|(\\["])') regex_unicode = re.compile(r'\\x[0-9a-f]{2}') regex_matches = re.findall(regex, line) backspace_count = 0 unicode_count = 0 for match in regex_matches: for item in match: if re.match(regex_unicode, item): unicode_count += 1 elif re.match(regex_backspace, item): backspace_count += 1 unicode_count *= 3 subtraction_count += backspace_count + unicode_count return line_length - subtraction_count if __name__ == "__main__": santa_list = parse_input.input_per_line('../input.txt') answer = sum([ string_code_length(line) - in_memory_strings(line) for line in santa_list ]) print(f"The answer is: {answer}") # 1373 is too high # 1364 is too high # 1338 is too low # 1332 is too low # 1345 isn't the answer either
return 1 else: return 0 if not alive and live_neighbors == 3: return 1 else: return 0 def play_round(grid_size: int, board: dict): """Figure out the new state of the board and return that.""" new_board: dict = {} for x in range(grid_size): for y in range(grid_size): new_board[(x, y)] = new_status((x, y), board) # make sure the corner lights are stuck on. new_board[(0, 0)] = 1 new_board[(0, 99)] = 1 new_board[(99, 0)] = 1 new_board[(99, 99)] = 1 return new_board if __name__ == "__main__": day_18_input = parse_input.input_per_line('../input.txt') initial_board = initialize_board(day_18_input) board = deepcopy(initial_board) for number in range(100): board = play_round(100, board) print(f"There are {sum(board.values())} lights on.")
from sys import path from itertools import combinations path.insert(0, '../../input_parsing') import parse_input container_sizes = parse_input.input_per_line('../input.txt') container_sizes = [int(x) for x in container_sizes] all_ways = [ element for size in range(1, len(container_sizes)) for element in combinations(container_sizes, size) if sum(element) == 150 ] minimum_number_of_containers = 999999999999 for combination in all_ways: if len(combination) < minimum_number_of_containers: minimum_number_of_containers = len(combination) all_ways = [ combination for combination in all_ways if len(combination) == minimum_number_of_containers ] print(f"The number of combinations for using my containers is {len(all_ways)}")
import sys sys.path.insert(0, '../../input_parsing') import parse_input def parse_floor_directions(instructions: str) -> int: """Take a series of parenthesis and figure out what floor that leaves Santa at.""" floor = 0 for parenthesis in instructions: if parenthesis == "(": floor += 1 elif parenthesis == ")": floor -= 1 return floor if __name__ == "__main__": floor_directions = parse_input.input_per_line('../input.txt') print(parse_floor_directions(floor_directions[0]))
reindeer) reindeer_list.append(Reindeer(speed, fly_time, rest_time)) return reindeer_list def move_and_assign_points(list_of_reindeer, total_seconds): time = 0 while time < total_seconds + 1: for reindeer in list_of_reindeer: reindeer.move() list_of_reindeer = sorted(list_of_reindeer) current_top_distance = list_of_reindeer[-1].total_distance for reindeer in list_of_reindeer: if reindeer.total_distance == current_top_distance: reindeer.points += 1 time += 1 if __name__ == "__main__": reindeer_attributes = parse_input.input_per_line('../input.txt') all_reindeer = create_reindeer_list(reindeer_attributes) move_and_assign_points(all_reindeer, 2503) highest_points = 0 for reindeer in all_reindeer: if reindeer.points > highest_points: highest_points = reindeer.points print(f"The highest-scoring reindeer got {highest_points} points.") # 1355 is too high # 1251 is too low