def scrmabled_strings(dictionary, input): """do the scrmabled strings search""" validate_inputs(dictionary, input) dict_words = parse_dict_file("dict.txt") length_grouped_word_maps = get_dict_maps(dict_words) dict_total = len(dict_words) input_lines = read_input("input.txt") found_words = set() # print the searching words logger.debug(f"Search: {dict_words}") for line in input_lines: # create cursor for each length channel of dict word, all start from 0 dict_cursor = dict.fromkeys(length_grouped_word_maps.keys(), 0) while dict_cursor: for word_len in length_grouped_word_maps.keys(): if word_len not in dict_cursor: # this length of word already finished continue slice = slice_str(line, dict_cursor[word_len], word_len) if not slice: # is search ended, pop this len from cursor dict_cursor.pop(word_len) continue slice_byte_map = get_byte_map(slice) for word in list(length_grouped_word_maps[word_len].keys()): word_map = length_grouped_word_maps[word_len][word] if check_scrambled_form(word, word_map, slice, slice_byte_map): # found, pop it from target dict logger.debug(f'Pop "{word}" as match with "{slice}"') length_grouped_word_maps[word_len].pop(word) found_words.add(word) dict_cursor[word_len] += 1 dict_rest = sum([len(x) for x in length_grouped_word_maps.values()]) # print the searching result logger.debug(f"Words found: {found_words}") logger.debug(f"Words not found: {dict_words-found_words}") return dict_total - dict_rest
22 13 17 11 0 8 2 23 4 24 21 9 14 16 7 6 10 3 18 5 1 12 20 15 19 3 15 0 2 22 9 18 13 17 5 19 8 7 25 23 20 11 10 24 4 14 21 16 12 6 14 21 17 24 4 10 16 15 9 19 18 8 23 26 20 22 11 13 6 5 2 0 12 3 7 ''' test_calls, test_boards = parse_raw_input(test_raw_input) assert find_winning_board(test_calls, test_boards).score() == 4512 assert find_losing_board(test_calls, test_boards).score() == 1924 ### THE REAL THING raw_input = read_input(4) calls, boards = parse_raw_input(raw_input) winning_board = find_winning_board(calls, boards) losing_board = find_losing_board(calls, boards) print(f"Part 1: {winning_board.score()}") print(f"Part 2: {losing_board.score()}")
#removing duplicate points pts = list(set(points)) P0 = min(pts, key=lambda p: (p[1], p[0])) H = [P0] # Since 'for loops' works as generators, 'H' is gonna be # populated within the loop and 'h' will always be # the most recent added. In the last iteration, 'H' won't # be updated (case when P0 is reached again) # and the 'for loop' ends. for h in H: a = h for b in pts: if ccw(h, a, b) < 0 or (ccw(h, a, b) == 0 and \ distance(h, b) > distance(h, a)): a = b if a is not P0: H.append(a) assert is_convex(H) return H if __name__ == '__main__': pts = read_input() import timeit print timeit.timeit(lambda : jarvis(pts), number=1) print jarvis(pts)
# display(cw_rotated, 'CW Rotation') # display(ccw_rotated, 'CCW Rotation') linked_id_array, oriented_tiles = find_tile_neighbors_and_orientations( image_tiles, 3079) assert get_corner_id_product(linked_id_array) == 20899048083289 stitched_image = image_tiles_to_image(linked_id_array, oriented_tiles) # display(stitched_image) template_matches = count_template_matches(stitched_image, sea_monster_template) assert template_matches == 2 rough_water_in_image = count_pixels_w_value( stitched_image, '#') - template_matches * count_pixels_w_value(sea_monster_template, '#') assert rough_water_in_image == 273 ### THE REAL THING #################################################### data = helper.read_input(20) image_tiles = parse_image_tiles(data) linked_id_array, oriented_tiles = find_tile_neighbors_and_orientations( image_tiles) print('Part 1:', get_corner_id_product(linked_id_array)) stitched_image = image_tiles_to_image(linked_id_array, oriented_tiles) template_matches = count_template_matches(stitched_image, sea_monster_template) rough_water_in_image = count_pixels_w_value( stitched_image, '#') - template_matches * count_pixels_w_value(sea_monster_template, '#') print('Part 2:', rough_water_in_image)
def test_read_input(self): line = read_input("input.txt") self.assertTrue(isinstance(line, list)) self.assertTrue(line[0].startswith("aa")) self.assertTrue("\n" not in line[0])
-6,-4,-5 0,7,-8'''.split('\n\n') rotations = make_rotations() other_orientations = [ScannerMap.from_str(sm) for sm in other_scanner_maps] rotated_test_scan_maps = [test_scanner.rotate(r) for r in rotations] num_found = 0 for oo in other_orientations: for rtsm in rotated_test_scan_maps: matches = sum(1 for oob, rtsmb in zip(oo.beacons, rtsm.beacons) if oob == rtsmb) if matches == len(test_scanner.beacons): num_found += 1 break assert num_found == 4 t = Vector(1, 1, 1) translated_test_scanner = test_scanner.translate(t) assert translated_test_scanner.beacons[0] == Vector(0, 0, 2) assert translated_test_scanner.beacons[-1] == Vector(9, 1, 8) test_full_map = register_maps(test_reports) assert len(test_full_map.beacons) == 79 ### THE REAL THING puzzle_input = helper.read_input() scan_maps = puzzle_input.split('\n\n') full_map = register_maps(scan_maps) print(f'Part 1: {len(full_map.beacons)}') print(f'Part 2: {""}')
import math from helper import read_input def count_trees(lines, right, down=1): counter = 0 n = len(lines[0]) for i, line in enumerate(lines[::down]): if line[right * i % n] == '#': counter += 1 return counter if __name__ == '__main__': area = read_input('input.txt') print(count_trees(area, 3)) slopes = [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]] trees = [count_trees(area, right, down) for right, down in slopes] print(math.prod(trees))
for lp in low_points: basin_points = [] find_basin_points(lp, height_map, basin_points) # For some reason I end up with dupes in my list, using set to eliminate # Ideally would fix recursion to avoid dupes but this works basin_sizes.append(len(set(basin_points))) basin_sizes = sorted(basin_sizes, reverse=True) prod = 1 for bs in basin_sizes[:n_largest_basins]: prod *= bs return prod if __name__ == '__main__': ### THE TEST test_height_map = '''2199943210 3987894921 9856789892 8767896789 9899965678 ''' test_height_map = parse_height_map(test_height_map) assert total_low_point_risk_level(test_height_map) == 15 assert get_product_of_largest_basin_sizes(test_height_map) == 1134 ### THE REAL THING height_map = parse_height_map(read_input()) print(f'Part 1: {total_low_point_risk_level(height_map)}') print(f'Part 2: {get_product_of_largest_basin_sizes(height_map)}')
========== Original file size: %s bytes Minified file size: %s bytes Removed: %s%% bytes """ % (input_size, output_size, removed) if __name__ == "__main__": if len(sys.argv) > 1: try: filename = sys.argv[1] if os.path.getsize(filename) == 0: print "C'mon, don't bug me! Empty file?!" exit(-1) input = read_input(filename) output = minifyme(input) output_filename = "%s.min.js" % sys.argv[1][:-3] write_output(output_filename, output) print_statistics(input, output) print "File %s written." % output_filename except Exception, e: print "Something wrong." print e else: print "Usage: minifyme file.js"
packets = parse_packet(test_packet)[0][0] assert packets['version'] == 6 and packets['type'] == 4 and packets['contents'][0] == 2021 test_packet = '38006F45291200' test_packet = convert_hex_to_bin_packet(test_packet) packets, _ = parse_packet(test_packet) test_packet = convert_hex_to_bin_packet('8A004A801A8002F478') packets, _ = parse_packet(test_packet) assert packets[0]['sum_of_versions'] == 16 test_packet = convert_hex_to_bin_packet('620080001611562C8802118E34') packets, _ = parse_packet(test_packet) assert sum(p['sum_of_versions'] for p in packets) == 12 test_packet = convert_hex_to_bin_packet('C0015000016115A2E0802F182340') packets, _ = parse_packet(test_packet) assert sum(p['sum_of_versions'] for p in packets) == 23 test_packet = convert_hex_to_bin_packet('A0016C880162017C3686B18A3D4780') packets, _ = parse_packet(test_packet) assert sum(p['sum_of_versions'] for p in packets) == 31 test_packet = convert_hex_to_bin_packet('C200B40A82') packets, _ = parse_packet(test_packet) result = evaluate_packets(packets[0]) assert result == 3 ### THE REAL THING puzzle_input = helper.read_input().strip() bin_packet = convert_hex_to_bin_packet(puzzle_input) packets, _ = parse_packet(bin_packet) print(f'Part 1: {sum(p["sum_of_versions"] for p in packets)}') packet_eval = evaluate_packets(packets[0]) print(f'Part 2: {packet_eval}')
Player 2: 5 8 4 7 10 ''' decks = parse_decks(sample_input) assert combat(decks, verbose=False)[1] == 306 _, score = combat(decks, recursive=True, verbose=False) assert score == 291 sample_input = '''Player 1: 43 19 Player 2: 2 29 14 ''' decks = parse_decks(sample_input) # _, score = combat(decks, verbose=True, recursive=True) ### THE REAL THING ############################ real_input = helper.read_input(22) decks = parse_decks(real_input) print("Part 1:", combat(decks)[1]) print("Part 2:", combat(decks, recursive=True)[1])
baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaaaabbaaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa babaaabbbaaabaababbaabababaaab aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba ''' rules, msgs = parse_input(sample_input) rule_0_match_count = count_matching_messages(msgs, rules, 0) assert rule_0_match_count == 3 assert part2(msgs, rules) == 12 # rules[8] = [[42], [42, 8]] # rules[11] = [[42, 31], [42, 11, 31]] # rule42 = resolve_rule(rules, 42) # rule31 = resolve_rule(rules, 31) # rule_0_match_count = count_matching_messages(msgs, rules, 0) # assert rule_0_match_count == 12 ### THE REAL THING ############################################ actual_input = helper.read_input(19) rules, msgs = parse_input(actual_input) rule_0_match_count = count_matching_messages(msgs, rules, 0) print("Part 1:", rule_0_match_count) print("Part 2:", part2(msgs, rules))
def count_unanimous_qs(group_decs: List[group_declaration]) -> int: return sum(1 for group in group_decs for q in group.declarations if len(group.declarations[q]) == group.size) sample_declaration_batch = '''abc a b c ab ac a a a a b''' sample_declarations = parse_declaration_batch(sample_declaration_batch) assert count_qs(sample_declarations) == 11 assert count_unanimous_qs(sample_declarations) == 6 declarations_batch = helper.read_input(6) declarations = parse_declaration_batch(declarations_batch) print("Part 1:", count_qs(declarations)) print("Part 2:", count_unanimous_qs(declarations))
from helper import read_input def read_pwd_line(line): """Read a line of format '<num>-<num> <char>: <string>' and returns a tuple (int(num), int(num), char, string)""" result = re.split(r' |-|: ', line) first_num, second_num, *result = result return int(first_num), int(second_num), *result def check_sled_pwd_policy(min_limit, max_limit, char, pwd): return min_limit <= pwd.count(char) <= max_limit def check_toboggal_pwd_policy(first_index, second_index, char, pwd): return operator.xor(pwd[first_index - 1] == char, pwd[second_index - 1] == char) def count_valid_pwds(lines, company): if company == 'sled': valid_pwds = (check_sled_pwd_policy(*read_pwd_line(line)) for line in lines) else: valid_pwds = (check_toboggal_pwd_policy(*read_pwd_line(line)) for line in lines) return sum(valid_pwds) if __name__ == '__main__': print(count_valid_pwds(read_input('input.txt'), 'sled')) print(count_valid_pwds(read_input('input.txt'), 'toboggal'))
""" Use it like: python andrew.py < inputs/brazil.in """ from helper import ccw, read_input, is_convex, interior_elimination def half_hull(pts): h = [] for p in pts: while len(h) >= 2 and ccw(h[-2], h[-1], p) <= 0: h.pop() h.append(p) return h def andrew(points, cutoff=False): if cutoff: points = interior_elimination(points) pts = sorted(set(points)) H = half_hull(pts)[:-1] + \ half_hull(reversed(pts))[:-1] assert is_convex(H) return H if __name__ == '__main__': pts = read_input() import timeit print timeit.timeit(lambda : andrew(pts), number=1) print andrew(pts)
sample_valid_passports = '''pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f eyr:2029 ecl:blu cid:129 byr:1989 iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm hcl:#888785 hgt:164cm byr:2001 iyr:2015 cid:88 pid:545766238 ecl:hzl eyr:2022 iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719''' passports = parse_batch(sample_valid_passports) assert len([ p for p in passports if p.check_passport(optional_fields='cid', validate=True) ]) == 4 ###### THE REAL THING ####################################################### batch = helper.read_input(4) passports = parse_batch(batch) print("Part 1:", len([p for p in passports if p.check_passport(optional_fields='cid')])) print( "Part 2:", len([ p for p in passports if p.check_passport(optional_fields='cid', validate=True) ]))
for slope in slopes: prod *= tree_map.count_trees_on_path(*slope) return prod sample_pattern = '''..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#''' tree_map = TreeMap(sample_pattern) assert not tree_map.check_for_tree(1, 3) assert tree_map.check_for_tree(2, 6) assert tree_map.check_for_tree(7, 21) assert tree_map.count_trees_on_path(1, 3) == 7 assert check_paths(tree_map) == 336 tree_pattern = helper.read_input(3) tree_map = TreeMap(tree_pattern) print('Part 1:', tree_map.count_trees_on_path(1, 3)) print('Part 2:', check_paths(tree_map))
def add_numbers(obj, ignore_red=False): sum_of_numbers = 0 if ignore_red and isinstance(obj, dict) and 'red' in obj.values(): return 0 for entry in obj: if isinstance(entry, list) or isinstance(entry, dict): sum_of_numbers += add_numbers(entry, ignore_red) elif isinstance(obj, dict) and (isinstance(obj[entry], list) or isinstance(obj[entry], dict)): sum_of_numbers += add_numbers(obj[entry], ignore_red) elif (isinstance(obj, dict) and not isinstance(obj[entry], str)): sum_of_numbers += obj[entry] elif not isinstance(entry, str): sum_of_numbers += entry return sum_of_numbers test = json.loads('[1,{"c":"red","b":2},3]') assert add_numbers(test) == 6 assert add_numbers(test, True) == 4 puzzle_input = json.loads(helper.read_input(12)) print("Part 1:", add_numbers(puzzle_input)) print("Part 2:", add_numbers(puzzle_input, True))
def test_read_input(self, m_open): result = read_input('/dummy/filename') m_open.assert_called_once_with('/dummy/filename') self.assertListEqual(['1', '2', '3'], result)
check_char_2 = pw[max_n - 1] if (check_char_1 == req_letter or check_char_2 == req_letter ) and not (check_char_1 == req_letter and check_char_2 == req_letter): return True return False def count_valid_passwords(pw_db, check_fn=is_pw_valid_sled): return sum(int(check_fn(db_record)) for db_record in pw_db) # Tests sample_db = '''1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc''' assert count_valid_passwords(parse_password_db(sample_db)) == 2 assert count_valid_passwords(parse_password_db(sample_db), is_pw_valid_toboggan) == 1 # The real thing raw_pw_db = helper.read_input(2) pw_db = parse_password_db(raw_pw_db) print('Part 1:', count_valid_passwords(pw_db)) print('Part 2:', count_valid_passwords(pw_db, is_pw_valid_toboggan))
return [int(val) for val in expense_report.split('\n') if val.strip()] def expense_report_checker(line_items, n_items=2, target_value=2020): for items in combinations(line_items, n_items): if sum(items) == target_value: prod = 1 for item in items: prod *= item return prod return -1 sample_input = '''1721 979 366 299 675 1456''' expense_report = parse_expense_report(sample_input) assert expense_report_checker(expense_report) == 514579 assert expense_report_checker(expense_report, 3) == 241861950 expense_report = parse_expense_report(helper.read_input(1)) print("First solution", expense_report_checker(expense_report)) print("Second solution", expense_report_checker(expense_report, 3))
def get_expenses_report(filename='input.txt'): report = read_input(filename) report = [int(expense) for expense in report] return report
def windowed_sum(sonar_report: List[int], window_length: int = 3) -> List[int]: windowed_report = [] for i in range(len(sonar_report) - window_length + 1): windowed_report.append(sum(sonar_report[i:(i + window_length)])) return windowed_report sample_sonar_report = """199 200 208 210 200 207 240 269 260 263""" sample_sonar_report = parse_raw_sonar_report(sample_sonar_report) assert count_depth_increases(sample_sonar_report) == 7 windowed_sample_sonar_report = windowed_sum(sample_sonar_report) assert count_depth_increases(windowed_sample_sonar_report) == 5 raw_sonar_report = helper.read_input(1) sonar_report = parse_raw_sonar_report(raw_sonar_report) depth_increase_count = count_depth_increases(sonar_report) windowed_sonar_report = windowed_sum(sonar_report) windowed_depth_increase_count = count_depth_increases(windowed_sonar_report) print(f"Part 1: {depth_increase_count}") print(f"Part 2: {windowed_depth_increase_count}")
def scalable_simulation(fish: List[int], days: int) -> int: fish_tracker = make_fish_tracker() for timer in fish: fish_tracker[timer] += 1 for d in range(days): next_fish_tracker = make_fish_tracker() for timer in range(new_fish_spawn_timer): next_fish_tracker[timer] = fish_tracker[timer + 1] next_fish_tracker[new_fish_spawn_timer] = fish_tracker[0] next_fish_tracker[spawn_timer] += fish_tracker[0] fish_tracker = next_fish_tracker.copy() return sum(fish_tracker[timer] for timer in fish_tracker) if __name__ == '__main__': ### TESTS test_fish = parse_fish('3,4,3,1,2') assert len(naive_simulation(test_fish, 18)) == 26 assert len(naive_simulation(test_fish, 80)) == 5934 assert scalable_simulation(test_fish, 18) == 26 assert scalable_simulation(test_fish, 80) == 5934 ### THE REAL THING fish = parse_fish(read_input(6)) print(f'Part 1: {len(naive_simulation(fish, 80))}') print(f'Part 2: {scalable_simulation(fish, 256)}')
assert sample_rules['class'] == [(1, 3), (5, 7)] assert len(sample_tix) == 4 assert sample_tix[0] == [7, 3, 47] and sample_tix[-1] == [38, 6, 12] assert validate_tickets(sample_rules, sample_tix)[0] == 71 assert validate_tickets(sample_rules, sample_tix)[1] == [[7, 3, 47]] sample_ticket_data = '''class: 0-1 or 4-19 row: 0-5 or 8-19 seat: 0-13 or 16-19 your ticket: 11,12,13 nearby tickets: 3,9,18 15,1,5 5,14,9 ''' sample_rules, sample_my_tix, sample_tix = parse_ticket_data(sample_ticket_data) _, sample_valid_tix = validate_tickets(sample_rules, sample_tix) field_order = find_field_order(sample_rules, sample_valid_tix) assert field_order == ['row', 'class', 'seat'] ticket_data = helper.read_input(16) rules, my_ticket, tix = parse_ticket_data(ticket_data) sample_error_rate, valid_tickets = validate_tickets(rules, tix) print('Part 1:', sample_error_rate) field_order = find_field_order(rules, valid_tickets) print('Part 2:', product_of_fields(field_order, my_ticket))
return last_position, last_fuel else: # Keep going down hill last_position, last_fuel = next_position, next_fuel steps += 1 ### TEST test_crab_positions = parse_fish('16,1,2,0,4,2,7,1,2,14') test_position, test_cost = optimize_position(test_crab_positions, constant_fuel_cost) assert test_position == 2 assert test_cost == 37 t0 = time() test_position, test_cost = optimizer2(test_crab_positions, growing_fuel_cost) print(time() - t0) t0 = time() test_position, test_cost = optimize_position(test_crab_positions, growing_fuel_cost) print(time() - t0) assert test_position == 5 assert test_cost == 168 ### THE REAL THING crab_positions = parse_fish(read_input(7)) print(f'Part 1: {optimizer2(crab_positions, constant_fuel_cost)[1]}') print(f'Part 2: {optimizer2(crab_positions, growing_fuel_cost)[1]}')