diff --git "a/aoc.csv" "b/aoc.csv" --- "a/aoc.csv" +++ "b/aoc.csv" @@ -1,4 +1,4 @@ -year,day,part,question,answer,solution,language +year,day,part,question,answer,solution,language 2024,2,1,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. @@ -67,7 +67,7 @@ if __name__ == ""__main__"": safe += 1 print(safe) -",python:3.9 +",python:3.9 2024,2,1,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. @@ -137,7 +137,7 @@ def solve(input): solve(input_path) -",python:3.9 +",python:3.9 2024,2,1,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. @@ -172,7 +172,7 @@ So, in this example, 2 reports are safe. Analyze the unusual data from the engineers. How many reports are safe?",341,"l = [list(map(int,x.split())) for x in open(""i.txt"")] -print(sum(any(all(d 0: safe+=1 -print (safe)",python:3.9 +print (safe)",python:3.9 2024,2,2,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. @@ -576,7 +576,7 @@ def solve(input_path: str): solve(input_path) -",python:3.9 +",python:3.9 2024,2,2,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. @@ -662,7 +662,7 @@ with open('input.txt', 'r') as file: break print(count) -",python:3.9 +",python:3.9 2024,2,2,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. @@ -755,7 +755,7 @@ with open('02.input', 'r') as file: valid_count += 1 print(f""Number of valid sequences: {valid_count}"") -",python:3.9 +",python:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -825,7 +825,7 @@ if __name__ == ""__main__"": for i in range(len(left)): sumDist += left[i] - right[i] if left[i] > right[i] else right[i] - left[i] print(sumDist) -",python:3.9 +",python:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -889,7 +889,7 @@ def main(): a, b = read_input_file('input2.txt') print(find_min_diff(a, b)) -main()",python:3.9 +main()",python:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -948,7 +948,7 @@ for i in range(len(left_list)): print(f""The total distance between the lists is {distance}"") -",python:3.9 +",python:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -1022,7 +1022,7 @@ if __name__ == ""__main__"": pairs = read_input(input_file) result = calculate_sum_of_differences(pairs) print(result) -",python:3.9 +",python:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -1090,7 +1090,7 @@ for i in range(len(liste_paires)): print(total) #the answer was 3508942 -",python:3.9 +",python:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -1194,7 +1194,7 @@ if __name__ == '__main__': left, right = build_lists(contents) score = calculate_similarity_score(left, right) print(score) -",python:3.9 +",python:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -1277,7 +1277,7 @@ total = 0 for i in range(len(leftNums)): total += leftNums[i] * rightNums.count(leftNums[i]) -print(f""total: {total}"")",python:3.9 +print(f""total: {total}"")",python:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -1369,7 +1369,7 @@ for num in list1: similarityScore += num * list2Count[num] print(similarityScore) -",python:3.9 +",python:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -1462,7 +1462,7 @@ for x in a: ans += x * counts[x] print(ans) -",python:3.9 +",python:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. @@ -1553,7 +1553,7 @@ for i in range(len(list1)): if num2 > num1: break total+= (num1*simscore) -print(total)",python:3.9 +print(total)",python:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1604,7 +1604,7 @@ def part2(): sum += runOps(op) print(sum) -part1()",python:3.9 +part1()",python:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1636,7 +1636,7 @@ mul_results = [int(instruction[0]) * int(instruction[1]) for instruction in mul_ mul_total = sum(mul_results) print(""Sum of all multiplications:"", mul_total) -",python:3.9 +",python:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1677,7 +1677,7 @@ def main(): print(""max"", max) main() -",python:3.9 +",python:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1704,7 +1704,7 @@ with open('input.txt', 'r') as file: sum = 0 for match in matches: sum += eval(match.replace(""mul("", """").replace("")"", """").replace("","", ""*"")) - print(sum)",python:3.9 + print(sum)",python:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1741,7 +1741,7 @@ for match in matches: print(result) -",python:3.9 +",python:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1804,7 +1804,7 @@ for row in data: sum += int(mul.group(1)) * int(mul.group(2)) * current print(sum) -",python:3.9 +",python:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1857,7 +1857,7 @@ for res in findall(r""mul\((\d+),(\d+)\)|(don't\(\))|(do\(\))"", input_text): elif (not do) and res[3]: do = True print(total) -",python:3.9 +",python:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1921,7 +1921,7 @@ def main(): print(f""total: {total}"") if __name__ == ""__main__"": - main()",python:3.9 + main()",python:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -1986,7 +1986,7 @@ with open('input.txt', 'r') as f: res += reduce(lambda x, y: int(x) * int(y), nums) print(res) -",python:3.9 +",python:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. @@ -2061,7 +2061,7 @@ with open('input.txt', 'r') as file: if largest_do >= largest_dont: sum += eval(match.group().replace(""mul("", """").replace("")"", """").replace("","", ""*"")) - print(sum)",python:3.9 + print(sum)",python:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -2138,7 +2138,7 @@ with open(""04_input.txt"", ""r"") as f: width = len(words[0]) height = len(words) -main()",python:3.9 +main()",python:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -2231,7 +2231,7 @@ def main(): pprint.pprint(result) if __name__ == ""__main__"": - main()",python:3.9 + main()",python:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -2305,7 +2305,7 @@ for i in range(n): ans += has_xmas(i, j, d) print(ans) -",python:3.9 +",python:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -2423,7 +2423,7 @@ if __name__ == ""__main__"": p_2_solution = int(solve_part_2(quiz_input)) end = time.time() print(f""Part 2: {p_2_solution} (took {(end - middle) * 1000:.3f}ms)"") -",python:3.9 +",python:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -2503,7 +2503,7 @@ for idx_diff in range(-num_cols + 1, num_rows): total += len(findall(r""XMAS"", diagonal)) total += len(findall(r""XMAS"", diagonal[::-1])) print(total) -",python:3.9 +",python:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -2610,7 +2610,7 @@ def count_word_for_pos(matrix: list[list], pos: tuple[int, int], word: str) -> i return count if __name__ == ""__main__"": - main()",python:3.9 + main()",python:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -2754,7 +2754,7 @@ def part2(): total = find_x_mas(input) print(total) -part2()",python:3.9 +part2()",python:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -2957,7 +2957,7 @@ if __name__ == ""__main__"": main() # ----------------------------------------------------------------------------- -",python:3.9 +",python:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -3049,7 +3049,7 @@ for grid in grids_3x3: print(count) -",python:3.9 +",python:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! @@ -3154,7 +3154,7 @@ for x in range(len(cont)): t += check(matrix) print(t) -",python:3.9 +",python:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -3273,7 +3273,7 @@ def correct_order(page_update): if __name__ == ""__main__"": main() -",python:3.9 +",python:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -3432,7 +3432,7 @@ for update in correct_updates: print(f""Tally: {tally}"") total = sum(tally) print(f""Result: {total}"") -",python:3.9 +",python:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -3564,7 +3564,7 @@ for x in lists: #Make a list of the middle numbers midNums = [int(x[len(x)//2]) for x in result] -print(sum(midNums))",python:3.9 +print(sum(midNums))",python:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -3790,7 +3790,7 @@ if __name__ == ""__main__"": main() # ----------------------------------------------------------------------------- -",python:3.9 +",python:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -3907,7 +3907,7 @@ with open(""input.txt"", ""r"") as f: # print(f""Update: {update}"") if checkValid(beforeDict, update): total += update[len(update) // 2] - print(total)",python:3.9 + print(total)",python:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -4058,7 +4058,7 @@ for update in updates: ans += seq[len(seq) // 2] print(ans) -",python:3.9 +",python:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -4185,7 +4185,7 @@ with open(""05_input.txt"", ""r"") as f: break print(result) -",python:3.9 +",python:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -4331,7 +4331,7 @@ for update in updates: total += update[len(update)//2] print(total) -",python:3.9 +",python:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -4478,7 +4478,7 @@ for update in updates: print(total) -",python:3.9 +",python:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. @@ -4619,7 +4619,7 @@ for update in updates: middle = fixed[len(fixed)//2] total += middle -print(total)",python:3.9 +print(total)",python:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -4755,7 +4755,7 @@ if __name__ == ""__main__"": grid = [] for line in f: grid.append(line.strip()) - print(""Number of unique positions: "" + str(get_unique_positions(grid)))",python:3.9 + print(""Number of unique positions: "" + str(get_unique_positions(grid)))",python:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -4884,7 +4884,7 @@ def main(): def turn_right(x: int) -> int: return (x + 1) % 4 -main()",python:3.9 +main()",python:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -5026,7 +5026,7 @@ print(len(visited)) - ",python:3.9 + ",python:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -5178,7 +5178,7 @@ with open(""input.txt"", ""r"") as f: pos = next print(len(visited)) -",python:3.9 +",python:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -5310,7 +5310,7 @@ while True: cord = (newx,newy) -print(len(visited))",python:3.9 +print(len(visited))",python:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -5557,7 +5557,7 @@ result = len(valid_positions) execution_time = time.time() - start_time print(result) -print(f""Time: {execution_time:.3f} seconds"")",python:3.9 +print(f""Time: {execution_time:.3f} seconds"")",python:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -5909,7 +5909,7 @@ for i, obs in enumerate(possible_obstacles): cont += 1 print(cont) -",python:3.9 +",python:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -6149,7 +6149,7 @@ if __name__ == ""__main__"": grid = [] for line in f: grid.append(line.strip()) - print(""Number of possible obstacles: "" + str(get_possible_obstacles(grid)))",python:3.9 + print(""Number of possible obstacles: "" + str(get_possible_obstacles(grid)))",python:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -6397,7 +6397,7 @@ def main(): if __name__ == ""__main__"": main() -",python:3.9 +",python:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. @@ -6647,7 +6647,7 @@ print(loop_ct) - ",python:3.9 + ",python:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -6731,7 +6731,7 @@ class Solution: solution = Solution() print(solution.calibration_result()) -",python:3.9 +",python:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -6796,7 +6796,7 @@ for res,nums in data: p1 += gen(nums) -print(p1)",python:3.9 +print(p1)",python:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -6846,7 +6846,7 @@ def find_solution(answer, terms): or find_solution(answer, [terms[0]*terms[1]]+terms[2:]) main() -",python:3.9 +",python:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -6907,7 +6907,7 @@ for line in f: print(total) -",python:3.9 +",python:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -6956,7 +6956,7 @@ for line in lines: if is_valid(test_val, 0, vals): total += test_val -print(total)",python:3.9 +print(total)",python:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -7086,7 +7086,7 @@ if __name__ == ""__main__"": #part1(data) part2(data) -",python:3.9 +",python:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -7173,7 +7173,7 @@ for res, nums in data: p2 += gen(nums) -print(p2)",python:3.9 +print(p2)",python:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -7227,7 +7227,7 @@ from part1 import read_input, sum_valid_expressions if __name__ == ""__main__"": expressions = read_input('input.txt') print( sum_valid_expressions(expressions, ['+', '*', '||'])) -",python:3.9 +",python:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -7331,7 +7331,7 @@ with open(input,'r') as f: total=total+a3 print(f""Total = {total}"") -",python:3.9 +",python:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? @@ -7409,7 +7409,7 @@ for i, line in enumerate(lines): print(ans) -",python:3.9 +",python:3.9 2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7521,7 +7521,7 @@ def main(): print(len(antinodes)) main() -",python:3.9 +",python:3.9 2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7637,7 +7637,7 @@ for freq in all_locs: print(len(antinodes)) -",python:3.9 +",python:3.9 2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7763,7 +7763,7 @@ for key, coordinates in antennas.items(): antinodes.append(node) print(len(antinodes)) -",python:3.9 +",python:3.9 2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7867,7 +7867,7 @@ for frequency in antenna_map: print(f""There's {len(antinodes)} unique locations containing an antinode"") - ",python:3.9 + ",python:3.9 2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8013,7 +8013,7 @@ for frequency in unique_frequencies: print(grid) print(len(grid.antinode_locations)) -",python:3.9 +",python:3.9 2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8175,7 +8175,7 @@ for a in uniq: nodes.add(node_b) print(ans) -",python:3.9 +",python:3.9 2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8368,7 +8368,7 @@ for frequency in unique_frequencies: print(grid) print(len(grid.antinode_locations)) -",python:3.9 +",python:3.9 2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8522,7 +8522,7 @@ for frequencies in dictionary.values(): add_antinodes(frequencies) print(len(anti_nodes)) -",python:3.9 +",python:3.9 2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8714,7 +8714,7 @@ for key in char_to_coord_map.keys(): print(len(antinodes)) # print(antinodes) -",python:3.9 +",python:3.9 2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8882,7 +8882,7 @@ def solve(filename): if __name__ == ""__main__"": res = solve(""i.txt"") print(res) -",python:3.9 +",python:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -8968,7 +8968,7 @@ while file_structure: if buffer: total += int(buffer[0] * buffer[1] * (current_index + (buffer[1] - 1) / 2)) print(total) -",python:3.9 +",python:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -9074,7 +9074,7 @@ def main(): print(f'Result: {checksum(sorted_input)}') if __name__ == ""__main__"": - main()",python:3.9 + main()",python:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -9173,7 +9173,7 @@ dick_map = [int(n) for n in in_date.strip()] disk_blocks = map_to_blocks(dick_map) compress(disk_blocks) print(compute_checksum(disk_blocks)) -",python:3.9 +",python:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -9270,7 +9270,7 @@ def checksum(arr): ans = checksum(move(filesystem)) print(ans) -",python:3.9 +",python:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -9368,7 +9368,7 @@ result = [item for sublist in result for item in sublist] compressed = compressFile(result) # print("""".join(compressed)) print(calculateCheckSum(compressed)) -",python:3.9 +",python:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -9530,7 +9530,7 @@ def main(): print(f'Result: {checksum(list_input)}') if __name__ == ""__main__"": - main()",python:3.9 + main()",python:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -9646,7 +9646,7 @@ def main(): print(checksum(layout)) if __name__ == ""__main__"": - main()",python:3.9 + main()",python:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -9789,7 +9789,7 @@ dick_map = [int(n) for n in in_date.strip()] disk_blocks = map_to_blocks(dick_map) compress_by_files(disk_blocks) print(compute_checksum(disk_blocks)) -",python:3.9 +",python:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -9921,7 +9921,7 @@ compressFile(files, free_space) compacted_file = alternate_join(files, free_space) compacted_file = [item for sublist in compacted_file for item in sublist] # print(''.join(compacted_file)) -print(f""Checksum: {calculateCheckSum(compacted_file)}"")",python:3.9 +print(f""Checksum: {calculateCheckSum(compacted_file)}"")",python:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. @@ -10031,7 +10031,7 @@ for file_id, file_length in file_structure: total += int(file_id * file_length * (idx + (file_length - 1) / 2)) idx += file_length print(total) -",python:3.9 +",python:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -10151,7 +10151,7 @@ grid = None with open(""i.txt"") as f: grid = [[int(x) for x in line.strip()] for line in f] res = solve(grid) -print(res)",python:3.9 +print(res)",python:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -10245,7 +10245,7 @@ for height in range(8, -1, -1): nine_reachable_from = new_nine_reachable_from print(sum(len(starting_points) for starting_points in nine_reachable_from.values())) -",python:3.9 +",python:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -10359,7 +10359,7 @@ for yi in range(ymax): score += Trail(xi, yi).score() print(score) -",python:3.9 +",python:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -10467,7 +10467,7 @@ for start in starts: trailheads += dfs(start, 0, set()) print(trailheads) -",python:3.9 +",python:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -10569,7 +10569,7 @@ for trailHead in TrailHeads: print(f""first trail head score: {calculateTrailHeadScore(TrailHeads[0])}"") print(TrailHeads) print(score) - ",python:3.9 + ",python:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -10727,7 +10727,7 @@ def main(): if __name__ == '__main__': main() -",python:3.9 +",python:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -10881,7 +10881,7 @@ for trailHead in TrailHeads: print(f""first trail head score: {calculateTrailHeadScore(TrailHeads[0])}"") print(TrailHeads) print(score) - ",python:3.9 + ",python:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -11117,7 +11117,7 @@ print(total_score2) end = time.time() print(""~~~~~~~~~~ RUNTIME ~~~~~~~~~~~~~~"") print(round(end - start, 3)) -",python:3.9 +",python:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -11284,7 +11284,7 @@ for row in range(len(trail_map)): answer += bfs(trail_map, (row, col)) print(answer) -",python:3.9 +",python:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. @@ -11452,4 +11452,25099 @@ for y in range(h): # exit(0) print(res) -",python:3.9 +",python:3.9 +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"stones = open('input.txt').read().strip().split(' ') +stones = [int(x) for x in stones] + + + +def get_next_stones(): + for i in range(len(stones)): + if stones[i] == 0: + stones[i] = 1 + elif len(str(stones[i])) % 2 == 0: + num = str(stones[i]) + # print(num) + stones[i] = int(num[:len(num)//2]) + stones.append(int(num[len(num)//2:])) + else: + stones[i] *= 2024 + + +for i in range(25): + # print(stones) + get_next_stones() + + +print(len(stones)) + ",python:3.9.21-slim +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def rules(n): + if n == 0: + return [1] + s = str(n) + if len(s) % 2 == 0: + l = len(s) // 2 + return [int(s[:l]), int(s[l:])] + return [n * 2024] + +def calc(stone, blinks): + if blinks == 0: + return 1 + new = rules(stone) + return sum(calc(num, blinks - 1) for num in new) + +res = 0 +stones = list(map(int, open('i.txt').read().split())) +for stone in stones: + res += calc(stone, 25) +print(res)",python:3.9.21-slim +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def blink(stones): + newStones = [] + for stone in stones: + if stone == 0: + newStones.append(1) + continue + n = len(str(stone)) + if n % 2 == 0: + newStones.append(int(str(stone)[:(n//2)])) + newStones.append(int(str(stone)[(n//2):])) + continue + newStones.append(stone * 2024) + return newStones + +def get_num_stones(stones): + for _ in range(25): + stones = blink(stones) + return len(stones) + +if __name__ == ""__main__"": + # Open file 'day11-1.txt' in read mode + with open('day11-1.txt', 'r') as f: + stones = [] + for line in f: + stones = [int(val) for val in line.strip().split()] + print(""Number of Stones: "" + str(get_num_stones(stones)))",python:3.9.21-slim +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def get_next_array(stones): + res = [] + + for stone in stones: + if stone == 0: + res.append(1) + + elif len(str(stone)) % 2 == 0: + stone_str = str(stone) + res.append(int(stone_str[0:len(stone_str)//2])) + res.append(int(stone_str[len(stone_str)//2:])) + + else: + res.append(stone * 2024) + + return res + + + +with open('input.txt') as f: + stones = [int(s) for s in f.read().split()] + + +for i in range(25): + stones = get_next_array(stones) + +print(len(stones))",python:3.9.21-slim +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"from functools import cache + + +@cache +def blink(value, times): + if times == 0: + return 1 + + if value == 0: + return blink(1, times - 1) + + digits = len(str(value)) + if digits % 2 == 0: + return blink(int(str(value)[:digits // 2]), times - 1) + blink( + int(str(value)[digits // 2:]), times - 1) + + return blink(value * 2024, times - 1) + + +with open(""input.txt"") as file: + stones = file.read().strip().split() + result = sum([blink(int(stone), 25) for stone in stones]) + print(result) +",python:3.9.21-slim +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import cache + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + + +@cache +def stones_created(num, rounds): + if rounds == 0: + return 1 + elif num == 0: + return stones_created(1, rounds - 1) + elif len(str(num)) % 2 == 0: + return stones_created( + int(str(num)[: len(str(num)) // 2]), rounds - 1 + ) + stones_created(int(str(num)[len(str(num)) // 2 :]), rounds - 1) + else: + return stones_created(num * 2024, rounds - 1) + + +nums = [int(x) for x in input_text[0].split()] +print(sum(stones_created(x, 75) for x in nums)) +",python:3.9.21-slim +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import cache + + +@cache +def blink(value, times): + if times == 0: + return 1 + + if value == 0: + return blink(1, times - 1) + + digits = len(str(value)) + if digits % 2 == 0: + return blink(int(str(value)[:digits // 2]), times - 1) + blink( + int(str(value)[digits // 2:]), times - 1) + + return blink(value * 2024, times - 1) + + +with open(""input.txt"") as file: + stones = file.read().strip().split() + result = sum([blink(int(stone), 75) for stone in stones]) + print(result) +",python:3.9.21-slim +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import lru_cache + + +def is_even(num): + count = 0 + a = num + while a: + a //= 10 + count += 1 + return count % 2 == 0 + + +@lru_cache(maxsize=1000_000) +def check_stone(stone): + if stone == 0: + return (1, -1) + if is_even(stone): + s = str(stone) + l = s[: len(s) // 2] + r = s[len(s) // 2 :] + return (int(l), int(r)) + return (stone * 2024, -1) + + +in_date = """" + +with open(""input.txt"") as f: + in_date = f.read() + +init_stones = [int(i) for i in in_date.strip().split()] + +total_nums = {} +for i in init_stones: + res = total_nums.get(i, 0) + 1 + total_nums[i] = res + + +for iter in range(75): + new_total_nums = {} + for n, c in total_nums.items(): + l, r = check_stone(n) + if r != -1: + r_count = new_total_nums.get(r, 0) + new_total_nums[r] = r_count + (1 * c) + l_count = new_total_nums.get(l, 0) + new_total_nums[l] = l_count + (1 * c) + total_nums = new_total_nums + +total = sum(total_nums.values()) +print(total) +",python:3.9.21-slim +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"from collections import defaultdict +import sys + +sys.setrecursionlimit(2**30) + +with open(""./day_11.in"") as fin: + raw_nums = list(map(int, fin.read().strip().split())) + +nums = defaultdict(int) +for x in raw_nums: + nums[x] += 1 + + +def blink(nums: dict): + new_nums = defaultdict(int) + for x in nums: + l = len(str(x)) + if x == 0: + new_nums[1] += nums[0] + elif l % 2 == 0: + new_nums[int(str(x)[:l//2])] += nums[x] + new_nums[int(str(x)[l//2:])] += nums[x] + else: + new_nums[x * 2024] += nums[x] + + return new_nums + + +for i in range(75): + nums = blink(nums) + +ans = 0 +for x in nums: + ans += nums[x] +print(ans) +",python:3.9.21-slim +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"try: + with open(""11/input.txt"", ""r"") as file: + data = file.read() +except Exception: + with open(""input.txt"", ""r"") as file: + data = file.read() + +data = data.split("" "") + + +class Stone: + def __init__(self, n, ntimes = 1): + self.n = int(n) + self.ntimes = ntimes + + def evolve(self): + if self.n == 0: + self.n = 1 + return [self] + elif len(str(self.n)) % 2 == 0: + return [Stone(str(self.n)[:len(str(self.n))//2], self.ntimes), Stone(str(self.n)[len(str(self.n))//2:], self.ntimes)] + else: + self.n = self.n*2024 + return [self] + + def __str__(self): + return ""{""+str(self.n)+"",""+str(self.ntimes)+""}"" + + +stones = [] +for i in data: + stones.append(Stone(i)) + +blinks = 75 +for blink in range(blinks): + newstones = [] + print(""Blink "", blink) + #print("" "".join([x.__str__() for x in stones])) + print(len(stones)) + for i in range(len(stones)): + for stone in stones[i].evolve(): + newstones.append(stone) + stones = newstones + + if True: + i = -1 + while i < len(stones)-1: + i = i+1 + j = i + while j < len(stones)-1: + j = j+1 + if stones[i].n == stones[j].n: + stones[i].ntimes += stones[j].ntimes + del stones[j] + j = j-1 + +print(""\n\n"", len(stones)) + +res = 0 +for i in stones: + res += i.ntimes +print(res) +",python:3.9.21-slim +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +",1377008," +def visit(x, y, visited): + area = 1 + visited.add((x, y)) + + for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + if ((x + dx, y + dy) not in visited and 0 <= x + dx < width + and 0 <= y + dy < height and garden[y][x] == garden[y + dy][x + dx]): + d_area, _ = visit(x + dx, y + dy, visited) + area += d_area + + return area, visited + +def perimeter(plot): + min_x = min(plot, key=lambda p: p[0])[0] + min_y = min(plot, key=lambda p: p[1])[1] + max_x = max(plot, key=lambda p: p[0])[0] + max_y = max(plot, key=lambda p: p[1])[1] + + perim = 0 + for ray_x in range(min_x , max_x + 1): + is_in = False + side_count = 0 + for ray_y in range(min_y, max_y + 2): + if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): + is_in = not is_in + side_count += 1 + + perim += side_count + + for ray_y in range(min_y , max_y + 1): + is_in = False + side_count = 0 + for ray_x in range(min_x, max_x + 2): + if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): + is_in = not is_in + side_count += 1 + + perim += side_count + return perim + +def main(): + visited = set() + result = 0 + for y, row in enumerate(garden): + for x, column in enumerate(row): + if (x, y) not in visited: + area, v = visit(x, y, set()) + perim = perimeter(v) + visited.update(v) + result += area * perim + + print(result) + + +with open(""12_input.txt"", ""r"") as f: + garden = [line.strip() for line in f.readlines()] + +width = len(garden[0]) +height = len(garden) + +if __name__ == '__main__': + main() +",python:3.9.21-slim +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +",1377008,"from collections import deque + +inp = [] +with open('day12-data.txt', 'r') as f: + for line in f: + inp.append(list(line.strip())) + +# print(inp) +num_rows = len(inp) +num_cols = len(inp[0]) + +def in_bounds(rc): + r, c = rc + return (0 <= r < num_rows) and (0 <= c < num_cols) + +def get_plant(rc): + r, c = rc + return inp[r][c] + +def get_neighbors(rc): + r, c = rc + neighbors = [] + ds = [(-1, 0), (0, 1), (1, 0), (0, -1)] # NESW + for (dr, dc) in ds: + neighbors.append((r + dr, c + dc)) + return [n for n in neighbors if in_bounds(n)] + +def get_plant_neighbors(rc): + neighbors = get_neighbors(rc) + return [n for n in neighbors if get_plant(n)==get_plant(rc)] + +# BFS +def get_region(rc): + visited = set() + region = set() + queue = deque([rc]) + while queue: + node = queue.popleft() + if node not in visited: + visited.add(node) + # visit node + region.add(node) + # add all unvisited neighbors to the queue + neighbors = get_plant_neighbors(node) + unvisited_neighbors = [n for n in neighbors if n not in visited] + # print(f'At node {node}, ns: {neighbors}, unvisited: {unvisited_neighbors}') + queue.extend(unvisited_neighbors) + return region + +def calc_perimeter(region): + perimeter = 0 + for rc in region: + plant = get_plant(rc) + neighbors = get_plant_neighbors(rc) + # Boundary adds to perimeter + perimeter += 4 - len(neighbors) + + return perimeter + +regions = [] +visited = set() +for r in range(num_rows): + for c in range(num_cols): + rc = (r, c) + if rc not in visited: + region = get_region(rc) + visited |= region + regions.append(region) + +# print(regions) + +total_price = 0 +for region in regions: + plant = get_plant(next(iter(region))) + area = len(region) + perimeter = calc_perimeter(region) + price = area * perimeter + total_price += price + # print(f'{plant} (area: {area}, perimeter: {perimeter}): {region}') + +print(total_price)",python:3.9.21-slim +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +",1377008,"input = open(""day_12\input.txt"", ""r"").read().splitlines() + +directions = [(1,0), (0,1), (-1, 0), (0, -1)] +total = 0 + +def add_padding(matrix): + padding_row = ['!' * (len(matrix[0]) + 2)] + padded_matrix = [f""{'!'}{row}{'!'}"" for row in matrix] + return padding_row + padded_matrix + padding_row + +def explore(char, i, j): + global area, perimeter + if not input[i][j] == char: + perimeter += 1 + return + + visited.add((i,j)) + global_visited.add((i, j)) + area += 1 + for (dy, dx) in directions: + if not (i + dy, j + dx) in visited: + explore(char, i + dy, j + dx) + + +input = [list(line) for line in add_padding(input)] +global_visited = set() + +for i in range(len(input)): + for j in range(len(input[i])): + if not input[i][j] == ""!"" and not (i, j) in global_visited: + visited = set() + area = 0 + perimeter = 0 + explore(input[i][j], i, j) + total += area * perimeter + +print(f""The total price of fencing all the regions is {total}"") + +",python:3.9.21-slim +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +",1377008,"from collections import deque + +with open('input.txt') as f: + data = f.read().splitlines() + +xmax = len(data[0]) +ymax = len(data) + +total_seen = set() + + +def calc_plot(x, y): + plant = data[y][x] + + perimeter = 0 + area = 0 + seen = set() + + q = deque() + q.append((x, y)) + + while q: + xi, yi = q.popleft() + + if (xi, yi) in seen: + continue + + if xi < 0 or xi >= xmax or yi < 0 or yi >= ymax or data[yi][xi] != plant: + perimeter += 1 + continue + + seen.add((xi, yi)) + area += 1 + + q.append((xi + 1, yi)) + q.append((xi - 1, yi)) + q.append((xi, yi + 1)) + q.append((xi, yi - 1)) + + total_seen.update(seen) + return area * perimeter + + +total = 0 +for yi in range(ymax): + for xi in range(xmax): + if (xi, yi) in total_seen: + continue + + total += calc_plot(xi, yi) + +print(total) +",python:3.9.21-slim +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +",1377008,"from typing import List +from pprint import pprint as pprint + +INPUT_FILE = ""input.txt"" +visited = set() + +class Plot: + def __init__(self, plant: str, area: int, perimeter: int): + self.plant = plant + self.area = area + self.perimeter = perimeter + + def __repr__(self): + return f""Plot({self.plant}, {self.area}, {self.perimeter})"" + + def __str__(self): + return f""Plot({self.plant}, {self.area}, {self.perimeter})"" + +def readInput() -> List[List[str]]: + with open(INPUT_FILE, 'r') as f: + return [list(line.strip()) for line in f.readlines()] + +def findPlot(grid: List[List[str]], currentPlot: Plot, currentLocation: tuple[int, int]) -> Plot: + plot = Plot(currentPlot.plant, currentPlot.area, currentPlot.perimeter) + visited.add(currentLocation) + + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] + + for direction in directions: + x = currentLocation[0] + direction[0] + y = currentLocation[1] + direction[1] + + if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]): + plot.perimeter += 1 + continue + if grid[x][y] != plot.plant: + plot.perimeter += 1 + continue + + if (x, y) in visited: + continue + + plot.area += 1 + plot = findPlot(grid, plot, (x, y)) + + return plot + +def getPlots(grid: List[List[str]]) -> List[Plot]: + plots = [] + for i in range(len(grid)): + for j in range(len(grid[0])): + if (i, j) in visited: + continue + plot = findPlot(grid, Plot(grid[i][j], 1, 0), (i, j)) + plots.append(plot) + return plots + +def calculateCosts(plots: List[Plot]) -> int: + cost = 0 + for plot in plots: + cost += plot.area * plot.perimeter + return cost + +def main(): + grid = readInput() + pprint(grid) + plots = getPlots(grid) + pprint(plots) + print(f'Cost: {calculateCosts(plots)}') + +if __name__ == ""__main__"": + main() + ",python:3.9.21-slim +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"input = open(""day_12\input.txt"", ""r"").read().splitlines() + +directions = [(1,0), (0,1), (-1, 0), (0, -1)] +total = 0 + +def add_padding(matrix): + padding_row = ['!' * (len(matrix[0]) + 2)] + padded_matrix = [f""{'!'}{row}{'!'}"" for row in matrix] + return padding_row + padded_matrix + padding_row + +def explore(char, i, j): + global area, sides + visited.add((i,j)) + global_visited.add((i,j)) + area += 1 + for (dy,dx) in directions: + if input[i + dy][j + dx] != char: + sides += [((dy,dx), (i,j))] + elif not (i + dy, j + dx) in visited: + explore(char, i + dy, j + dx) + +def calculate_sides(sides): + unique_sides = 0 + while len(sides) > 0: + current_side = sides[0] + sides = explore_side(current_side, sides[0:]) + unique_sides += 1 + if current_side in sides: sides.remove(current_side) + return unique_sides + +def explore_side(side, sides): + if side[0] == (1, 0) or side[0] == (-1, 0): + targets = [(side[0], (side[1][0], side[1][1] - 1)), (side[0], (side[1][0], side[1][1] + 1))] + for target in targets: + if target in sides: + sides.remove(target) + sides = explore_side(target, sides) + elif side[0] == (0, 1) or side[0] == (0, -1): + targets = [(side[0], (side[1][0] + 1, side[1][1])), (side[0], (side[1][0] - 1, side[1][1]))] + for target in targets: + if target in sides: + sides.remove(target) + sides = explore_side(target, sides) + return sides + +input = [list(line) for line in add_padding(input)] +global_visited = set() + +for i in range(len(input)): + for j in range(len(input[i])): + if input[i][j] != ""!"" and not (i, j) in global_visited: + visited = set() + area = 0 + sides = [] + explore(input[i][j], i, j) + total += area * calculate_sides(sides) + +print(f""The total price of fencing all the regions is {total}"") + +",python:3.9.21-slim +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"def add_to_region_from(grid, loc, region, visited): + region.add(loc) + visited.add(loc) + + neighbors = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)] + neighbors = [pt for pt in neighbors if pt[0] in range(len(grid)) and pt[1] in range(len(grid))] + + + for neighbor in neighbors: + if grid[loc[0]][loc[1]] == grid[neighbor[0]][neighbor[1]] and not neighbor in visited: + add_to_region_from(grid, neighbor, region, visited) + +def get_area(region): + return len(region) + +def get_sides(region): + sides = 0 + visited_edges = set() + + sorted_region = sorted(list(region)) + + for loc in sorted_region: + above = (loc[0] - 1, loc[1]) + if above not in region: + visited_edges.add((above, 'bottom')) + if ((above[0], above[1] - 1), 'bottom') not in visited_edges and ((above[0], above[1] + 1), 'bottom') not in visited_edges: + sides += 1 + + below = (loc[0] + 1, loc[1]) + if below not in region: + visited_edges.add((below, 'top')) + if ((below[0], below[1] - 1), 'top') not in visited_edges and ((below[0], below[1] + 1), 'top') not in visited_edges: + sides += 1 + + left = (loc[0], loc[1] - 1) + if left not in region: + visited_edges.add((left, 'right')) + if ((left[0] - 1, left[1]), 'right') not in visited_edges and ((left[0] + 1, left[1]), 'right') not in visited_edges: + sides += 1 + + + right = (loc[0], loc[1] + 1) + if right not in region: + visited_edges.add((right, 'left')) + if ((right[0] - 1, right[1]), 'left') not in visited_edges and ((right[0] + 1, right[1]), 'left') not in visited_edges: + sides += 1 + + return sides + +def get_corners(region): + corners = 0 + for loc in region: + outer_top_left = [((0, -1), False), ((-1, 0), False)] + outer_top_right = [((0, 1), False), ((-1, 0), False)] + outer_bottom_right = [((0, 1), False), ((1, 0), False)] + outer_bottom_left = [((0, -1), False), ((1, 0), False)] + + inner_top_left = [((0, 1), True), ((1, 0), True), ((1, 1), False)] + inner_top_right = [((0, -1), True), ((1, 0), True), ((1, -1), False)] + inner_bottom_right = [((0, -1), True), ((-1, 0), True), ((-1, -1), False)] + inner_bottom_left = [((0, 1), True), ((-1, 0), True), ((-1, 1), False)] + + all_neighbors = [outer_top_left, outer_top_right, outer_bottom_right, outer_bottom_left, inner_top_left, inner_top_right, inner_bottom_right, inner_bottom_left] + + corners += sum([all([((loc[0] + pt[0][0], loc[1] + pt[0][1]) in region) == pt[1] for pt in neighbor]) for neighbor in all_neighbors]) + + return corners + + +def get_perimeter(region): + perimeter = 0 + + for loc in region: + neighbors = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)] + perimeter += len([pt for pt in neighbors if pt not in region]) + + return perimeter + + + +with open('input.txt') as f: + grid = [[c for c in line] for line in f.read().splitlines()] + + +visited = set() +regions = [] + +for i in range(len(grid)): + for j in range(len(grid[i])): + if not (i, j) in visited: + region = set() + add_to_region_from(grid, (i, j), region, visited) + regions.append(region) + + visited.add((i, j)) + +total_price = 0 + +for region in regions: + price = get_area(region) * get_corners(region) + total_price += price + +print(total_price) + +",python:3.9.21-slim +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"from collections import deque + +with open('input.txt') as f: + data = f.read().splitlines() + +xmax = len(data[0]) +ymax = len(data) + +total_seen = set() + + +def count_corners(plant, x, y): + up = data[y - 1][x] if y - 1 >= 0 else None + down = data[y + 1][x] if y + 1 < ymax else None + left = data[y][x - 1] if x - 1 >= 0 else None + right = data[y][x + 1] if x + 1 < xmax else None + + count = sum(1 for i in (up, down, left, right) if i == plant) + + corners = 0 + + if count == 0: + return 4 + if count == 1: + return 2 + if count == 2: + if left == right == plant or up == down == plant: + return 0 + corners += 1 + + if up == left == plant and (y - 1 >= 0 and x - 1 >= 0) and data[y - 1][x - 1] != plant: + corners += 1 + if up == right == plant and (y - 1 >= 0 and x + 1 < xmax) and data[y - 1][x + 1] != plant: + corners += 1 + if down == left == plant and (y + 1 < ymax and x - 1 >= 0) and data[y + 1][x - 1] != plant: + corners += 1 + if down == right == plant and (y + 1 < ymax and x + 1 < xmax) and data[y + 1][x + 1] != plant: + corners += 1 + + return corners + + +def calc_plot(x, y): + plant = data[y][x] + + perimeter = 0 + area = 0 + corners = 0 + seen = set() + + q = deque() + q.append((x, y)) + + while q: + xi, yi = q.popleft() + + if (xi, yi) in seen: + continue + + if xi < 0 or xi >= xmax or yi < 0 or yi >= ymax or data[yi][xi] != plant: + perimeter += 1 + continue + + seen.add((xi, yi)) + area += 1 + corners += count_corners(plant, xi, yi) + + q.append((xi + 1, yi)) + q.append((xi - 1, yi)) + q.append((xi, yi + 1)) + q.append((xi, yi - 1)) + + total_seen.update(seen) + + return area * corners + + +total = 0 +for yi in range(ymax): + for xi in range(xmax): + if (xi, yi) in total_seen: + continue + + total += calc_plot(xi, yi) + +print(total) +",python:3.9.21-slim +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788," +def visit(x, y, visited): + area = 1 + visited.add((x, y)) + + for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + if ((x + dx, y + dy) not in visited and 0 <= x + dx < width + and 0 <= y + dy < height and garden[y][x] == garden[y + dy][x + dx]): + d_area, _ = visit(x + dx, y + dy, visited) + area += d_area + + return area, visited + +def perimeter(plot): + min_x = min(plot, key=lambda p: p[0])[0] + min_y = min(plot, key=lambda p: p[1])[1] + max_x = max(plot, key=lambda p: p[0])[0] + max_y = max(plot, key=lambda p: p[1])[1] + + # vertical rays + hits = {} + for ray_x in range(min_x - 1, max_x + 1): + is_in = False + hits[ray_x] = [] + for ray_y in range(min_y - 1, max_y + 2): + if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): + is_in = not is_in + hits[ray_x].append((ray_y, is_in)) + + side_count = 0 + for i, hit_x in enumerate(hits): + if i > 0: + for (y, is_in) in hits[hit_x]: + if (y, is_in) not in hits[hit_x - 1]: + side_count += 1 + + # horizontal rays + hits = {} + for ray_y in range(min_y - 1, max_y + 1): + is_in = False + hits[ray_y] = [] + for ray_x in range(min_x - 1, max_x + 2): + if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): + is_in = not is_in + hits[ray_y].append((ray_x, is_in)) + + for i, hit_y in enumerate(hits): + if i > 0: + for (y, is_in) in hits[hit_y]: + if (y, is_in) not in hits[hit_y - 1]: + side_count += 1 + return side_count + +def main(): + visited = set() + result = 0 + for y, row in enumerate(garden): + for x, column in enumerate(row): + if (x, y) not in visited: + area, v = visit(x, y, set()) + perim = perimeter(v) + visited.update(v) + result += area * perim + + print(result) + + +with open(""12_input.txt"", ""r"") as f: + garden = [line.strip() for line in f.readlines()] + +width = len(garden[0]) +height = len(garden) + +if __name__ == '__main__': + main() +",python:3.9.21-slim +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"from collections import deque + +def get_total_cost(farm): + n = len(farm) + m = len(farm[0]) + + def in_bounds(r, c): + return (0 <= r < n) and (0 <= c < m) + + def get_val(r, c): + return farm[r][c] + + def get_neighbours(r, c): + neighbours = [] + dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)] + for (dr, dc) in dirs: + neighbours.append((r + dr, c + dc)) + + return [neighbour for neighbour in neighbours if in_bounds(neighbour[0], neighbour[1])] + + def get_val_neighbours(r, c): + neighbours = get_neighbours(r, c) + return [neighbour for neighbour in neighbours if get_val(neighbour[0], neighbour[1]) == get_val(r, c)] + + def get_region(r, c): + visited = set() + region = set() + queue = deque([(r, c)]) + + while queue: + node = queue.popleft() + if node not in visited: + visited.add(node) + region.add(node) + neighbours = get_val_neighbours(node[0], node[1]) + neighbours = [neighbour for neighbour in neighbours if neighbour not in visited] + queue.extend(neighbours) + return region + + def calc_edges(region): + edges = 0 + for (r, c) in region: + if ((r - 1, c) not in region): + if not (((r, c - 1) in region) and ((r - 1, c - 1) not in region)): + edges += 1 + + if ((r + 1, c) not in region): + if not (((r, c - 1) in region) and ((r + 1, c - 1) not in region)): + edges += 1 + + if ((r, c - 1) not in region): + if not (((r - 1, c) in region) and ((r - 1, c - 1) not in region)): + edges += 1 + + if ((r, c + 1) not in region): + if not (((r - 1, c) in region) and ((r - 1, c + 1) not in region)): + edges += 1 + return edges + + regions = [] + visited = set() + for i in range(n): + for j in range(m): + if (i, j) not in visited: + region = get_region(i, j) + visited |= region + regions.append(region) + + cost = 0 + for region in regions: + nextRegion = next(iter(region)) + val = get_val(nextRegion[0], nextRegion[1]) + area = len(region) + edges = calc_edges(region) + price = area * edges + cost += price + + return cost + +if __name__ == ""__main__"": + # Open file 'day12-2.txt' in read mode + with open('day12-2.txt', 'r') as f: + farm = [] + for line in f: + farm.append(line.strip()) + print(""Total fencing cost: "" + str(get_total_cost(farm)))",python:3.9.21-slim +2024,13,1,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +total = 0 +for problem in range((len(input_text) + 1) // 4): + button_a_move_x, button_a_move_y = ( + input_text[problem * 4].removeprefix(""Button A: "").split("", "") + ) + button_a_move = ( + int(button_a_move_x.removeprefix(""X+"")), + int(button_a_move_y.removeprefix(""Y+"")), + ) + button_b_move_x, button_b_move_y = ( + input_text[problem * 4 + 1].removeprefix(""Button B: "").split("", "") + ) + button_b_move = ( + int(button_b_move_x.removeprefix(""X+"")), + int(button_b_move_y.removeprefix(""Y+"")), + ) + target_x, target_y = input_text[problem * 4 + 2].removeprefix(""Prize: "").split("", "") + target = (int(target_x.removeprefix(""X="")), int(target_y.removeprefix(""Y=""))) + + min_cost = float(""inf"") + for a_presses in range(101): + for b_presses in range(101): + if ( + a_presses * button_a_move[0] + b_presses * button_b_move[0], + a_presses * button_a_move[1] + b_presses * button_b_move[1], + ) == target: + min_cost = min(min_cost, a_presses * 3 + b_presses) + if min_cost < float(""inf""): + total += min_cost +print(total) +",python:3.9.21-slim +2024,13,1,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"import re + +with open(""./day_13.in"") as fin: + lines = fin.read().strip().split(""\n\n"") + + +def parse(x): + lines = x.split(""\n"") + a = list(map(int, re.findall(r""Button A: X\+(\d+), Y\+(\d+)"", lines[0])[0])) + b = list(map(int, re.findall(r""Button B: X\+(\d+), Y\+(\d+)"", lines[1])[0])) + p = list(map(int, re.findall(r""Prize: X=(\d+), Y=(\d+)"", lines[2])[0])) + return a, b, p + + +prices = [] +for a, b, p in [parse(line) for line in lines]: + def test(i, j): + x = a[0] * i + b[0] * j + y = a[1] * i + b[1] * j + return (x, y) == tuple(p) + + va = 1<<30 + for i in range(100): + for j in range(100): + if test(i, j): + va = min(va, 3*i + j) + + if va < 1<<30: + prices.append(va) + + +spent = 0 +print(sum(prices)) +",python:3.9.21-slim +2024,13,1,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"from typing import List +from pprint import pprint as pprint +from functools import cache + +INPUT_FILE = ""input.txt"" +MAX_PRIZE = 401 + +class Button: + def __init__(self, price: int, d_x: int, d_y: int): + self.price = price + self.d_x = d_x + self.d_y = d_y + + def __repr__(self): + return f""Button({self.price}, {self.d_x}, {self.d_y})"" + + def __str__(self): + return f""Button({self.price}, {self.d_x}, {self.d_y})"" + +class Prize: + def __init__(self, x: int, y: int): + self.x = x + self.y = y + + def __repr__(self): + return f""Price({self.x}, {self.y})"" + + def __str__(self): + return f""Price({self.x}, {self.y})"" + +def readInput() -> List[str]: + with open(INPUT_FILE, 'r') as f: + return f.read().split('\n\n') + +def parseInput(data: str) -> tuple[Prize, tuple[Button, Button]]: + a, b, prize = data.splitlines() + + button_a = Button(3, int(a.split(""X+"")[1].split("","")[0]), int(a.split(""Y+"")[1])) + button_b = Button(1, int(b.split(""X+"")[1].split("","")[0]), int(b.split(""Y+"")[1])) + prize = Prize(int(prize.split(""X="")[1].split("","")[0]), int(prize.split(""Y="")[1])) + + return (prize, (button_a, button_b)) + +@cache +def getCost(prize: Prize, buttons: tuple[Button, Button]) -> int: + # lowest_cost = MAX_PRIZE + + for a in range(100): + for b in range(100): + if prize.x == buttons[0].d_x*a+buttons[1].d_x*b and prize.y == buttons[0].d_y*a+buttons[1].d_y*b: + return a * buttons[0].price + b * buttons[1].price + + return 0 + +def costs(machines: List[tuple[Prize, tuple[Button, Button]]]) -> List[int]: + costs = [] + + for machine in machines: + costs.append(getCost(machine[0], machine[1])) + + return costs + +def main(): + data = readInput() + # pprint(data) + machines = [parseInput(line) for line in data] + # pprint(machines) + costs_list = costs(machines) + # pprint(costs_list) + print(f""Result: {sum(costs_list)}"") + +if __name__ == ""__main__"": + main()",python:3.9.21-slim +2024,13,1,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"f = open(""input.txt"") +machines = [elem.split(""\n"") for elem in f.read().split(""\n\n"")] + +def find_solution(A_button, B_button, prize): + X_a, Y_a = A_button + X_b, Y_b = B_button + X_prize, Y_prize = prize + b = (X_prize * Y_a - Y_prize * X_a) / (X_b * Y_a - X_a * Y_b) + a = (X_prize * Y_b - Y_prize * X_b) / (X_a * Y_b - X_b * Y_a) + if (int(a) == a and a <= 100 and int(b) == b and b <= 100): + return (a,b) + return () + +def get_cost(solution): + return solution[0]*3 + solution[1] + + +total = 0 +for machine in machines: + A_button = tuple([int(text[3:]) for text in machine[0].split("":"")[1].split("","")]) + B_button = tuple([int(text[3:]) for text in machine[1].split("":"")[1].split("","")]) + prize = tuple([int(text[3:]) for text in machine[2].split("":"")[1].split("","")]) + solution = find_solution(A_button, B_button, prize) + if solution != (): + cost = get_cost(solution) + total += cost + +print(total) + + + + +",python:3.9.21-slim +2024,13,1,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"import os + + +def reader(): + return open(f""input.txt"", 'r').read().splitlines() + + +def part1(): + f = list(map(lambda s: s.split('\n'), '\n'.join(reader()).split('\n\n'))) + M = [] + for l in f: + Ax = int(l[0][(l[0].find('X+') + 2):l[0].find(',')]) + Ay = int(l[0][(l[0].find('Y+') + 2):]) + Bx = int(l[1][(l[1].find('X+') + 2):l[1].find(',')]) + By = int(l[1][(l[1].find('Y+') + 2):]) + X = int(l[2][(l[2].find('X=') + 2):l[2].find(',')]) + Y = int(l[2][(l[2].find('Y=') + 2):]) + M.append([(Ax, Ay), (Bx, By), (X, Y)]) + t = 0 + for m in M: + l = -1, 0 + for i in range(101): + for j in range(101): + cost = 3 * i + j + pos = i * m[0][0] + j * m[1][0], i * m[0][1] + j * m[1][1] + if pos == m[2]: + l = (0, cost) if l[0] == -1 else (0, min(l[1], cost)) + if l[0] == 0: + t += l[1] + print(t) + +part1()",python:3.9.21-slim +2024,13,2,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? + +Your puzzle answer was 34787. + +--- Part Two --- + +As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! + +Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=10000000008400, Y=10000000005400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=10000000012748, Y=10000000012176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=10000000007870, Y=10000000006450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=10000000018641, Y=10000000010279 +Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. + +Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"def get_cheapest(machine): + A = machine[0] + B = machine[1] + prize = (machine[2][0] + 10000000000000, machine[2][1] + 10000000000000) + + af = (A[1] / A[0]) + bf = (B[1] / B[0]) + + xIntersection = round((prize[0] * af - prize[1]) / (af - bf)) + if xIntersection % B[0] != 0: + return 0 + + b = xIntersection // B[0] + rem = ((prize[0] - B[0] * b), (prize[1] - B[1] * b)) + if rem[0] % A[0] != 0: + return 0 + + a = rem[0] // A[0] + if ((B[0] * b) + (A[0] * a) == prize[0] and (B[1] * b) + (A[1] * a)) == prize[1]: + return b + (a * 3) + + return 0 + + +def get_fewest_tokens(machines): + tokens = 0 + for machine in machines: + tokens += get_cheapest(machine) + return tokens + +if __name__ == ""__main__"": + # Open file 'day13-2.txt' in read mode + with open('day13-2.txt', 'r') as f: + machines = [] + A = (0, 0) + B = (0, 0) + prize = (0, 0) + for i, line in enumerate(f): + line = line.strip() + if i % 4 == 0: + A = (int(line[line.find('+') + 1: line.find(',')]), int(line[line.find(',') + 4:])) + elif i % 4 == 1: + B = (int(line[line.find('+') + 1: line.find(',')]), int(line[line.find(',') + 4:])) + elif i % 4 == 2: + prize = (int(line[line.find('=') + 1: line.find(',')]), int(line[line.find(',') + 4:])) + machines.append([ + A, + B, + prize + ]) + else: + A = (0, 0) + B = (0, 0) + prize = (0, 0) + + print(""Fewest number of tokens: "" + str(get_fewest_tokens(machines)))",python:3.9.21-slim +2024,13,2,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? + +Your puzzle answer was 34787. + +--- Part Two --- + +As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! + +Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=10000000008400, Y=10000000005400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=10000000012748, Y=10000000012176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=10000000007870, Y=10000000006450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=10000000018641, Y=10000000010279 +Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. + +Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"f = open(""input.txt"") +machines = [elem.split(""\n"") for elem in f.read().split(""\n\n"")] + +def find_solution(A_button, B_button, prize): + X_a, Y_a = A_button + X_b, Y_b = B_button + X_prize, Y_prize = prize + X_prize += 10000000000000 + Y_prize += 10000000000000 + b = (X_prize * Y_a - Y_prize * X_a) / (X_b * Y_a - X_a * Y_b) + a = (X_prize * Y_b - Y_prize * X_b) / (X_a * Y_b - X_b * Y_a) + if (int(a) == a and int(b) == b): + return (a,b) + return () + +def get_cost(solution): + return solution[0]*3 + solution[1] + + +total = 0 +for machine in machines: + A_button = tuple([int(text[3:]) for text in machine[0].split("":"")[1].split("","")]) + B_button = tuple([int(text[3:]) for text in machine[1].split("":"")[1].split("","")]) + prize = tuple([int(text[3:]) for text in machine[2].split("":"")[1].split("","")]) + solution = find_solution(A_button, B_button, prize) + if solution != (): + cost = get_cost(solution) + total += cost + +print(total) + + + + +",python:3.9.21-slim +2024,13,2,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? + +Your puzzle answer was 34787. + +--- Part Two --- + +As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! + +Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=10000000008400, Y=10000000005400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=10000000012748, Y=10000000012176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=10000000007870, Y=10000000006450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=10000000018641, Y=10000000010279 +Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. + +Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"import re +from typing import Tuple, List + +def parse_input(file_path: str) -> List[Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]]: + """""" + Parses the input file to extract button and prize coordinates. + + The input file should contain lines formatted as: + ""Button A: X+, Y+ Button B: X+, Y+ Prize: X=, Y="" + + Args: + file_path (str): The path to the input file. + + Returns: + List[Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]]: A list of tuples, each containing: + - A tuple representing the coordinates of Button A (X, Y). + - A tuple representing the coordinates of Button B (X, Y). + - A tuple representing the coordinates of the Prize (X, Y) with 10000000000000 added to each coordinate. + """""" + pattern = re.compile(r""Button A: X\+(\d+), Y\+(\d+)\s+Button B: X\+(\d+), Y\+(\d+)\s+Prize: X=(\d+), Y=(\d+)"") + results = [] + + with open(file_path, 'r') as file: + content = file.read() + matches = pattern.findall(content) + for match in matches: + button_a = (int(match[0]), int(match[1])) + button_b = (int(match[2]), int(match[3])) + prize = (int(match[4]) + 10000000000000, int(match[5]) + 10000000000000) + results.append((button_a, button_b, prize)) + + return results + +def solve(scenario: Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]) -> int: + """""" + Solves the given scenario by finding integers a and b such that the linear combination + of the vectors (ax, ay) and (bx, by) equals the target vector (tx, ty). + + Args: + scenario (Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]): A tuple containing + three tuples, each representing a vector in the form (x, y). The first two tuples + are the vectors (ax, ay) and (bx, by), and the third tuple is the target vector (tx, ty). + + Returns: + int: The result of the expression 3 * a + b if the linear combination is valid, otherwise 0. + """""" + (ax, ay), (bx, by), (tx, ty) = scenario + b = (tx * ay - ty * ax) // (ay * bx - by * ax) + a = (tx * by - ty * bx) // (by * ax - bx * ay) + if ax * a + bx * b == tx and ay * a + by * b == ty: + return 3 * a + b + else: + return 0 + +if __name__ == ""__main__"": + file_path = 'input.txt' + parsed_data = parse_input(file_path) + results = [solve(scenario) for scenario in parsed_data] + print(sum(results)) +",python:3.9.21-slim +2024,13,2,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? + +Your puzzle answer was 34787. + +--- Part Two --- + +As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! + +Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=10000000008400, Y=10000000005400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=10000000012748, Y=10000000012176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=10000000007870, Y=10000000006450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=10000000018641, Y=10000000010279 +Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. + +Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"import re + +def min_cost_for_prize(prize, a, b): + prize_x = prize[0] + prize_y = prize[1] + + a_x = a[0] + a_y = a[1] + b_x = b[0] + b_y = b[1] + + if (prize_x * b_y - b_x * prize_y) % (a_x * b_y - b_x * a_y) != 0: + return (False, -1) + + a_val = (prize_x * b_y - b_x * prize_y) // (a_x * b_y - b_x * a_y) + + if (prize_x - a_x * a_val) % b_x != 0: + return (False, -1) + + b_val = (prize_x - a_x * a_val) // b_x + + return (True, 3 * a_val + b_val) + + +with open('input.txt') as f: + claw_strs = f.read().split(""\n\n"") + +claw_data = [] + +for claw_input in claw_strs: + lines = claw_input.splitlines() + claw = dict() + claw['A'] = tuple(map(int, re.match(""Button A: X\\+(\\d+), Y\\+(\\d+)"", lines[0]).groups())) + claw['B'] = tuple(map(int, re.match(""Button B: X\\+(\\d+), Y\\+(\\d+)"", lines[1]).groups())) + claw['Prize'] = tuple(map(lambda n: n + 10000000000000, map(int, re.match(""Prize: X=(\\d+), Y=(\\d+)"", lines[2]).groups()))) + claw_data.append(claw) + +total_cost = 0 +for claw in claw_data: + res = min_cost_for_prize(claw['Prize'], claw['A'], claw['B']) + if res[0]: + total_cost += res[1] + +print(total_cost) + +",python:3.9.21-slim +2024,13,2,"--- Day 13: Claw Contraption --- + +Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. + +Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? + +The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. + +With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. + +Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. + +You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 +This list describes the button configuration and prize location of four different claw machines. + +For now, consider just the first claw machine in the list: + +Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. +Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. +The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. +The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. + +For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. + +For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. + +So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. + +You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? + +Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? + +Your puzzle answer was 34787. + +--- Part Two --- + +As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! + +Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: + +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=10000000008400, Y=10000000005400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=10000000012748, Y=10000000012176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=10000000007870, Y=10000000006450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=10000000018641, Y=10000000010279 +Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. + +Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +total = 0 +for problem in range((len(input_text) + 1) // 4): + button_a_move_x, button_a_move_y = ( + input_text[problem * 4].removeprefix(""Button A: "").split("", "") + ) + button_a_move = ( + int(button_a_move_x.removeprefix(""X+"")), + int(button_a_move_y.removeprefix(""Y+"")), + ) + button_b_move_x, button_b_move_y = ( + input_text[problem * 4 + 1].removeprefix(""Button B: "").split("", "") + ) + button_b_move = ( + int(button_b_move_x.removeprefix(""X+"")), + int(button_b_move_y.removeprefix(""Y+"")), + ) + target_x, target_y = input_text[problem * 4 + 2].removeprefix(""Prize: "").split("", "") + target = ( + int(target_x.removeprefix(""X="")) + 10000000000000, + int(target_y.removeprefix(""Y="")) + 10000000000000, + ) + sol_a, sol_b = ( + (button_b_move[1] * target[0] - button_b_move[0] * target[1]) + // (button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0]), + (-button_a_move[1] * target[0] + button_a_move[0] * target[1]) + // (button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0]), + ) + if ( + ( + (button_b_move[1] * target[0] - button_b_move[0] * target[1]) + % ( + button_a_move[0] * button_b_move[1] + - button_a_move[1] * button_b_move[0] + ) + ) + == 0 + and ( + (-button_a_move[1] * target[0] + button_a_move[0] * target[1]) + % ( + button_a_move[0] * button_b_move[1] + - button_a_move[1] * button_b_move[0] + ) + ) + == 0 + and sol_a > 0 + and sol_b > 0 + ): + total += 3 * sol_a + sol_b + +print(total) +",python:3.9.21-slim +2024,14,1,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"import re + +def read_input(): + robots = [] + with open(""./input.txt"") as f: + while True: + line = f.readline() + if not line: + break + numbers = re.findall(r""-?\d+"", line) + robots.append([int(s) for s in numbers]) + return robots + +def move_robot_n_step(robot, width, height, n): + x0 = robot[0] + y0 = robot[1] + vx = robot[2] + vy = robot[3] + for i in range(n): + x0 = (x0 + vx) % width + y0 = (y0 + vy) % height + + return x0, y0 + +def move_robot_one_step(robot, width, height): + x0 = robot[0] + y0 = robot[1] + vx = robot[2] + vy = robot[3] + + robot[0] = (x0 + vx) % width + robot[1] = (y0 + vy) % height + + +def get_quadrant(x, y, width, height): + cx = width // 2 + cy = height // 2 + + if x < cx and y < cy: + return 4 + elif x < cx and y > cy: + return 3 + elif x > cx and y < cy: + return 1 + elif x > cx and y > cy: + return 2 + else: + return -1 + +def solve_part1(robots, width, height): + q = {1:0, 2:0, 3:0, 4:0, -1:0} + for robot in robots: + x,y = move_robot_n_step(robot, width, height, 100) + iq = get_quadrant(x, y, width, height) + q[iq] += 1 + + print(f""q1: {q[1]}, q2: {q[2]}, q3: {q[3]}, q4: {q[4]}"") + return q[1] * q[2] * q[3] * q[4] + +def solve_part2(robots, width, height): + best_iter = None + min_safe = float('inf') + for i in range(width * height): + q = {1:0, 2:0, 3:0, 4:0, -1:0} + for robot in robots: + x,y = move_robot_n_step(robot, width, height, 1) + robot[0] = x + robot[1] = y + iq = get_quadrant(x, y, width, height) + q[iq] += 1 + safe = q[1] * q[2] * q[3] * q[4] + if safe < min_safe: + min_safe = safe + best_iter = i + if i == 99: + print(""At 100 sec, "", safe) + print(f""best iter {best_iter}, min safe {min_safe}"") + +if __name__ == ""__main__"": + robots = read_input() + width = 101 + height = 103 + multiply = solve_part1(robots, width, height) + print(f""Part 1: the product is {multiply}"") + solve_part2(robots, width, height)",python:3.9.21-slim +2024,14,1,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"from collections import Counter +import re + +width = 101 #11 +half_width = width // 2 +height = 103 #7 +half_height = height // 2 + + +class Robot: + + def __init__(self, px, py, vx, vy) -> None: + self.px = px + self.py = py + self.vx = vx + self.vy = vy + self.q = None + + def move(self, seconds): + self.px = (self.px + self.vx * seconds) % width + self.py = (self.py + self.vy * seconds) % height + self.q = self.quadrant() + + def quadrant(self): + quadrants = { + (True, True): 1, + (True, False): 3, + (False, True): 2, + (False, False): 4, + } + return quadrants[(self.px < half_width, + self.py < half_height)] if self.px != half_width and self.py != half_height else None + + +with open('input.txt') as f: + robots = [Robot(*map(int, re.findall(r'(-?\d+)', line))) for line in f] + + +def print_grid(robots: list[Robot]): + grid = [list('.' * width) for _ in range(height)] + + for robot in robots: + val = grid[robot.py][robot.px] + grid[robot.py][robot.px] = '1' if val == '.' else str(int(val) + 1) + + print('\n'.join(''.join(row) for row in grid)) + + +quadrants = [] +for robot in robots: + robot.move(100) + quadrants.append(robot.q) + +counter = Counter(quadrants) +counter.pop(None) + +print(counter[1] * counter[2] * counter[3] * counter[4]) +",python:3.9.21-slim +2024,14,1,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"#!/usr/bin/python3 + +class Robot: + + def __init__(self, position, velocity): + self.position = position + self.velocity = velocity + + def teleport(self, pos:int, dim:int): + """"""Move to opposite side rather than out of the space."""""" + return pos - dim if pos >= dim else dim - abs(pos) if pos < 0 else pos + + def move_robot(self, width:int, height:int): + """"""Move robot according to its velocity."""""" + self.position = [self.position[0] + self.velocity[0], + self.position[1] + self.velocity[1]] + if self.position[0] not in range(width): + self.position[0] = self.teleport(self.position[0], width) + if self.position[1] not in range(height): + self.position[1] = self.teleport(self.position[1], height) + + +# Get initial position and velocity for each robot. +with open(""input.txt"") as file: + + robots = {} + + for l, line in enumerate(file): + + robot_name = ""robot_"" + str(l+1) + pos = line.split()[0].strip(""p="").split("","") + vel = line.split()[1].strip(""v="").split("","") + + robots[robot_name] = Robot([int(pos[0]),int(pos[1])], + [int(vel[0]),int(vel[1])]) + + +# Move robots for 100 seconds in a space 101 tiles wide and 103 tiles tall. +for robot in robots: + for sec in range(100): + robots[robot].move_robot(101, 103) + +# Determine the safety factor. +quadrant_1 = [robots[robot].position for robot in robots + if robots[robot].position[0] < 50 and robots[robot].position[1] < 51] +quadrant_2 = [robots[robot].position for robot in robots + if robots[robot].position[0] > 50 and robots[robot].position[1] < 51] +quadrant_3 = [robots[robot].position for robot in robots + if robots[robot].position[0] < 50 and robots[robot].position[1] > 51] +quadrant_4 = [robots[robot].position for robot in robots + if robots[robot].position[0] > 50 and robots[robot].position[1] > 51] + +print(""Safety factor after 100 seconds:"", + len(quadrant_1) * len(quadrant_2) * len(quadrant_3) * len(quadrant_4)) +",python:3.9.21-slim +2024,14,1,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"from typing import List + +EXAMPLE: bool = False + +WIDTH: int = 11 if EXAMPLE else 101 +HEIGHT: int = 7 if EXAMPLE else 103 + +INPUT_FILE: str = ""e_input.txt"" if EXAMPLE else ""input.txt"" + +class Robot: + def __init__(self, x: int, y: int, v_x: int, v_y: int): + self.x = x + self.y = y + self.v_x = v_x + self.v_y = v_y + + def move(self): + self.x += self.v_x + self.y += self.v_y + + if self.x < 0: + self.x = WIDTH + self.x + if self.y < 0: + self.y = HEIGHT + self.y + + if self.x >= WIDTH: + self.x -= WIDTH + if self.y >= HEIGHT: + self.y -= HEIGHT + + def __str__(self): + return f""Robot: x={self.x}, y={self.y}, v_x={self.v_x}, v_y={self.v_y}"" + + def __repr__(self): + return self.__str__() + +def read_input() -> List[str]: + with open(INPUT_FILE, ""r"") as f: + return f.read().splitlines() + +def parse_input(input: List[str]) -> List[Robot]: + robots: List[Robot] = [] + for line in input: + line = line.split("" "") + + pos = line[0][2:].split("","") + x, y = int(pos[0]), int(pos[1]) + velo = line[1][2:].split("","") + v_x, v_y = int(velo[0]), int(velo[1]) + + robots.append(Robot(x, y, v_x, v_y)) + + return robots + +def predict(robots: List[Robot], seconds: int) -> List[Robot]: + for i in range(seconds): + for robot in robots: + robot.move() + + return robots + +def print_grid(robots: List[Robot]): + for y in range(HEIGHT): + for x in range(WIDTH): + r = 0 + for robot in robots: + if robot.x == x and robot.y == y: + r += 1 + + if r == 0: + print(""."", end="""") + else: + print(str(r), end="""") + print() + +def safety_score(robots: List[Robot]) -> int: + quadrant_one = 0 + quadrant_two = 0 + quadrant_three = 0 + quadrant_four = 0 + + for robot in robots : + if robot.x < WIDTH // 2 and robot.y < HEIGHT // 2: + quadrant_one += 1 + elif robot.x > WIDTH // 2 and robot.y < HEIGHT // 2: + quadrant_two += 1 + elif robot.x < WIDTH // 2 and robot.y > HEIGHT // 2: + quadrant_three += 1 + elif robot.x > WIDTH // 2 and robot.y > HEIGHT // 2: + quadrant_four += 1 + + return quadrant_one * quadrant_two * quadrant_three * quadrant_four + +def main(): + robots = parse_input(read_input()) + robots = predict(robots, 100) + print(safety_score(robots)) + +if __name__ == ""__main__"": + main() +",python:3.9.21-slim +2024,14,1,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"import re +from functools import reduce +from operator import mul + +result = 0 +width = 101 +height = 103 +duration = 100 +robots = [] +with open(""14_input.txt"", ""r"") as f: + for line in f: + px, py, vx, vy = map(int, re.findall(r""(-?\d+)"", line)) + + for sec in range(duration): + px = (px + vx) % width + py = (py + vy) % height + + robots.append((px, py)) + +q_width = width // 2 +q_height = height // 2 + +quadrants = {0: 0, 1: 0, 2: 0, 3: 0} + +for robot in robots: + if robot[0] < q_width: + if robot[1] < q_height: + quadrants[0] += 1 + elif robot[1] > q_height: + quadrants[1] += 1 + elif robot[0] > q_width: + if robot[1] < q_height: + quadrants[2] += 1 + elif robot[1] > q_height: + quadrants[3] += 1 + +print(reduce(mul, quadrants.values())) +",python:3.9.21-slim +2024,14,2,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? + +Your puzzle answer was 219150360. + +--- Part Two --- + +During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import re +from functools import reduce +from operator import mul + +with open('input.txt') as f: + lines = f.read().splitlines() + +positions = [] +velocities = [] +for line in lines: + m = re.match(""p=(\\d+),(\\d+) v=(\\-?\\d+),(\\-?\\d+)"", line) + positions.append(tuple(map(int, m.groups()[0:2]))) + velocities.append(tuple(map(int, m.groups()[2:]))) + +x_len = 101 +y_len = 103 + +initial_positions = positions[:] + +for num_seconds in range(10000): + for i in range(len(positions)): + new_x = (initial_positions[i][0] + num_seconds * velocities[i][0]) % x_len + new_y = (initial_positions[i][1] + num_seconds * velocities[i][1]) % y_len + positions[i] = (new_x, new_y) + + grid = [[0] * x_len for j in range(y_len)] + + for pos in positions: + grid[pos[1]][pos[0]] += 1 + + no_dupes = True + for y in range(y_len): + for x in range(x_len): + if grid[y][x] > 1: + no_dupes = False + break + + if no_dupes: + print(""after"", num_seconds, ""seconds:"") + for y in range(y_len): + row = """" + for x in range(x_len): + v = grid[y][x] + row += f'{v}' if v > 0 else '.' + print(row) + break + + + + + + + +",python:3.9.21-slim +2024,14,2,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? + +Your puzzle answer was 219150360. + +--- Part Two --- + +During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"from collections import defaultdict +from statistics import stdev + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +num_x = 101 +num_y = 103 +initial_positions = [] +velocities = [] +for line in input_text: + p_sec, v_sec = line.split() + initial_positions.append([int(i) for i in p_sec.split(""="")[1].split("","")]) + velocities.append([int(i) for i in v_sec.split(""="")[1].split("","")]) + +for counter in range(10000): + block_counts = defaultdict(int) + new_initial_positions = [] + for initial_pos, velocity in zip(initial_positions, velocities): + new_position = [ + (initial_pos[0] + velocity[0]) % num_x, + (initial_pos[1] + velocity[1]) % num_y, + ] + new_initial_positions.append(new_position) + block_counts[(new_position[0] // 5, new_position[1] // 5)] += 1 + if stdev(block_counts.values()) > 3: + print(counter + 1) + initial_positions = new_initial_positions +",python:3.9.21-slim +2024,14,2,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? + +Your puzzle answer was 219150360. + +--- Part Two --- + +During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import re + + +with open(""input.txt"") as i: + input = [x.strip() for x in i.readlines()] + +test_data = """"""p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3"""""".split(""\n"") + +w, h = 101, 103 + +# w, h = 11, 7 +# input = test_data + +start_robots = [] +for l in input: + a, b, c, d = re.match(r""p=(-?\d+),(-?\d+) v=(-?\d+),(-?\d+)"", l).groups() + start_robots.append((int(a),int(b),int(c),int(d))) + +robots = start_robots +for i in range(100): + tmp = [] + for x, y, dx, dy in robots: + tmp.append(((x+dx) % w, (y+dy)%h, dx, dy)) + robots = tmp + +q1 = [(x,y,dx,dy) for x,y,dx,dy in robots if xh//2] +q3 = [(x,y,dx,dy) for x,y,dx,dy in robots if x>w//2 and yw//2 and y>h//2] + +print(len(q1)*len(q2)*len(q3)*len(q4))",python:3.9.21-slim +2024,14,2,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? + +Your puzzle answer was 219150360. + +--- Part Two --- + +During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"#!/usr/bin/env python3 + +import re +from collections import defaultdict + +myfile = open(""14.in"", ""r"") +lines = myfile.read().strip().splitlines() +myfile.close() + +part_one = 0 +part_two = 0 + +width = 101 +height = 103 +robots = [] +for line in lines: + p, v = line.split() + p = [int(x) for x in re.findall(r""-?\d+"", p)] + v = [int(x) for x in re.findall(r""-?\d+"", v)] + robots.append((p, v)) + +found_tree = False +for s in range(1, 10000): + if found_tree: + break + + grid = defaultdict(bool) + for i, r in enumerate(robots): + p, v = r + new_p = ((p[0] + v[0]) % width, (p[1] + v[1]) % height) + grid[new_p] = True + robots[i] = (new_p, v) + + if s == 100: + quad_1 = quad_2 = quad_3 = quad_4 = 0 + for r in robots: + mid_x = width // 2 + mid_y = height // 2 + + p = r[0] + if p[0] < mid_x and p[1] < mid_y: + quad_1 += 1 + elif p[0] > mid_x and p[1] < mid_y: + quad_2 += 1 + elif p[0] < mid_x and p[1] > mid_y: + quad_3 += 1 + elif p[0] > mid_x and p[1] > mid_y: + quad_4 += 1 + part_one = quad_1 * quad_2 * quad_3 * quad_4 + +print(""Part One:"", part_one)",python:3.9.21-slim +2024,14,2,"--- Day 14: Restroom Redoubt --- + +One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. + +Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. + +The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. + +The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? + +Your puzzle answer was 219150360. + +--- Part Two --- + +During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"from collections import defaultdict +import re + +def move_hundred_times(curr_x, curr_y, curr_vel_x, curr_vel_y, max_w, max_h): + pos_x = (100 * curr_vel_x + curr_x) % max_w + pos_y = (100 * curr_vel_y + curr_y) % max_h + + return pos_x, pos_y + + +def move_n_times(n, curr_x, curr_y, curr_vel_x, curr_vel_y, max_w, max_h): + pos_x = (n * curr_vel_x + curr_x) % max_w + pos_y = (n * curr_vel_y + curr_y) % max_h + + return pos_x, pos_y + + +positions = defaultdict(int) +# max_pos = (11, 7) +max_pos = (101, 103) + +start_pos = [] + +for line in open(""input.txt""): + x, y, v_x, v_y = re.findall(r""-?[0-9]+"", line) + + start_pos.append((int(x), int(y), int(v_x), int(v_y))) + + pos_x, pos_y = move_hundred_times(int(x), int(y), int(v_x), int(v_y), *max_pos) + + positions[(pos_x, pos_y)] += 1 + + +res = 1 +res *= sum(val for (x, y), val in positions.items() if x < (max_pos[0] - 1) // 2 and y < (max_pos[1] - 1) // 2) +res *= sum(val for (x, y), val in positions.items() if x < (max_pos[0] - 1) // 2 and y > (max_pos[1] - 1) // 2) +res *= sum(val for (x, y), val in positions.items() if x > (max_pos[0] - 1) // 2 and y < (max_pos[1] - 1) // 2) +res *= sum(val for (x, y), val in positions.items() if x > (max_pos[0] - 1) // 2 and y > (max_pos[1] - 1) // 2) + +print(res)",python:3.9.21-slim +2024,15,1,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"def get_next(pos, move): + move_dict = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} + return tuple(map(sum, zip(pos, move_dict[move]))) + + +grid = [] +moves = [] + +with open('input.txt') as f: + for line in f.read().splitlines(): + if line.startswith(""#""): + grid += [[c for c in line]] + + elif not line == """": + moves += [c for c in line] + +for i in range(len(grid)): + for j in range(len(grid)): + if grid[i][j] == '@': + robot_pos = (i, j) + break + +for move in moves: + next_i, next_j = get_next(robot_pos, move) + if grid[next_i][next_j] == '.': + grid[robot_pos[0]][robot_pos[1]] = '.' + grid[next_i][next_j] = '@' + robot_pos = (next_i, next_j) + elif grid[next_i][next_j] == 'O': + available = get_next((next_i, next_j), move) + while grid[available[0]][available[1]] == 'O': + available = get_next(available, move) + if grid[available[0]][available[1]] == '.': + grid[robot_pos[0]][robot_pos[1]] = '.' + grid[next_i][next_j] = '@' + grid[available[0]][available[1]] = 'O' + robot_pos = (next_i, next_j) + +total = 0 +for i in range(len(grid)): + for j in range(len(grid)): + if grid[i][j] == 'O': + total += 100 * i + j + +print(total) + + + + + + + +",python:3.9.21-slim +2024,15,1,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"pos = (0, 0) + +collision = {} + +directions = { + '<': (-1, 0), + '>': (1, 0), + '^': (0, -1), + 'v': (0, 1), +} + +commands = [] + + +def check_spot(position, directon): + if (item := collision.get(position)) is None: + return True + if item == 'Wall': + return False + return item.can_move(directon) + + +def can_move(position, direction): + x, y = position + dir = directions[direction] + + new_pos = (x + dir[0], y + dir[1]) + + return check_spot(new_pos, direction) + + +def move(position, direction): + dir = directions[direction] + return (position[0] + dir[0], position[1] + dir[1]) + + +class Box: + + def __init__(self, x, y): + self.x = x + self.y = y + + @property + def position(self): + return (self.x, self.y) + + def can_move(self, direction): + x, y = self.position + dir = directions[direction] + + new_pos = (x + dir[0], y + dir[1]) + + return check_spot(new_pos, direction) + + def move(self, direction): + dir = directions[direction] + + collision[self.position] = None + + self.x += dir[0] + self.y += dir[1] + + box = collision.get(self.position) + if isinstance(box, Box): + box.move(direction) + + collision[self.position] = self + + @property + def score(self): + return self.x + (self.y * 100) + + +with open('input.txt') as f: + has_read = False + for yi, line in enumerate(f): + if not has_read: + for xi, c in enumerate(line): + if len(line.strip()) == 0: + has_read = True + continue + if not has_read: + if c == '#': + collision[(xi, yi)] = ""Wall"" + elif c == '@': + pos = (xi, yi) + elif c == 'O': + box = Box(xi, yi) + collision[(xi, yi)] = box + else: + commands.append(line.strip()) + + commands = ''.join(commands) + + +def print_grid(): + mx, my = max(collision.keys()) + + grid = [['.'] * (mx + 1) for _ in range(my + 1)] + + for k, v in collision.items(): + if v is None: + continue + x, y = k + + if v == 'Wall': + grid[y][x] = '#' + elif isinstance(v, Box): + bx, by = v.position + grid[by][bx] = 'O' + + grid[pos[1]][pos[0]] = '@' + + print('\n'.join(''.join(x) for x in grid)) + + +for direction in commands: + if can_move(pos, direction): + pos = move(pos, direction) + if isinstance(collision.get(pos), Box): + collision[pos].move(direction) + +print_grid() + +boxes = set(collision[x] for x in collision if isinstance(collision[x], Box)) +print(sum(x.score for x in boxes)) +",python:3.9.21-slim +2024,15,1,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"import re +from typing import List, Tuple + +def parse_input(file_path: str) -> Tuple[List[List[str]], List[str]]: + with open(file_path, 'r') as file: + content = file.read().strip() + + grid_part, instructions_part = content.split('\n\n') + grid = [list(line) for line in grid_part.split('\n')] + instructions = list(''.join(instructions_part.split('\n'))) + + return grid, instructions + +def find_robot_position(grid: List[List[str]]) -> Tuple[int, int]: + for y, row in enumerate(grid): + for x, cell in enumerate(row): + if cell == '@': + return x, y + return -1, -1 + +def move_robot(grid: List[List[str]], instructions: List[str]) -> List[List[str]]: + direction_map = { + '^': (0, -1), + 'v': (0, 1), + '<': (-1, 0), + '>': (1, 0) + } + + x, y = find_robot_position(grid) + + for instruction in instructions: + dx, dy = direction_map[instruction] + new_x, new_y = x + dx, y + dy + + if not (0 <= new_x < len(grid[0]) and 0 <= new_y < len(grid)): + continue + if grid[new_y][new_x] == '#': + continue + elif grid[new_y][new_x] == 'O': + # Check if we can push the box + box_x, box_y = new_x, new_y + while 0 <= box_x + dx < len(grid[0]) and 0 <= box_y + dy < len(grid) and grid[box_y][box_x] == 'O': + box_x += dx + box_y += dy + if not (0 <= box_x + dx < len(grid[0]) and 0 <= box_y + dy < len(grid)) or grid[box_y][box_x] == '#': + break + else: + # Move the robot and push the boxes + while (box_x, box_y) != (new_x, new_y): + box_x -= dx + box_y -= dy + grid[box_y + dy][box_x + dx] = 'O' + grid[new_y][new_x] = '@' + grid[y][x] = '.' + x, y = new_x, new_y + else: + grid[new_y][new_x] = '@' + grid[y][x] = '.' + x, y = new_x, new_y + + return grid + +def calculate_gps_sum(grid: List[List[str]]) -> int: + gps_sum = 0 + for y, row in enumerate(grid): + for x, cell in enumerate(row): + if cell == 'O': + gps_sum += 100 * y + x + return gps_sum + +if __name__ == ""__main__"": + file_path = 'input.txt' + grid, instructions = parse_input(file_path) + + print(""Initial Grid:"") + for row in grid: + print(''.join(row)) + + grid = move_robot(grid, instructions) + + print(""\nFinal Grid:"") + for row in grid: + print(''.join(row)) + + gps_sum = calculate_gps_sum(grid) + print(f""\nSum of all boxes' GPS coordinates: {gps_sum}"")",python:3.9.21-slim +2024,15,1,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"input = open(""day_15\input.txt"", ""r"").read().splitlines() + +warehouse_map = [] +movements = """" +cur_pos = (0,0) +total = 0 + +movement_dict = { + ""v"": (1, 0), + ""^"": (-1, 0), + "">"": (0, 1), + ""<"": (0, -1) +} + +def find_open_spot(pos, move): + while True: + pos = tuple(map(sum, zip(pos, move))) + pos_value = warehouse_map[pos[0]][pos[1]] + if pos_value == ""#"": return False + elif pos_value == ""."": return pos + + +i = 0 +while input[i] != """": + if ""@"" in input[i]: + cur_pos = (i, input[i].index(""@"")) + warehouse_map.append(list(input[i])) + i += 1 + +i += 1 +while i < len(input): + movements += input[i] + i += 1 + +for move in movements: + destination = tuple(map(sum, zip(cur_pos, movement_dict[move]))) + destination_value = warehouse_map[destination[0]][destination[1]] + + if destination_value == ""O"": + open_spot = find_open_spot(destination, movement_dict[move]) + if open_spot: + warehouse_map[open_spot[0]][open_spot[1]] = ""O"" + warehouse_map[destination[0]][destination[1]] = ""@"" + warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" + cur_pos = destination + elif destination_value == ""."": + warehouse_map[destination[0]][destination[1]] = ""@"" + warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" + cur_pos = destination + +for i in range(len(warehouse_map)): + for j in range(len(warehouse_map[i])): + if warehouse_map[i][j] == ""O"": + total += 100 * i + j + +print(f""The sum of all boxes' GPS coordinates is {total}"") +",python:3.9.21-slim +2024,15,1,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"from collections import deque + +def find_start(grid, n, m): + for i in range(n): + for j in range(m): + if grid[i][j] == '@': + return (i, j) + return (0, 0) + +def in_bounds(i, j, n, m): + return (0 <= i < n) and (0 <= j < m) + +def move(grid, loc, dir, n, m): + curr = (loc[0], loc[1]) + addStack = deque() + addStack.append('@') + while True: + newPos = (curr[0] + dir[0], curr[1] + dir[1]) + if in_bounds(newPos[0], newPos[1], n, m): + val = grid[newPos[0]][newPos[1]] + if val == '#': + return loc + elif val == 'O': + addStack.append('O') + elif val == '.': + revDir = (-dir[0], -dir[1]) + while addStack: + movedVal = addStack.pop() + grid[newPos[0]] = grid[newPos[0]][:newPos[1]] + movedVal + grid[newPos[0]][newPos[1] + 1:] + newPos = (newPos[0] + revDir[0], newPos[1] + revDir[1]) + grid[loc[0]] = grid[loc[0]][:loc[1]] + '.' + grid[loc[0]][loc[1] + 1:] + return (loc[0] + dir[0], loc[1] + dir[1]) + else: + return loc + curr = (newPos[0], newPos[1]) + + +def get_box_coords(grid, instructions): + n = len(grid) + m = len(grid[0]) + loc = find_start(grid, n, m) + + dirMap = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} + for instruction in instructions: + loc = move(grid, loc, dirMap.get(instruction), n, m) + + total = 0 + for i in range(n): + for j in range(m): + if grid[i][j] == 'O': + total += ((100 * i) + j) + return total + +if __name__ == ""__main__"": + # Open file 'day15-1.txt' in read mode + with open('day15-1.txt', 'r') as f: + grid = [] + ended = False + instructions = [] + for line in f: + if line == '\n': + ended = True + line = line.strip() + if not ended: + grid.append(line) + else: + instructions.extend(list(line)) + + print(""Final Coordinates of Boxes: "" + str(get_box_coords(grid, instructions)))",python:3.9.21-slim +2024,15,2,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? + +Your puzzle answer was 1499739. + +--- Part Two --- + +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. + +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. + +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: + +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) + +The larger example from before would now look like this: + +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: + +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### + + bool: + return 0 <= y < len(self.grid) and 0 <= x < len(self.grid[y]) + + def is_wall(self, x: int, y: int) -> bool: + return self.is_valid(x, y) and self.grid[y][x] == ""#"" + + def is_box(self, x: int, y: int) -> bool: + if self.is_valid(x, y): + if self.grid[y][x] == ""O"": + return True + if self.grid[y][x] == ""["" or self.grid[y][x] == ""]"": + return True + return False + + def is_empty(self, x: int, y: int) -> bool: + return self.is_valid(x, y) and self.grid[y][x] == ""."" + + def get_robot_pos(self) -> tuple[int, int]: + if self.robot_pos != None: + return self.robot_pos + + for y in range(len(self.grid)): + for x in range(len(self.grid[y])): + if self.grid[y][x] == ""@"": + self.set_robot_pos(x, y) + return (x, y) + + return None + + def set_robot_pos(self, x: int, y: int): + self.robot_pos = (x, y) + + def swap(self, x1: int, y1: int, x2: int, y2: int): + if self.is_valid(x1, y1) and self.is_valid(x2, y2): + temp = self.grid[y1][x1] + self.grid[y1][x1] = self.grid[y2][x2] + self.grid[y2][x2] = temp + + def __str__(self): + out = """" + for row in self.grid: + line = """" + for val in row: + line += val + out += line + ""\n"" + return out + +def parse() -> tuple[Grid, str]: + grid_input, moves = open(""input.txt"").read().split(""\n\n"") + + grid = Grid([[val for val in line] for line in grid_input.splitlines()]) + return (grid, moves) + +def move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: + new_x, new_y = x + delta_x, y + delta_y + if grid.is_empty(new_x, new_y): + grid.swap(new_x, new_y, x, y) + return True + + if grid.is_box(new_x, new_y): + if move(grid, new_x, new_y, delta_x, delta_y): + grid.swap(new_x, new_y, x, y) + return True + else: + return False + + if grid.is_wall(new_x, new_y): + return False + return False + +def can_move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: + new_x, new_y = x + delta_x, y + delta_y + if grid.is_empty(new_x, new_y): + return True + + if grid.is_box(new_x, new_y): + possible_to_move = False + if delta_y != 0: + if grid.grid[new_y][new_x] == ""["": + possible_to_move |= can_move(grid, new_x + 1, new_y, delta_x, delta_y) + else: + possible_to_move |= can_move(grid, new_x - 1, new_y, delta_x, delta_y) + return possible_to_move and can_move(grid, new_x, new_y, delta_x, delta_y) + else: + return can_move(grid, new_x, new_y, delta_x, delta_y) + + if grid.is_wall(new_x, new_y): + return False + return False + +def wide_move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: + new_x, new_y = x + delta_x, y + delta_y + if grid.is_empty(new_x, new_y): + grid.swap(new_x, new_y, x, y) + return True + + if grid.is_box(new_x, new_y): + if delta_y != 0: + if grid.grid[new_y][new_x] == ""["": + wide_move(grid, new_x + 1, new_y, delta_x, delta_y) + else: + wide_move(grid, new_x - 1, new_y, delta_x, delta_y) + wide_move(grid, new_x, new_y, delta_x, delta_y) + grid.swap(new_x, new_y, x, y) + return True + + if grid.is_box(new_x, new_y): + return False + +def part1(): + grid, moves = parse() + + for robot_move in moves: + x, y = grid.get_robot_pos() + delta_x, delta_y = (1 if robot_move == "">"" else -1 if robot_move == ""<"" else 0, 1 if robot_move == ""v"" else -1 if robot_move == ""^"" else 0) + if move(grid, x, y, delta_x, delta_y): + grid.set_robot_pos(x + delta_x, y + delta_y) + + print(grid) + coords = [100 * y + x if grid.is_box(x, y) else 0 for y in range(len(grid.grid)) for x in range(len(grid.grid[y]))] + print(sum(coords)) + +def part2(): + grid, moves = parse() + new_grid = [[]] + for idx, row in enumerate(grid.grid): + new_grid.append([]) + for val in row: + if val == ""#"": + new_grid[idx].append(""#"") + new_grid[idx].append(""#"") + elif val == ""O"": + new_grid[idx].append(""["") + new_grid[idx].append(""]"") + elif val == ""."": + new_grid[idx].append(""."") + new_grid[idx].append(""."") + elif val == ""@"": + new_grid[idx].append(""@"") + new_grid[idx].append(""."") + grid.grid = new_grid + + for robot_move in moves: + x, y = grid.get_robot_pos() + delta_x, delta_y = (1 if robot_move == "">"" else -1 if robot_move == ""<"" else 0, 1 if robot_move == ""v"" else -1 if robot_move == ""^"" else 0) + if can_move(grid, x, y, delta_x, delta_y): + if wide_move(grid, x, y, delta_x, delta_y): + grid.set_robot_pos(x + delta_x, y + delta_y) + # print(grid) + + print(grid) + coords = [100 * y + x if grid.grid[y][x] == ""["" else 0 for y in range(len(grid.grid)) for x in range(len(grid.grid[y]))] + print(sum(coords)) + +part2()",python:3.9.21-slim +2024,15,2,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? + +Your puzzle answer was 1499739. + +--- Part Two --- + +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. + +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. + +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: + +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) + +The larger example from before would now look like this: + +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: + +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### + +': (0, 1), 'v': (1, 0), '<': (0, -1)} + return tuple(map(sum, zip(pos, move_dict[move]))) + +def get_chars(c): + if c == '@': + return '@.' + elif c == 'O': + return '[]' + else: + return c + c + +def can_push(grid, pos, move): + if move in ['<', '>']: + next_pos = get_next(get_next(pos, move), move) + if grid[next_pos[0]][next_pos[1]] == '.': + return True + + if grid[next_pos[0]][next_pos[1]] in ['[', ']']: + return can_push(grid, next_pos, move) + + return False + + if move in ['^', 'v']: + if grid[pos[0]][pos[1]] == '[': + left, right = (pos, (pos[0], pos[1] + 1)) + else: + left, right = ((pos[0], pos[1] - 1), pos) + + next_left = get_next(left, move) + next_right = get_next(right, move) + + if grid[next_left[0]][next_left[1]] == '#' or grid[next_right[0]][next_right[1]] == '#': + return False + + return (grid[next_left[0]][next_left[1]] == '.' or can_push(grid, next_left, move)) and (grid[next_right[0]][next_right[1]] == '.' or can_push(grid, next_right, move)) + +def push(grid, pos, move): + if move in ['<', '>']: + j = pos[1] + while grid[pos[0]][j] != '.': + _, j = get_next((pos[0], j), move) + if j < pos[1]: + grid[pos[0]][j:pos[1]] = grid[pos[0]][j+1:pos[1]+1] + else: + grid[pos[0]][pos[1]+1:j+1] = grid[pos[0]][pos[1]:j] + + if move in ['^', 'v']: + if grid[pos[0]][pos[1]] == '[': + left, right = (pos, (pos[0], pos[1] + 1)) + else: + left, right = ((pos[0], pos[1] - 1), pos) + + next_left = get_next(left, move) + next_right = get_next(right, move) + + if grid[next_left[0]][next_left[1]] == '[': + push(grid, next_left, move) + + else: + if grid[next_left[0]][next_left[1]] == ']': + push(grid, next_left, move) + + if grid[next_right[0]][next_right[1]] == '[': + push(grid, next_right, move) + + + grid[next_left[0]][next_left[1]] = '[' + grid[next_right[0]][next_right[1]] = ']' + grid[left[0]][left[1]] = '.' + grid[right[0]][right[1]] = '.' + + +def print_grid(grid): + for line in grid: + print("""".join(line)) + + + +grid = [] +moves = [] + +with open('input.txt') as f: + for line in f.read().splitlines(): + if line.startswith(""#""): + row = """" + for c in line: + row += get_chars(c) + grid += [[c for c in row]] + + elif not line == """": + moves += [c for c in line] + +for i in range(len(grid)): + for j in range(len(grid[i])): + if grid[i][j] == '@': + robot_pos = (i, j) + break + +for move in moves: + next_i, next_j = get_next(robot_pos, move) + if grid[next_i][next_j] == '.': + grid[robot_pos[0]][robot_pos[1]] = '.' + grid[next_i][next_j] = '@' + robot_pos = (next_i, next_j) + elif grid[next_i][next_j] in ['[', ']']: + if can_push(grid, (next_i, next_j), move): + push(grid, (next_i, next_j), move) + grid[robot_pos[0]][robot_pos[1]] = '.' + grid[next_i][next_j] = '@' + robot_pos = (next_i, next_j) + + +total = 0 +for i in range(len(grid)): + for j in range(len(grid[i])): + if grid[i][j] == '[': + total += 100 * i + j + +print(total) + + + + + + + +",python:3.9.21-slim +2024,15,2,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? + +Your puzzle answer was 1499739. + +--- Part Two --- + +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. + +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. + +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: + +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) + +The larger example from before would now look like this: + +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: + +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### + += width or y < 0 or y >= height: + return False + + if (x, y) in walls: + return False + + # horizontal move: + if move[1] == 0: + # left move: + if move[0] == -1: + if (x + move[0], x, y) in boxes: + # need to move (x + move[0], x, y) box to left + to_move.add((x + move[0], x, y)) + return can_move(x + move[0], y, move, width, height, to_move) + # right move + else: + if (x, x + move[0], y) in boxes: + to_move.add((x, x + move[0], y)) + return can_move(x + move[0], y, move, width, height, to_move) + + # vertical move: + if move[0] == 0: + if (x - 1, x, y) in boxes: + to_move.add((x - 1, x, y)) + return can_move(x - 1, y, move, width, height, to_move) and can_move(x, y, move, width, height, to_move) + if (x, x + 1, y) in boxes: + to_move.add((x, x + 1, y)) + return can_move(x, y, move, width, height, to_move) and can_move(x + 1, y, move, width, height, to_move) + + return True + +def move_robot(x, y, width, height): + for move in moves: + to_move = set() + if can_move(x, y, move, width, height, to_move): + for each in to_move: + boxes.remove(each) + for each in to_move: + boxes.add((each[0] + move[0], each[1] + move[0], each[2] + move[1])) + x += move[0] + y += move[1] + + +def main(): + warehouse_done = False + robot_x = 0 + robot_y = 0 + width = 0 + height = 0 + y = 0 + with open(""15_input.txt"", ""r"") as f: + for line in f: + line = line.strip() + if line != """": + if warehouse_done: + moves.extend([char_map[c] for c in line]) + else: + x = 0 + for char in line: + if char == '#': + walls.append((x, y)) + walls.append((x + 1, y)) + elif char == ""O"": + boxes.add((x, x + 1, y)) + elif char == ""@"": + robot_x = x + robot_y = y + x += 2 + if x > width: + width = x + else: + warehouse_done = True + if not warehouse_done: + y += 1 + if y > height: + height = y + + + move_robot(robot_x, robot_y, width, height) + result = 0 + for box in boxes: + result += 100 * box[2] + box[0] + + print(result) + + +char_map = {""^"": (0, -1), + "">"": (1, 0), + ""<"": (-1, 0), + ""v"": (0, 1)} +walls = [] +boxes = set() +moves = [] + +if __name__ == ""__main__"": + main()",python:3.9.21-slim +2024,15,2,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? + +Your puzzle answer was 1499739. + +--- Part Two --- + +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. + +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. + +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: + +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) + +The larger example from before would now look like this: + +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: + +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### + +"": (1, 0), ""^"": (0, -1), ""v"": (0, 1)} + + +class Warehouse: + def __init__(self, width): + self.width = width + self.robot_location = (0, 0) + self.walls = [] + self.boxes = {} + self.moves = [] + + def print(self): + for y in range(self.height): + for x in range(self.width): + p = (x, y) + if p == self.robot_location: + print(ROBOT, end="""") + elif p in self.boxes: + print(self.boxes[p], end="""") + elif p in self.walls: + print(WALL, end="""") + else: + print(""."", end="""") + print() + + def add_wall(self, wall): + wall_position = (wall[0] * 2, wall[1]) + self.walls.append(wall_position) + self.walls.append((wall_position[0] + 1, wall_position[1])) + + def add_box(self, box): + box_position = (box[0] * 2, box[1]) + self.boxes[box_position] = BOX_LEFT + self.boxes[(box_position[0] + 1, box_position[1])] = BOX_RIGHT + + def set_robot_location(self, location): + self.robot_location = (location[0] * 2, location[1]) + + def set_height(self, height): + self.height = height + + def print_moves(self): + for move in self.moves: + print(move) + + def move(self, move): + dx, dy = MOVES[move] + new_location = (self.robot_location[0] + dx, self.robot_location[1] + dy) + if new_location in self.walls: + return + if new_location in self.boxes: + self.move_box(new_location, move) + if new_location in self.boxes or new_location in self.walls: + return + self.robot_location = new_location + + def move_box(self, box, move): + dx, dy = MOVES[move] + + if self.boxes[box] == BOX_RIGHT: + box_left = (box[0] - 1, box[1]) + box_right = box + new_box_left = (box_left[0] + dx, box_left[1] + dy) + new_box_right = (box_right[0] + dx, box_right[1] + dy) + else: + box_left = box + box_right = (box[0] + 1, box[1]) + new_box_left = (box_left[0] + dx, box_left[1] + dy) + new_box_right = (box_right[0] + dx, box_right[1] + dy) + + # if horizontal + if move == ""<"" or move == "">"": + if self.boxes[box] == BOX_RIGHT: + if new_box_left in self.walls or new_box_right in self.walls: + return False + if new_box_right != box_left: + if new_box_left in self.boxes or new_box_right in self.boxes: + if not self.move_box(new_box_left, move): + return False + if new_box_left in self.boxes: + if not self.move_box(new_box_left, move): + return False + self.boxes.pop(box_left) + self.boxes.pop(box_right) + self.boxes[new_box_left] = BOX_LEFT + self.boxes[new_box_right] = BOX_RIGHT + elif self.boxes[box] == BOX_LEFT: + if new_box_left in self.walls or new_box_right in self.walls: + return False + if new_box_left != box_right: + if new_box_left in self.boxes or new_box_right in self.boxes: + if not self.move_box(new_box_right, move): + return False + if new_box_right in self.boxes: + if not self.move_box(new_box_right, move): + return False + self.boxes.pop(box_left) + self.boxes.pop(box_right) + self.boxes[new_box_left] = BOX_LEFT + self.boxes[new_box_right] = BOX_RIGHT + else: + if self.collision_check(box, move): + return False + if new_box_left in self.walls or new_box_right in self.walls: + return False + if new_box_left in self.boxes: + if not self.move_box(new_box_left, move): + return False + if new_box_right in self.boxes: + if not self.move_box(new_box_right, move): + return False + self.boxes.pop(box_left) + self.boxes.pop(box_right) + self.boxes[new_box_left] = BOX_LEFT + self.boxes[new_box_right] = BOX_RIGHT + + return True + + def collision_check(self, box, move): + collision = False + dx, dy = MOVES[move] + + if self.boxes[box] == BOX_RIGHT: + box_left = (box[0] - 1, box[1]) + box_right = box + new_box_left = (box_left[0] + dx, box_left[1] + dy) + new_box_right = (box_right[0] + dx, box_right[1] + dy) + else: + box_left = box + box_right = (box[0] + 1, box[1]) + new_box_left = (box_left[0] + dx, box_left[1] + dy) + new_box_right = (box_right[0] + dx, box_right[1] + dy) + if new_box_left in self.walls or new_box_right in self.walls: + return True + if new_box_left in self.boxes: + if self.collision_check(new_box_left, move): + return True + if new_box_right in self.boxes: + if self.collision_check(new_box_right, move): + return True + return collision + + def run(self): + for move in self.moves: + self.move(move) + + def sum_of_box_locations(self): + result = 0 + for x, y in self.boxes: + if self.boxes[(x, y)] == BOX_LEFT: + result += x + 100 * y + return result + + +def read_file(): + with open(INPUT_FILE, ""r"") as f: + lines = f.readlines() + width = len(lines[0].strip()) * 2 + warehouse = Warehouse(width) + moves = [] + for y, line in enumerate(lines): + if line[0] == ""#"": + for x, c in enumerate(line.strip()): + p = (x, y) + if c == WALL: + warehouse.add_wall(p) + elif c == ROBOT: + warehouse.set_robot_location(p) + elif c == BOX: + warehouse.add_box(p) + elif line[0] == ""\n"": + warehouse.set_height(y) + else: + for move in line.strip(): + moves.append(move) + + warehouse.moves = moves + + return warehouse + + +warehouse = read_file() + +warehouse.print() +warehouse.run() +print(warehouse.sum_of_box_locations()) +",python:3.9.21-slim +2024,15,2,"--- Day 15: Warehouse Woes --- + +You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: + +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) + +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. + +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. + +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? + +Your puzzle answer was 1499739. + +--- Part Two --- + +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. + +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. + +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: + +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) + +The larger example from before would now look like this: + +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: + +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### + +"": (0, 1), + ""<"": (0, -1) +} + +def move_horizontally(pos, move): + while True: + pos = tuple(map(sum, zip(pos, move))) + pos_value = warehouse_map[pos[0]][pos[1]] + if pos_value == ""#"": return False + elif pos_value == ""."": + if move[1] == 1: + warehouse_map[pos[0]][pos[1]] = ""]"" + else: warehouse_map[pos[0]][pos[1]] = ""["" + + while warehouse_map[pos[0]][pos[1] - move[1]] != ""@"": + pos = (pos[0], pos[1] - move[1]) + warehouse_map[pos[0]][pos[1]] = ""]"" if warehouse_map[pos[0]][pos[1]] == ""["" else ""["" + return True + +def move_vertically(positions, move): + involved_boxes = set(positions) + next_positions = set(positions) + while True: + involved_boxes |= next_positions + if len(next_positions) == 0: + boxes_dict = {(x,y): warehouse_map[x][y] for (x,y) in involved_boxes} + for box in involved_boxes: + if not (box[0] - move[0], box[1]) in boxes_dict: + warehouse_map[box[0]][box[1]] = ""."" + warehouse_map[box[0] + move[0]][box[1]] = boxes_dict[box] + return True + positions = next_positions.copy() + next_positions.clear() + for pos in positions: + next_pos = tuple(map(sum, zip(pos, move))) + next_pos_value = warehouse_map[next_pos[0]][next_pos[1]] + if next_pos_value == ""["": + next_positions.add(next_pos) + next_positions.add((next_pos[0], next_pos[1] + 1)) + elif next_pos_value == ""]"": + next_positions.add(next_pos) + next_positions.add((next_pos[0], next_pos[1] - 1)) + elif next_pos_value == ""#"": + return False + + +i = 0 +while input[i] != """": + modified_input = [] + for char in input[i]: + if char == ""#"": + modified_input += [""#"", ""#""] + elif char == ""O"": + modified_input += [""["", ""]""] + elif char == ""."": + modified_input += [""."", "".""] + else: + modified_input += [""@"", "".""] + cur_pos = (i, modified_input.index(""@"")) + + warehouse_map.append(modified_input) + i += 1 + +i += 1 +while i < len(input): + movements += input[i] + i += 1 + +for move in movements: + destination = tuple(map(sum, zip(cur_pos, movement_dict[move]))) + destination_value = warehouse_map[destination[0]][destination[1]] + + if destination_value == ""["" or destination_value == ""]"": + if move == ""<"" or move == "">"": + open_spot = move_horizontally(destination, movement_dict[move]) + else: + if destination_value == ""["": + open_spot = move_vertically([destination, (destination[0], destination[1] + 1)], movement_dict[move]) + else: open_spot = move_vertically([destination, (destination[0], destination[1] - 1)], movement_dict[move]) + if open_spot: + warehouse_map[destination[0]][destination[1]] = ""@"" + warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" + cur_pos = destination + elif destination_value == ""."": + warehouse_map[destination[0]][destination[1]] = ""@"" + warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" + cur_pos = destination + +for i in range(len(warehouse_map)): + for j in range(len(warehouse_map[i])): + if warehouse_map[i][j] == ""["": + total += 100 * i + j + +print(f""The sum of all boxes' final GPS coordinates is {total}"") +",python:3.9.21-slim +2024,16,1,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"from heapq import heappop, heappush + +def get_lowest_score(maze): + m = len(maze) + n = len(maze[0]) + start = (-1, -1) + end = (-1, -1) + for i in range(m): + for j in range(n): + if maze[i][j] == 'S': + start = (i, j) + elif maze[i][j] == 'E': + end = (i, j) + + maze[end[0]][end[1]] = '.' + dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] + visited = set() + heap = [(0, 0, *start)] + + while heap: + score, dI, i, j = heappop(heap) + if (i, j) == end: + break + + if (dI, i, j) in visited: + continue + + visited.add((dI, i, j)) + + x = i + dirs[dI][0] + y = j + dirs[dI][1] + + if maze[x][y] == '.' and (dI, x, y) not in visited: + heappush(heap, (score + 1, dI, x, y)) + + left = (dI - 1) % 4 + if (left, i, j) not in visited: + heappush(heap, (score + 1000, left, i, j)) + + right = (dI + 1) % 4 + if (right, i, j) not in visited: + heappush(heap, (score + 1000, right, i, j)) + + return score + +if __name__ == ""__main__"": + # Open file 'day16-1.txt' in read mode + with open('day16-1.txt', 'r') as f: + maze = [] + for line in f: + line = line.strip() + maze.append(list(line)) + + print(""Lowest Score:"", get_lowest_score(maze))",python:3.9.21-slim +2024,16,1,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"import heapq + +def dijkstra(grid): + for i in range(len(grid)): + for j in range(len(grid[i])): + if grid[i][j] == 'S': + start = ((i, j), (0, 1)) + + pq = [(0, start)] + costs = { start: 0 } + + while len(pq) > 0: + cost, (pos, direction) = heapq.heappop(pq) + + if grid[pos[0]][pos[1]] == 'E': + return cost + + turns = [(1000, (pos, turn)) for turn in [(direction[1] * i, direction[0] * i) for i in [-1,1]]] + + step = tuple(map(sum, zip(pos, direction))) + + neighbors = turns + ([(1, (step, direction))] if grid[step[0]][step[1]] != '#' else []) + for neighbor in neighbors: + next_cost = cost + neighbor[0] + if next_cost < costs.get(neighbor[1], float('inf')): + heapq.heappush(pq, (next_cost, neighbor[1])) + costs[neighbor[1]] = next_cost + + print(""Could not find min path"") + return None + + + + +with open('input.txt') as f: + grid = [[c for c in line] for line in f.read().splitlines()] + +print(dijkstra(grid)) + + +",python:3.9.21-slim +2024,16,1,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"# Python heap implementation +from heapq import heappush, heappop + +with open(""./day_16.in"") as fin: + grid = fin.read().strip().split(""\n"") + +n = len(grid) +for i in range(n): + for j in range(n): + if grid[i][j] == ""S"": + start = (i, j) + elif grid[i][j] == ""E"": + end = (i, j) + +dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] + +# DIjkstra's +q = [(0, 0, *start)] +seen = set() +while len(q) > 0: + top = heappop(q) + cost, d, i, j = top + if (d, i, j) in seen: + continue + seen.add((d, i, j)) + + if grid[i][j] == ""#"": + continue + + if grid[i][j] == ""E"": + print(cost) + break + + ii = i + dd[d][0] + jj = j + dd[d][1] + + for nbr in [(cost + 1, d, ii, jj), + (cost + 1000, (d + 1) % 4, i, j), + (cost + 1000, (d + 3) % 4, i, j)]: + if nbr[1:] in seen: + continue + heappush(q, nbr) +",python:3.9.21-slim +2024,16,1,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"import re +from typing import List, Tuple +import heapq + +def parse_input(file_path: str): + """""" + Parse the input file to extract the data. + + Args: + file_path (str): The path to the input file. + + Returns: + List[str]: A list of strings representing the data from the file. + """""" + with open(file_path, 'r') as file: + return [line.strip() for line in file] + +def find_starting_position(grid: List[str]) -> Tuple[int, int]: + """""" + Find the starting position marked as 'S' in the grid. + + Args: + grid (List[str]): A list of strings representing the grid. + + Returns: + Tuple[int, int]: A tuple containing the row and column indices of the starting position. + """""" + for i, row in enumerate(grid): + for j, cell in enumerate(row): + if cell == 'S': + return i, j + return -1, -1 + +# given a grid and a current position as well as a direction, +# return the list of next possible moves either moving forward in the current direction or turning left or right +def get_possible_moves(grid: List[str], i: int, j: int, direction: str) -> List[Tuple[int, int, str]]: + """""" + Get the possible moves from the current position in the grid. + + Args: + grid (List[str]): A list of strings representing the grid. + i (int): The row index of the current position. + j (int): The column index of the current position. + direction (str): The current direction ('N', 'E', 'S', 'W'). + + Returns: + List[Tuple[int, int, str]]: A list of tuples where each tuple contains the row index, column index, and the direction of the possible moves. + """""" + rows, cols = len(grid), len(grid[0]) + moves = {'N': (-1, 0), 'E': (0, 1), 'S': (1, 0), 'W': (0, -1)} + left_turns = {'N': 'W', 'E': 'N', 'S': 'E', 'W': 'S'} + right_turns = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'} + possible_moves = [] + + # Check forward move + dx, dy = moves[direction] + new_i, new_j = i + dx, j + dy + if 0 <= new_i < rows and 0 <= new_j < cols and grid[new_i][new_j] != '#': + possible_moves.append((new_i, new_j, direction)) + + # Check left turn + left_direction = left_turns[direction] + left_dx, left_dy = moves[left_direction] + left_i, left_j = i + left_dx, j + left_dy + if 0 <= left_i < rows and 0 <= left_j < cols and grid[left_i][left_j] != '#': + possible_moves.append((i, j, left_direction)) + + # Check right turn + right_direction = right_turns[direction] + right_dx, right_dy = moves[right_direction] + right_i, right_j = i + right_dx, j + right_dy + if 0 <= right_i < rows and 0 <= right_j < cols and grid[right_i][right_j] != '#': + possible_moves.append((i, j, right_direction)) + + return possible_moves + +def find_lowest_score(grid: List[str], i: int, j: int, direction: str) -> int: + """""" + Finds the shortest path in a grid from a starting position (i, j) in a given direction. + + Args: + grid (List[str]): A 2D grid represented as a list of strings. + i (int): The starting row index. + j (int): The starting column index. + direction (str): The initial direction of movement. + + Returns: + int: The shortest path score to reach the target 'E' in the grid. If the target is not reachable, returns float('inf'). + """""" + visited = set() + heap = [(0, i, j, direction)] # (score, row, col, direction) + while heap: + score, i, j, direction = heapq.heappop(heap) + if (i, j, direction) in visited: + continue + visited.add((i, j, direction)) + if grid[i][j] == 'E': + return score + for new_i, new_j, new_direction in get_possible_moves(grid, i, j, direction): + new_score = score + 1 if new_direction == direction else score + 1000 + heapq.heappush(heap, (new_score, new_i, new_j, new_direction)) + return float('inf') + +if __name__ == ""__main__"": + file_path = 'input.txt' + parsed_data = parse_input(file_path) + i, j = find_starting_position(parsed_data) + score = find_lowest_score(parsed_data, i, j, 'E') + print(score)",python:3.9.21-slim +2024,16,1,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"# Python heap implementation +from heapq import heappush, heappop +from collections import defaultdict + +with open(""16.in"") as fin: + grid = fin.read().strip().split(""\n"") + +n = len(grid) +for i in range(n): + for j in range(n): + if grid[i][j] == ""S"": + start = (i, j) + elif grid[i][j] == ""E"": + end = (i, j) + +dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] + +# Dijkstra's +q = [(0, 0, *start, 0, *start)] +cost = {} +deps = defaultdict(list) +while len(q) > 0: + top = heappop(q) + c, d, i, j, pd, pi, pj = top + if (d, i, j) in cost: + if cost[(d, i, j)] == c: + deps[(d, i, j)].append((pd, pi, pj)) + continue + + never_seen_pos = True + for newd in range(4): + if (newd, i, j) in cost: + never_seen_pos = True + break + if never_seen_pos: + deps[(d, i, j)].append((pd, pi, pj)) + + cost[(d, i, j)] = c + + + if grid[i][j] == ""#"": + continue + + if grid[i][j] == ""E"": + end_dir = d + print(c) + break + + ii = i + dd[d][0] + jj = j + dd[d][1] + + for nbr in [(c + 1, d, ii, jj, d, i, j), + (c + 1000, (d + 1) % 4, i, j, d, i, j), + (c + 1000, (d + 3) % 4, i, j, d, i, j)]: + heappush(q, nbr) + +",python:3.9.21-slim +2024,16,2,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? + +Your puzzle answer was 94444. + +--- Part Two --- + +Now that you know what the best paths look like, you can figure out the best spot to sit. + +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! + +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"# Python heap implementation +from heapq import heappush, heappop +from collections import defaultdict + +with open(""16.in"") as fin: + grid = fin.read().strip().split(""\n"") + +n = len(grid) +for i in range(n): + for j in range(n): + if grid[i][j] == ""S"": + start = (i, j) + elif grid[i][j] == ""E"": + end = (i, j) + +dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] + +# Dijkstra's +q = [(0, 0, *start, 0, *start)] +cost = {} +deps = defaultdict(list) +while len(q) > 0: + top = heappop(q) + c, d, i, j, pd, pi, pj = top + if (d, i, j) in cost: + if cost[(d, i, j)] == c: + deps[(d, i, j)].append((pd, pi, pj)) + continue + + never_seen_pos = True + for newd in range(4): + if (newd, i, j) in cost: + never_seen_pos = True + break + if never_seen_pos: + deps[(d, i, j)].append((pd, pi, pj)) + + cost[(d, i, j)] = c + + + if grid[i][j] == ""#"": + continue + + if grid[i][j] == ""E"": + end_dir = d + break + + ii = i + dd[d][0] + jj = j + dd[d][1] + + for nbr in [(c + 1, d, ii, jj, d, i, j), + (c + 1000, (d + 1) % 4, i, j, d, i, j), + (c + 1000, (d + 3) % 4, i, j, d, i, j)]: + heappush(q, nbr) + +# Go back through deps +stack = [(end_dir, *end)] +seen = set() +seen_pos = set() +while len(stack) > 0: + top = stack.pop() + if top in seen: + continue + seen.add(top) + seen_pos.add(top[1:]) + + for nbr in deps[top]: + stack.append(nbr) + +print(len(seen_pos))",python:3.9.21-slim +2024,16,2,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? + +Your puzzle answer was 94444. + +--- Part Two --- + +Now that you know what the best paths look like, you can figure out the best spot to sit. + +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! + +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"#d16 part 2 + +from heapq import heappop, heappush + + +def part2(puzzle_input): + grid = puzzle_input.split('\n') + m, n = len(grid), len(grid[0]) + for i in range(m): + for j in range(n): + if grid[i][j] == 'S': + start = (i, j) + elif grid[i][j] == 'E': + end = (i, j) + + grid[end[0]] = grid[end[0]].replace('E', '.') + + def can_visit(d, i, j, score): + prev_score = visited.get((d, i, j)) + if prev_score and prev_score < score: + return False + visited[(d, i, j)] = score + return True + + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] + heap = [(0, 0, *start, {start})] + visited = {} + lowest_score = None + winning_paths = set() + while heap: + score, d, i, j, path = heappop(heap) + if lowest_score and lowest_score < score: + break + + if (i, j) == end: + lowest_score = score + winning_paths |= path + continue + + if not can_visit(d, i, j, score): + continue + + x = i + directions[d][0] + y = j + directions[d][1] + if grid[x][y] == '.' and can_visit(d, x, y, score+1): + heappush(heap, (score + 1, d, x, y, path | {(x, y)})) + + left = (d - 1) % 4 + if can_visit(left, i, j, score + 1000): + heappush(heap, (score + 1000, left, i, j, path)) + + right = (d + 1) % 4 + if can_visit(right, i, j, score + 1000): + heappush(heap, (score + 1000, right, i, j, path)) + + return len(winning_paths) + + +with open(r'16.txt','r') as f: + input_text = f.read() + +res = part2(input_text) +res",python:3.9.21-slim +2024,16,2,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? + +Your puzzle answer was 94444. + +--- Part Two --- + +Now that you know what the best paths look like, you can figure out the best spot to sit. + +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! + +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import heapq +from sys import maxsize + +maze = open(""16.txt"").read().splitlines() + +seen = [[[maxsize for _ in range(4)] for x in range(len(maze[0]))] for y in range(len(maze))] + +velocities = [(-1, 0), (0, 1), (1, 0), (0, -1)] + +start_pos = None +end_pos = None +for j, r in enumerate(maze): + for i, c in enumerate(r): + if c == 'S': + start_pos = (j, i) + if c == 'E': + end_pos = (j, i) + +# TODO For C, need a better track of path than shoving it all into a list lmao +# I saw on da reddit a lot of folks searching backwards through the maze scores +# for all scores where score is -1 or -1001 from current, starting at end. +pq = [(0, (*start_pos, 1), [start_pos])] # start facing EAST +paths = [] +best_score = maxsize + +while pq and pq[0][0] <= best_score: + score, (y, x, dir), path = heapq.heappop(pq) + + if (y, x) == end_pos: + best_score = score + paths.append(path) + continue + + if seen[y][x][dir] < score: + continue + seen[y][x][dir] = score + + for i in range(4): + dy, dx = velocities[i] + ny, nx = y + dy, x + dx + if maze[ny][nx] != '#' and (ny, nx) not in path: + cost = 1 if i == dir else 1001 + heapq.heappush(pq, (score + cost, (ny, nx, i), path + [(ny, nx)])) + +seats = set() +for path in paths: + seats |= set(path) +print(len(seats))",python:3.9.21-slim +2024,16,2,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? + +Your puzzle answer was 94444. + +--- Part Two --- + +Now that you know what the best paths look like, you can figure out the best spot to sit. + +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! + +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import heapq +from typing import Dict, List, Tuple + + +class MinHeap: + """""" + Min heap implementation using heapq library + """""" + + def __init__(self): + self.heap = [] + + def insert(self, element: Tuple[int, str]): + heapq.heappush(self.heap, element) + + def extract_min(self) -> Tuple[int, str]: + return heapq.heappop(self.heap) + + def size(self) -> int: + return len(self.heap) + + +DIRECTIONS = [ + {""x"": 1, ""y"": 0}, + {""x"": 0, ""y"": 1}, + {""x"": -1, ""y"": 0}, + {""x"": 0, ""y"": -1}, +] + + +def dijkstra( + graph: Dict[str, Dict[str, int]], start: Dict[str, int], directionless: bool +) -> Dict[str, int]: + queue = MinHeap() + distances = {} + + starting_key = ( + f""{start['x']},{start['y']},0"" + if not directionless + else f""{start['x']},{start['y']}"" + ) + queue.insert((0, starting_key)) + distances[starting_key] = 0 + + while queue.size() > 0: + current_score, current_node = queue.extract_min() + + if distances[current_node] < current_score: + continue + + if current_node not in graph: + continue + + for next_node, weight in graph[current_node].items(): + new_score = current_score + weight + if next_node not in distances or distances[next_node] > new_score: + distances[next_node] = new_score + queue.insert((new_score, next_node)) + + return distances + + +def parse_grid(grid: List[str]): + width, height = len(grid[0]), len(grid) + + start = {""x"": 0, ""y"": 0} + end = {""x"": 0, ""y"": 0} + forward = {} + reverse = {} + + for y in range(height): + for x in range(width): + if grid[y][x] == ""S"": + start = {""x"": x, ""y"": y} + if grid[y][x] == ""E"": + end = {""x"": x, ""y"": y} + + if grid[y][x] != ""#"": + for i, direction in enumerate(DIRECTIONS): + position = {""x"": x + direction[""x""], ""y"": y + direction[""y""]} + + key = f""{x},{y},{i}"" + move_key = f""{position['x']},{position['y']},{i}"" + + if ( + 0 <= position[""x""] < width + and 0 <= position[""y""] < height + and grid[position[""y""]][position[""x""]] != ""#"" + ): + forward.setdefault(key, {})[move_key] = 1 + reverse.setdefault(move_key, {})[key] = 1 + + for rotate_key in [ + f""{x},{y},{(i + 3) % 4}"", + f""{x},{y},{(i + 1) % 4}"", + ]: + forward.setdefault(key, {})[rotate_key] = 1000 + reverse.setdefault(rotate_key, {})[key] = 1000 + + for i in range(len(DIRECTIONS)): + key = f""{end['x']},{end['y']}"" + rotate_key = f""{end['x']},{end['y']},{i}"" + + forward.setdefault(rotate_key, {})[key] = 0 + reverse.setdefault(key, {})[rotate_key] = 0 + + return {""start"": start, ""end"": end, ""forward"": forward, ""reverse"": reverse} + + +def tilesApartFromMaze() -> int: + with open(""input.txt"") as file: + con = file.read() + grid = con.strip().split(""\n"") + parsed = parse_grid(grid) + + from_start = dijkstra(parsed[""forward""], parsed[""start""], False) + to_end = dijkstra(parsed[""reverse""], parsed[""end""], True) + + end_key = f""{parsed['end']['x']},{parsed['end']['y']}"" + target = from_start[end_key] + spaces = set() + + for position in from_start: + if ( + position != end_key + and from_start[position] + to_end.get(position, float(""inf"")) == target + ): + x, y, *_ = position.split("","") # Unpack and ignore direction in the key + spaces.add(f""{x},{y}"") + print(len(spaces)) + + +tilesApartFromMaze()",python:3.9.21-slim +2024,16,2,"--- Day 16: Reindeer Maze --- + +It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? + +Your puzzle answer was 94444. + +--- Part Two --- + +Now that you know what the best paths look like, you can figure out the best spot to sit. + +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! + +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import time +from collections import deque + +POSSIBLE_DIRS = (1, -1, 1j, -1j) + + +def calculate_min_scores( + start: complex, walls: set[complex] +) -> dict[complex, dict[complex, int]]: + scores = {1: {start: 0}, -1: {}, 1j: {}, -1j: {}} + points = deque([(start, 1)]) + while points: + p, d = points.popleft() + score = scores[d][p] + for move, dir, cost in [(p + d, d, 1), (p, d * -1j, 1000), (p, d * 1j, 1000)]: + if move in walls: + continue + if move in scores[dir] and scores[dir][move] <= score + cost: + continue + scores[dir][move] = score + cost + points.append((move, dir)) + return scores + + +def parse(text: str): + walls: set[complex] = set() + start: complex = 0j + end: complex = 0j + for y, row in enumerate(text.splitlines()): + for x, c in enumerate(row): + match c: + case ""#"": + walls.add(complex(x, y)) + case ""S"": + start = complex(x, y) + case ""E"": + end = complex(x, y) + case _: + pass + return start, end, walls + + +def solve_part_2(text: str): + start, end, walls = parse(text) + scores = calculate_min_scores(start, walls) + path: set[complex] = {start, end} + cost = min(scores[dir][end] for dir in POSSIBLE_DIRS if end in scores[dir]) + points = deque( + [ + (end, dir, cost) + for dir in POSSIBLE_DIRS + if end in scores[dir] and scores[dir][end] == cost + ] + ) + while points: + p, d, cost = points.popleft() + for move, dir, c1 in [ + (p - d, d, cost - 1), + (p, d * 1j, cost - 1000), + (p, d * -1j, cost - 1000), + ]: + if move in scores[dir] and scores[dir][move] == c1: + path.add(move) + points.append((move, dir, c1)) + return len(path) + + +if __name__ == ""__main__"": + with open(""input.txt"", ""r"") as f: + quiz_input = f.read() + p_2_solution = int(solve_part_2(quiz_input))",python:3.9.21-slim +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","ADV = 0 +BXL = 1 +BST = 2 +JNZ = 3 +BXC = 4 +OUT = 5 +BDV = 6 +CDV = 7 + +def get_combo_operand(operand, reg): + if 0 <= operand <= 3: + return operand + + if 4 <= operand <= 6: + return reg[chr(ord('A') + operand - 4)] + + raise ValueError(f""Unexpected operand {operand}"") + +with open('input.txt') as f: + lines = f.read().splitlines() + +reg = { 'A': int(lines[0].split("": "")[1]), 'B': int(lines[1].split("": "")[1]), 'C': int(lines[2].split("": "")[1])} +instructions = list(map(int, lines[4].split("": "")[1].split("",""))) + +output = [] +instr_ptr = 0 + +while instr_ptr < len(instructions): + jump = False + opcode, operand = instructions[instr_ptr:instr_ptr + 2] + + if opcode == ADV: + reg['A'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) + + elif opcode == BXL: + reg['B'] = reg['B'] ^ operand + + elif opcode == BST: + reg['B'] = get_combo_operand(operand, reg) % 8 + + elif opcode == JNZ: + if reg['A'] != 0: + instr_ptr = operand + jump = True + + elif opcode == BXC: + reg['B'] = reg['B'] ^ reg['C'] + + elif opcode == OUT: + output += [get_combo_operand(operand, reg) % 8] + + elif opcode == BDV: + reg['B'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) + + elif opcode == CDV: + reg['C'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) + + else: + raise ValueError(f""Unexpected opcode {opcode}"") + + if not jump: + instr_ptr += 2 + +print("","".join(map(str, output)))",python:3.9.21-slim +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","from collections.abc import Generator + + +def get_out(a: int) -> int: + b = (a % 8) ^ 1 + return (b ^ (a // 2**b) ^ 4) % 8 + + +def get_all_out(a: int) -> list[int]: + out: list[int] = [] + while a > 0: + out.append(get_out(a)) + a = a // 8 + + return out + + +def next_A(seq: int, a: int) -> Generator[int]: + while True: + out = get_out(a) + if out == seq: + yield a + + a += 1 + + +def main() -> None: + seq: list[int] = [0, 3, 5, 5, 3, 0, 4, 1, 7, 4, 5, 7, 1, 1, 4, 2] + a: int = 0 + + steps: dict[int, Generator[int]] = {} + i = 1 + while True: + if i == len(seq) + 1: + break + + s = seq[i - 1] + + if i not in steps: + steps[i] = next_A(s, a) + + a = next(steps[i]) + + out = get_all_out(a) + if out == list(reversed(seq[:i])): + i += 1 + a *= 8 + + print(a // 8) + + +if __name__ == ""__main__"": + main() +",python:3.9.21-slim +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","#!/usr/bin/python3 + +def combo_operand(op:int) -> int: + combo_operands = {4:""A"",5:""B"",6:""C""} + return op if op < 4 else registers[combo_operands[op]] + +def adv(op:int) -> int: + return int(registers[""A""] / 2 ** combo_operand(op)) + +def bxl(op:int) -> int: + return registers[""B""] ^ op + +def bst(op:int) -> int: + return combo_operand(op) % 8 + +def jnz(inst_pointer:int, op:int) -> int: + return op if registers[""A""] != 0 else inst_pointer + 2 + +def bxc(op:int) -> int: + return registers[""B""] ^ registers[""C""] + +def out(op:int) -> str: + return str(combo_operand(op) % 8) + +def bdv(op:int) -> int: + return adv(op) + +def cdv(op:int) -> int: + return adv(op) + + +with open(""input.txt"") as file: + registers = {} + for line in file: + if ""Register"" in line: + line = line.strip().split() + registers[line[1].strip("":"")] = int(line[2]) + elif ""Program"" in line: + line = line.strip(""Program: "") + program = [int(n) for n in line.strip().split("","")] + + +instruction_pointer = 0 +output = [] + +while instruction_pointer < len(program): + opcode = program[instruction_pointer] + operand = program[instruction_pointer + 1] + + if opcode == 0: + registers[""A""] = adv(operand) + elif opcode == 1: + registers[""B""] = bxl(operand) + elif opcode == 2: + registers[""B""] = bst(operand) + elif opcode == 3: + instruction_pointer = jnz(instruction_pointer, operand) + continue + elif opcode == 4: + registers[""B""] = bxc(operand) + elif opcode == 5: + output.append(out(operand)) + elif opcode == 6: + registers[""B""] = bdv(operand) + elif opcode == 7: + registers[""C""] = cdv(operand) + + instruction_pointer += 2 + +print(""Program output:"", "","".join(output)) +",python:3.9.21-slim +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","output = """" +i = 0 + +def get_result_string(regs, instructions): + global output + n = len(instructions) + global i + + def get_combo(operand): + if 0 <= operand < 4: + return operand + elif operand == 4: + return regs['a'] + elif operand == 5: + return regs['b'] + elif operand == 6: + return regs['c'] + return 0 + + def adv(operand): + operand = get_combo(operand) + regs['a'] = int(regs['a'] // (2**operand)) + return + + def bxl(operand): + regs['b'] = int(regs['b'] ^ operand) + return + + def bst(operand): + operand = get_combo(operand) + regs['b'] = int(operand % 8) + return + + def jnz(operand): + global i + if regs['a'] != 0: + i = int(operand) - 1 + return + + def bxc(operand): + regs['b'] = int(regs['b'] ^ regs['c']) + return + + def out(operand): + global output + operand = get_combo(operand) + output += str(operand % 8) + return + + def bdv(operand): + operand = get_combo(operand) + regs['b'] = int(regs['a'] // (2**operand)) + return + + def cdv(operand): + operand = get_combo(operand) + regs['c'] = int(regs['a'] // (2**operand)) + return + + while i < n: + curr = instructions[i] + if curr[0] == 0: + adv(curr[1]) + elif curr[0] == 1: + bxl(curr[1]) + elif curr[0] == 2: + bst(curr[1]) + elif curr[0] == 3: + jnz(curr[1]) + elif curr[0] == 4: + bxc(curr[1]) + elif curr[0] == 5: + out(curr[1]) + elif curr[0] == 6: + bdv(curr[1]) + elif curr[0] == 7: + cdv(curr[1]) + i += 1 + return ','.join(list(output)) + +if __name__ == ""__main__"": + regs = {} + instructions = [] + # Open file 'day17-1.txt' in read mode + with open('day17-1.txt', 'r') as f: + for line in f: + line = line.strip() + if regs.get('a') is None: + regs['a'] = int(line[line.find(':') + 2:]) + elif regs.get('b') is None: + regs['b'] = int(line[line.find(':') + 2:]) + elif regs.get('c') is None: + regs['c'] = int(line[line.find(':') + 2:]) + else: + instructions = [int(val) for val in line[line.find(':') + 2:].split(',') if len(val) == 1] + instructions = [(instructions[i], instructions[i + 1]) for i in range(0, len(instructions), 2)] + + print(""Result String:"", get_result_string(regs, instructions))",python:3.9.21-slim +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","import re + +instr_map = { + 0: lambda operand: adv(operand), + 1: lambda operand: bxl(operand), + 2: lambda operand: bst(operand), + 3: lambda operand: jnz(operand), + 4: lambda operand: bxc(operand), + 5: lambda operand: out(operand), + 6: lambda operand: bdv(operand), + 7: lambda operand: cdv(operand) +} + +def combo(operand): + global reg_a, reg_b, reg_c + + if 0 <= operand <= 3: + return operand + elif operand == 4: + return reg_a + elif operand == 5: + return reg_b + elif operand == 6: + return reg_c + +def adv(operand): + global reg_a + reg_a = reg_a // (2 ** combo(operand)) + +def bxl(operand): + global reg_b + reg_b = reg_b ^ operand + +def bst(operand): + global reg_b + reg_b = combo(operand) % 8 + +def bxc(operand): + global reg_b, reg_c + reg_b = reg_b ^ reg_c + +def out(operand): + print(f'{combo(operand) % 8},', end='') + +def bdv(operand): + global reg_a, reg_b + reg_b = reg_a // (2 ** combo(operand)) + +def cdv(operand): + global reg_a, reg_c + reg_c = reg_a // (2 ** combo(operand)) + +def jnz(operand): + global ip, reg_a + if reg_a != 0: + ip = operand + ip -= 2 + +def main(): + global reg_a, reg_b, reg_c, ip + with open(""17_input.txt"", ""r"") as f: + reg_a = int(re.search(r""(\d+)"", f.readline())[0]) + reg_b = int(re.search(r""(\d+)"", f.readline())[0]) + reg_c = int(re.search(r""(\d+)"", f.readline())[0]) + + f.readline() + program = [int(opcode) for opcode in re.findall(r""(\d+)"", f.readline())] + + print(f'{reg_a=}, {reg_b=}, {reg_c=}, {program=}') + while 0 <= ip < len(program): + instr_map[program[ip]](program[ip+1]) + ip += 2 + +reg_a: int = 0 +reg_b: int = 0 +reg_c: int = 0 +ip: int = 0 +if __name__ == '__main__': + main()",python:3.9.21-slim +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"def run(regs, instructions): + n = len(instructions) + i = 0 + output = [] + def get_combo(operand): + if 0 <= operand < 4: + return operand + elif operand == 4: + return regs['a'] + elif operand == 5: + return regs['b'] + elif operand == 6: + return regs['c'] + return 0 + + while i < n: + curr = instructions[i] + operand = instructions[i + 1] + if curr == 0: + regs['a'] //= 2**get_combo(operand) + elif curr == 1: + regs['b'] ^= operand + elif curr == 2: + regs['b'] = get_combo(operand) % 8 + elif curr == 3: + if regs['a']: + i = operand + continue + elif curr == 4: + regs['b'] ^= regs['c'] + elif curr == 5: + output.append(get_combo(operand) % 8) + elif curr == 6: + regs['b'] = regs['a'] // 2**get_combo(operand) + elif curr == 7: + regs['c'] = regs['a'] // 2**get_combo(operand) + i += 2 + return list(output) + +def get_lowest_a(regs, instructions): + regs['a'] = 0 + j = 1 + iFloor = 0 + while j <= len(instructions) and j >= 0: + regs['a'] <<= 3 + for i in range(iFloor, 8): + regsCopy = regs.copy() + regsCopy['a'] += i + if instructions[-j:] == run(regsCopy, instructions): + break + else: + j -= 1 + regs['a'] >>= 3 + iFloor = regs['a'] % 8 + 1 + regs['a'] >>= 3 + continue + + j += 1 + regs['a'] += i + iFloor = 0 + + return regs['a'] + +if __name__ == ""__main__"": + regs = {} + instructions = [] + # Open file 'day17-2.txt' in read mode + with open('day17-2.txt', 'r') as f: + for line in f: + line = line.strip() + if regs.get('a') is None: + regs['a'] = 0 + elif regs.get('b') is None: + regs['b'] = int(line[line.find(':') + 2:]) + elif regs.get('c') is None: + regs['c'] = int(line[line.find(':') + 2:]) + else: + instructions = [int(val) for val in line[line.find(':') + 2:].split(',') if len(val) == 1] + + print(""Lowest value of Register A:"", get_lowest_a(regs, instructions))",python:3.9.21-slim +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"from part1 import parse_input + +def run(program, regs): + """""" + Executes a given program with specified registers. + + Args: + program (list of int): A list of integers representing the program's opcodes and operands. + regs (list of int): A list of initial values for the registers. + + Yields: + int: The result of the operation specified by opcode 5, modulo 8. + + The program supports the following opcodes: + 0: Divide the value in reg_a by 2 raised to the power of the value in the register specified by operand. + 1: XOR the value in reg_b with the operand. + 2: Set reg_b to the value in the register specified by operand, modulo 8. + 3: If the value in reg_a is non-zero, set the instruction pointer to operand - 2. + 4: XOR the value in reg_b with the value in reg_c. + 5: Yield the value in the register specified by operand, modulo 8. + 6: Set reg_b to the value in reg_a divided by 2 raised to the power of the value in the register specified by operand. + 7: Set reg_c to the value in reg_a divided by 2 raised to the power of the value in the register specified by operand. + """""" + reg_a, reg_b, reg_c = range(4, 7) + ip = 0 + combo = [0, 1, 2, 3, *regs] + while ip < len(program): + opcode, operand = program[ip:ip + 2] + if opcode == 0: + combo[reg_a] //= 2 ** combo[operand] + elif opcode == 1: + combo[reg_b] ^= operand + elif opcode == 2: + combo[reg_b] = combo[operand] % 8 + elif opcode == 3: + if combo[reg_a]: + ip = operand - 2 + elif opcode == 4: + combo[reg_b] ^= combo[reg_c] + elif opcode == 5: + yield combo[operand] % 8 + elif opcode == 6: + combo[reg_b] = combo[reg_a] // (2 ** combo[operand]) + elif opcode == 7: + combo[reg_c] = combo[reg_a] // (2 ** combo[operand]) + ip += 2 + +def expect(program, target_output, prev_a=0): + """""" + Tries to find an integer 'a' such that when the 'program' is run with inputs derived from 'a', + it produces the 'target_output' sequence. + + Args: + program (iterable): The program to be run, which yields outputs based on inputs. + target_output (list): The desired sequence of outputs that the program should produce. + prev_a (int, optional): The previous value of 'a' used in the recursive calls. Defaults to 0. + + Returns: + int or None: The integer 'a' that produces the 'target_output' when the program is run, + or None if no such 'a' can be found. + """""" + def helper(program, target_output, prev_a): + if not target_output: + return prev_a + for a in range(1 << 10): + if a >> 3 == prev_a & 127 and next(run(program, (a, 0, 0))) == target_output[-1]: + result = helper(program, target_output[:-1], (prev_a << 3) | (a % 8)) + if result is not None: + return result + return None + + return helper(program, target_output, prev_a) + +if __name__ == ""__main__"": + file_path = 'input.txt' + registers, program = parse_input(file_path) + + # Example target output + target_output = program.copy() + + initial_value = expect(program, target_output) + if initial_value is not None: + print(f""The initial value for register A that produces the target output is: {initial_value}"") + else: + print(""No initial value found that produces the target output within the given attempts."")",python:3.9.21-slim +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +program = [int(x) for x in input_text[4].removeprefix(""Program: "").split("","")] +a = 0 +position = 0 +offsets = [0] + +while position < len(program): + if program[-1 - position] == ((a % 8) ^ 5 ^ 6 ^ (a // (2 ** ((a % 8) ^ 5)))) % 8: + a *= 8 + position += 1 + offsets.append(0) + elif offsets[-1] < 7: + a += 1 + offsets[-1] += 1 + else: + while offsets[-1] >= 7 and position > 0: + a //= 8 + offsets.pop(-1) + position -= 1 + a += 1 + offsets[-1] += 1 + + +print(a // 8) +",python:3.9.21-slim +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"import re + + +with open(""17.txt"") as i: + input = [x.strip() for x in i.readlines()] + +test_data = """"""Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0"""""".split(""\n"") + +# input = test_data + +a, b, c = 0, 0, 0 +program = None + +for l in input: + if l.startswith(""Register ""): + r, v = re.match(r""Register (A|B|C): (\d+)"", l).groups() + if r == ""A"": a = int(v) + elif r == ""B"": b = int(v) + elif r == ""C"": c = int(v) + elif l.startswith(""Program: ""): + program = [int(x) for x in l[9:].split("","")] + +def run_program(program: list[int], aa: int, bb: int, cc: int) -> list[int]: + output = [] + a, b, c = aa, bb, cc + ip = 0 + while ip < len(program): + i = program[ip] + op = program[ip+1] + cop = None + if op == 4: cop = a + elif op == 5: cop = b + elif op == 6: cop = c + else: cop = op + + if i == 0: # adv + a = a // (2**cop) + elif i == 1: # bxl + b = b ^ op + elif i == 2: #bst + b = cop % 8 + elif i == 3: # jnz + if a != 0: + ip = op + continue + elif i == 4: # bxc + b = b ^ c + elif i == 5: # out + output.append(cop%8) + elif i == 6: # bdv + b = a // (2**cop) + elif i == 7: # cdv + c = a // (2**cop) + ip += 2 + return output + +current = len(program) +solutions = [0] +while current>0: + next_solutions = [] + for aa in solutions: + for i in range(8): + r = run_program(program, (aa<<3) | i, b, c) + if r[0] == program[current-1]: + next_solutions.append((aa << 3) | i) + current = current - 1 + solutions = next_solutions + +part2 = min(solutions) +print(part2)",python:3.9.21-slim +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"# day 17 +import os + +def reader(): + return open(f""17.txt"", 'r').read().splitlines() + + +def simulate(program, A): + l = [0, 1, 2, 3, A, 0, 0, -1] + out = [] + i = 0 + while i < len(program): + op = program[i] + operand = program[i + 1] + if op == 0: + l[4] = int(l[4] / (2 ** l[operand])) + elif op == 1: + l[5] = l[5] ^ operand + elif op == 2: + l[5] = l[operand] % 8 + elif op == 3: + if l[4] != 0: + i = operand + continue + elif op == 4: + l[5] = l[5] ^ l[6] + elif op == 5: + out.append(l[operand] % 8) + elif op == 6: + l[5] = int(l[4] / (2 ** l[operand])) + elif op == 7: + l[6] = int(l[4] / (2 ** l[operand])) + i += 2 + return out + +def part2(): + f = reader() + program = list(map(int, f[4][(f[4].find(': ') + 2):].split(','))) + + def backtrack(A=0, j=-1): + if -j > len(program): + return A + m = float('inf') + for i in range(8): + t = (A << 3) | i + if simulate(program, t)[j:] == program[j:]: + m = min(m, backtrack(t, j - 1)) + return m + + print(backtrack()) + +part2()",python:3.9.21-slim +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heapify, heappop, heappush + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +grid_size = 70 +num_fallen = 1024 +bytes = set() +for byte in input_text[:num_fallen]: + byte_x, byte_y = byte.split("","") + bytes.add((int(byte_x), int(byte_y))) + +movements = ((-1, 0), (1, 0), (0, 1), (0, -1)) +explored = set() +discovered = [(0, 0, 0)] +heapify(discovered) +while True: + distance, byte_x, byte_y = heappop(discovered) + if (byte_x, byte_y) not in explored: + explored.add((byte_x, byte_y)) + if byte_x == byte_y == grid_size: + print(distance) + break + for movement in movements: + new_position = (byte_x + movement[0], byte_y + movement[1]) + if ( + new_position not in bytes + and new_position not in explored + and all(0 <= coord <= grid_size for coord in new_position) + ): + heappush(discovered, (distance + 1, *new_position)) +",python:3.9.21-slim +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from collections import deque +from typing import List, Tuple + +def parse_input(file_path: str) -> List[Tuple[int, int]]: + """""" + Parses the input file and returns a list of tuples containing integer pairs. + + Args: + file_path (str): The path to the input file. + + Returns: + List[Tuple[int, int]]: A list of tuples, where each tuple contains two integers + parsed from a line in the input file. Each line in the file should contain two + integers separated by a comma. + """""" + with open(file_path, 'r') as file: + return [tuple(map(int, line.strip().split(','))) for line in file] + +def initialize_grid(size: int) -> List[List[str]]: + """""" + Initializes a square grid of the given size with all cells set to '.'. + + Args: + size (int): The size of the grid (number of rows and columns). + + Returns: + List[List[str]]: A 2D list representing the initialized grid. + """""" + return [['.' for _ in range(size)] for _ in range(size)] + +def simulate_falling_bytes(grid: List[List[str]], byte_positions: List[Tuple[int, int]], num_bytes: int): + """""" + Simulates the falling of bytes in a grid. + + Args: + grid (List[List[str]]): A 2D list representing the grid where bytes will fall. + byte_positions (List[Tuple[int, int]]): A list of tuples representing the (x, y) positions of bytes. + num_bytes (int): The number of bytes to simulate falling. + + Returns: + None + """""" + for x, y in byte_positions[:num_bytes]: + grid[y][x] = '#' + +def find_shortest_path(grid: List[List[str]]) -> int: + """""" + Finds the shortest path in a grid from the top-left corner to the bottom-right corner. + The grid is represented as a list of lists of strings, where '.' represents an open cell + and any other character represents an obstacle. + Args: + grid (List[List[str]]): The grid to search, where each element is a string representing a cell. + Returns: + int: The number of steps in the shortest path from the top-left to the bottom-right corner. + Returns -1 if no such path exists. + """""" + size = len(grid) + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + queue = deque([(0, 0, 0)]) # (x, y, steps) + visited = set([(0, 0)]) + + while queue: + x, y, steps = queue.popleft() + + if (x, y) == (size - 1, size - 1): + return steps + + for dx, dy in directions: + nx, ny = x + dx, y + dy + if 0 <= nx < size and 0 <= ny < size and grid[ny][nx] == '.' and (nx, ny) not in visited: + visited.add((nx, ny)) + queue.append((nx, ny, steps + 1)) + + return -1 # No path found + +if __name__ == ""__main__"": + file_path = 'input.txt' + byte_positions = parse_input(file_path) + grid_size = 71 # For the actual problem, use 71; for the example, use 7 + grid = initialize_grid(grid_size) + simulate_falling_bytes(grid, byte_positions, 1024) + steps = find_shortest_path(grid) + print(f""Minimum number of steps needed to reach the exit: {steps}"") +",python:3.9.21-slim +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heappop, heappush + +def in_bounds(i, j, n): + return 0 <= i < n and 0 <= j < n + +def navigate(maze, n): + start = (0, 0) + end = (n - 1, n - 1) + heap = [(0, start[0], start[1])] + visited = set() + + while heap: + score, i, j = heappop(heap) + + if (i, j) == end: + break + + if (i, j) in visited: + continue + + visited.add((i, j)) + + if in_bounds(i, j+1, n) and maze[i][j+1] not in visited and maze[i][j+1] == '.': + heappush(heap, (score + 1, i, j+1)) + + if in_bounds(i+1, j, n) and maze[i+1][j] not in visited and maze[i+1][j] == '.': + heappush(heap, (score + 1, i+1, j)) + + if in_bounds(i, j-1, n) and maze[i][j-1] not in visited and maze[i][j-1] == '.': + heappush(heap, (score + 1, i, j-1)) + + if in_bounds(i-1, j, n) and maze[i-1][j] not in visited and maze[i-1][j] == '.': + heappush(heap, (score + 1, i-1, j)) + + return score + +def init_maze(bytes, n, numBytes): + maze = [['.' for _ in range(n)] for _ in range(n)] + for byte in bytes[:numBytes]: + maze[byte[1]][byte[0]] = '#' + return maze + +def get_min_steps(bytes): + n = 71 + numBytes = 1024 + maze = init_maze(bytes, n, numBytes) + return navigate(maze, n) + +if __name__ == ""__main__"": + # Open file 'day18-1.txt' in read mode + with open('day18-1.txt', 'r') as f: + bytes = [] + for line in f: + line = line.strip() + x, y = line.split(',') + bytes.append((int(x), int(y))) + + print(""Minimum steps:"", get_min_steps(bytes))",python:3.9.21-slim +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"def bfs(byte_locs, x_len, y_len): + start = (0, 0) + end = (x_len - 1, y_len - 1) + visited = set() + frontier = [[start]] + + while len(frontier) > 0: + path = frontier.pop(0) + cur = path[-1] + + if cur == end: + return path + + visited.add(cur) + + + neighbors = [tuple(map(sum, zip(cur, direction))) for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]] + neighbors = [pos for pos in neighbors if pos[0] in range(x_len) and pos[1] in range(y_len) and pos not in byte_locs] + + for neighbor in neighbors: + if neighbor not in visited: + frontier.append(path + [neighbor]) + visited.add(neighbor) + + print(""no path found"") + return None + + + + +with open('input.txt') as f: + lines = f.read().splitlines() + +byte_locs = [tuple(map(int, line.split("",""))) for line in lines] + +x_len = 71 +y_len = 71 + +print(len(bfs(set(byte_locs[0:1024]), x_len, y_len)) - 1) +",python:3.9.21-slim +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heappush, heappop + +with open(""./day_18.in"") as fin: + lines = fin.read().strip().split(""\n"") + coords = set([tuple(map(int, line.split("",""))) for line in lines][:1024]) + +dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] + +N = 70 + +# Heuristic for A* +def h(i, j): + return abs(N - i) + abs(N - j) + +def in_grid(i, j): + return 0 <= i <= N and 0 <= j <= N and (i, j) not in coords + +q = [(h(0, 0), 0, 0)] +cost = {} +while len(q) > 0: + c, i, j = heappop(q) + if (i, j) in cost: + continue + cost[(i, j)] = c - h(i, j) + + if (i, j) == (N, N): + print(cost[(i, j)]) + break + + for di, dj in dd: + ii, jj = i + di, j + dj + if in_grid(ii, jj): + heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj)) +",python:3.9.21-slim +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from heapq import heapify, heappop, heappush + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +grid_size = 70 +bytes_list = [] +for byte in input_text: + byte_x, byte_y = byte.split("","") + bytes_list.append((int(byte_x), int(byte_y))) + +movements = ((-1, 0), (1, 0), (0, 1), (0, -1)) + +bytes_needed_lower = 0 +bytes_needed_upper = len(bytes_list) - 1 +while bytes_needed_lower < bytes_needed_upper: + mid = (bytes_needed_lower + bytes_needed_upper) // 2 + bytes = set(bytes_list[:mid]) + explored = set() + discovered = [(0, 0, 0)] + heapify(discovered) + while discovered: + distance, byte_x, byte_y = heappop(discovered) + if (byte_x, byte_y) not in explored: + explored.add((byte_x, byte_y)) + if byte_x == byte_y == grid_size: + break + for movement in movements: + new_position = (byte_x + movement[0], byte_y + movement[1]) + if ( + new_position not in bytes + and new_position not in explored + and all(0 <= coord <= grid_size for coord in new_position) + ): + heappush(discovered, (distance + 1, *new_position)) + else: + bytes_needed_upper = mid + continue + bytes_needed_lower = mid + 1 + +print("","".join([str(x) for x in bytes_list[bytes_needed_lower - 1]])) +",python:3.9.21-slim +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","def bfs(byte_locs, x_len, y_len): + start = (0, 0) + end = (x_len - 1, y_len - 1) + visited = set() + frontier = [[start]] + + while len(frontier) > 0: + path = frontier.pop(0) + cur = path[-1] + + if cur == end: + return path + + visited.add(cur) + + + neighbors = [tuple(map(sum, zip(cur, direction))) for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]] + neighbors = [pos for pos in neighbors if pos[0] in range(x_len) and pos[1] in range(y_len) and pos not in byte_locs] + + for neighbor in neighbors: + if neighbor not in visited: + frontier.append(path + [neighbor]) + visited.add(neighbor) + + return None + + + + +with open('input.txt') as f: + lines = f.read().splitlines() + +byte_locs = [tuple(map(int, line.split("",""))) for line in lines] + +x_len = 71 +y_len = 71 + + +lower = 0 +upper = len(byte_locs) - 1 + +while lower <= upper: + mid = (lower + upper) // 2 + test = bfs(set(byte_locs[0:mid]), x_len, y_len) + if test is None: + upper = mid - 1 + print(""not reachable at"", byte_locs[mid-1]) + else: + print(""reachable at"", byte_locs[mid-1]) + lower = mid + 1 + +print(byte_locs[mid]) +",python:3.9.21-slim +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from heapq import heappush, heappop + +with open(""./day_18.in"") as fin: + lines = fin.read().strip().split(""\n"") + coords = [tuple(map(int, line.split("",""))) for line in lines] + +dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] + +N = 70 + +# Heuristic for A* +def h(i, j): + return abs(N - i) + abs(N - j) + +def doable(idx): + # Can we get to the index with first `idx` coords blocked? + def in_grid(i, j): + return 0 <= i <= N and 0 <= j <= N and (i, j) not in coords[:idx] + + q = [(h(0, 0), 0, 0)] + cost = {} + while len(q) > 0: + c, i, j = heappop(q) + if (i, j) in cost: + continue + cost[(i, j)] = c - h(i, j) + + if (i, j) == (N, N): + return True + + for di, dj in dd: + ii, jj = i + di, j + dj + if in_grid(ii, jj): + heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj)) + + return False + +# Binary search for first coord that is not doable +lo = 0 +hi = len(coords) - 1 +while hi > lo: + mid = (lo + hi) // 2 + if doable(mid): + lo = mid + 1 + else: + hi = mid + +print("","".join(map(str, coords[lo-1]))) +",python:3.9.21-slim +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from collections import deque + + +l = open(""18.txt"").read().splitlines() +l = [list(map(int, x.split("",""))) for x in l] + +max_x = max(coord[0] for coord in l) +max_y = max(coord[1] for coord in l) +def P2(): + for find in range(1024,len(l)): + grid = [[""."" for _ in range(max_y + 1)] for _ in range(max_x + 1)] + + for i in range(find): + x,y = l[i] + grid[x][y] = ""#"" + + def bfs(grid, start, end): + rows, cols = len(grid), len(grid[0]) + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] + queue = deque([(start, 0)]) + visited = set() + + while queue: + (x, y), dist = queue.popleft() + + if (x, y) == end: + return dist + + if (x, y) in visited or grid[x][y] == ""#"": + continue + visited.add((x, y)) + + for dx, dy in directions: + nx, ny = x + dx, y + dy + if 0 <= nx < rows and 0 <= ny < cols and (nx, ny) not in visited: + queue.append(((nx, ny), dist + 1)) + + return -1 + + + if bfs(grid, (0,0), (max_x, max_y)) == -1: + return l[find-1] + +print(P2())",python:3.9.21-slim +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","#!/usr/bin/env python3 + +import re +from collections import defaultdict, deque + +myfile = open(""18.in"", ""r"") +lines = myfile.read().strip().splitlines() +myfile.close() + +blocks = [tuple(map(int, re.findall(r""\d+"", line))) for line in lines] + +part_one = 0 +part_two = 0 + +height = width = 70 + + +def search(block_count): + grid = defaultdict(str) + for x in range(width + 1): + for y in range(height + 1): + grid[(x, y)] = ""."" + grid[(width, height)] = ""$"" + for x, y in blocks[: block_count + 1]: + grid[(x, y)] = """" + + visited = set() + scores = defaultdict(lambda: float(""inf"")) + scores[(0, 0)] = 0 + q = deque([(0, 0)]) + while q: + pos = q.popleft() + visited.add(pos) + + if grid[pos] == ""$"": + return scores[pos] + + next_score = scores[pos] + 1 + for dir in [(1, 0), (0, -1), (-1, 0), (0, 1)]: + next_pos = (pos[0] + dir[0], pos[1] + dir[1]) + if next_pos not in visited and next_score < scores[next_pos]: + if grid[next_pos] != """": + scores[next_pos] = next_score + q.append(next_pos) + + return -1 + +unblocked, blocked = 1024, len(blocks) +while blocked - unblocked > 1: + mid = (unblocked + blocked) // 2 + result = search(mid) + if result == -1: + blocked = mid + else: + unblocked = mid +part_two = "","".join(map(str, blocks[blocked])) + +print(""Part Two:"", part_two)",python:3.9.21-slim +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from pprint import pprint + +WHITE = ""w"" +BLUE = ""u"" +BLACK = ""b"" +RED = ""r"" +GREEN = ""g"" + +INPUT_FILE = ""test.txt"" + +read_file = open(INPUT_FILE, ""r"") + +lines = read_file.readlines() + +available_towels = lines[0].strip().split("", "") + +designs = [] + +for line in lines[2:]: + designs.append(line.strip()) + + +def find_first_pattern(design, start_index=0): + for i in range(len(design), 0, -1): + if design[start_index:i] in available_towels: + return (i, design[start_index:i]) + return (None, None) + + +def find_last_pattern(design, end_index): + for i in range(len(design)): + if design[i:end_index] in available_towels: + return (i, design[i:end_index]) + + return (None, None) + + +def find_largest_from_start(design, start=0): + largest_pattern_match = None + end = 0 + for i in range(1 + start, len(design)): + sub_string = design[start:i] + print(sub_string) + if sub_string in available_towels: + largest_pattern_match = sub_string + end = i + + return (largest_pattern_match, end) + + +results = [] +impossible_designs = [] + + +def can_build_word(target, patterns): + def can_build(remaining, memo=None): + if memo is None: + memo = {} + + # Base cases + if not remaining: # Successfully used all letters + return True + if remaining in memo: # Already tried this combo + return memo[remaining] + + # Try each pattern at the start of our remaining string + # We can reuse patterns, so no need to track what we've used + for pattern in patterns: + if remaining.startswith(pattern): + new_remaining = remaining[len(pattern) :] + if can_build(new_remaining, memo): + memo[remaining] = True + print(memo) + return True + + memo[remaining] = False + return False + + return can_build(target) + + +can_build_count = 0 + +for design in designs: + if can_build_word(design, available_towels): + can_build_count += 1 + +print(can_build_count) + +quit() + +for design in designs: + patterns = {} + result = 0 + pattern_found = False + while True: + (result, pattern) = find_first_pattern(design, result) + patterns[pattern] = patterns.get(pattern, 0) + 1 + if not result: + pattern_found = False + break + if design[:result] == design: + pattern_found = True + break + if pattern_found: + results.append((design, patterns)) + else: + patterns = {} + result = len(design) + pattern_found = False + while True: + (result, pattern) = find_last_pattern(design, result) + patterns[pattern] = patterns.get(pattern, 0) + 1 + if result == None: + pattern_found = False + break + if result == 0: + pattern_found = True + break + if pattern_found: + results.append((design, patterns)) + else: + impossible_designs.append(design) +",python:3.9.21-slim +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from functools import cache + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +towels_trie = {} +for towel in input_text[0].split("", ""): + inner_dict = towels_trie + for letter in list(towel): + if letter not in inner_dict: + inner_dict[letter] = {} + inner_dict = inner_dict[letter] + inner_dict[None] = None + + +@cache +def pattern_possible(pattern): + if not pattern: + return True + patterns_needed = [] + trie = towels_trie + for i, letter in enumerate(pattern): + if letter in trie: + trie = trie[letter] + if None in trie: + patterns_needed.append(pattern[i + 1 :]) + else: + break + return any(pattern_possible(sub_pattern) for sub_pattern in patterns_needed) + + +print(sum(pattern_possible(pattern) for pattern in input_text[2:])) +",python:3.9.21-slim +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"def is_pattern_possible(pattern, towels, visited): + if pattern == """": + return True + + visited.add(pattern) + + return any([pattern.startswith(t) and pattern[len(t):] not in visited and is_pattern_possible(pattern[len(t):], towels, visited) for t in towels]) + + +with open('input.txt') as f: + lines = f.read().splitlines() + +towels = [s.strip() for s in lines[0].split("","")] + +patterns = lines[2:] + +print(sum([is_pattern_possible(p, towels, set()) for p in patterns]))",python:3.9.21-slim +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from pprint import pprint + +WHITE = ""w"" +BLUE = ""u"" +BLACK = ""b"" +RED = ""r"" +GREEN = ""g"" + +INPUT_FILE = ""test.txt"" + +read_file = open(INPUT_FILE, ""r"") + +lines = read_file.readlines() + +available_towels = lines[0].strip().split("", "") + +designs = [] + +for line in lines[2:]: + designs.append(line.strip()) + + +def find_first_pattern(design, start_index=0): + for i in range(len(design), 0, -1): + if design[start_index:i] in available_towels: + return (i, design[start_index:i]) + return (None, None) + + +def find_last_pattern(design, end_index): + for i in range(len(design)): + if design[i:end_index] in available_towels: + return (i, design[i:end_index]) + + return (None, None) + + +def find_largest_from_start(design, start=0): + largest_pattern_match = None + end = 0 + for i in range(1 + start, len(design)): + sub_string = design[start:i] + print(sub_string) + if sub_string in available_towels: + largest_pattern_match = sub_string + end = i + + return (largest_pattern_match, end) + + +results = [] +impossible_designs = [] + + +def can_build_pattern(target, patterns): + def can_build(remaining, memo=None): + if memo is None: + memo = {} + + # Base cases + if not remaining: # Successfully used all letters + return True + if remaining in memo: # Already tried this combo + return memo[remaining] + + # Try each pattern at the start of our remaining string + # We can reuse patterns, so no need to track what we've used + for pattern in patterns: + if remaining.startswith(pattern): + new_remaining = remaining[len(pattern) :] + if can_build(new_remaining, memo): + memo[remaining] = True + print(memo) + return True + + memo[remaining] = False + return False + + return can_build(target) + + +can_build_count = 0 + +for design in designs: + if can_build_pattern(design, available_towels): + can_build_count += 1 + +print(can_build_count) + +quit() + +for design in designs: + patterns = {} + result = 0 + pattern_found = False + while True: + (result, pattern) = find_first_pattern(design, result) + patterns[pattern] = patterns.get(pattern, 0) + 1 + if not result: + pattern_found = False + break + if design[:result] == design: + pattern_found = True + break + if pattern_found: + results.append((design, patterns)) + else: + patterns = {} + result = len(design) + pattern_found = False + while True: + (result, pattern) = find_last_pattern(design, result) + patterns[pattern] = patterns.get(pattern, 0) + 1 + if result == None: + pattern_found = False + break + if result == 0: + pattern_found = True + break + if pattern_found: + results.append((design, patterns)) + else: + impossible_designs.append(design) +",python:3.9.21-slim +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"with open(""./day_19.in"") as fin: + lines = fin.read().strip().split(""\n"") + units = lines[0].split("", "") + + designs = lines[2:] + + +def possible(design): + n = len(design) + dp = [False] * len(design) + for i in range(n): + if design[:i+1] in units: + dp[i] = True + continue + + for u in units: + if design[i-len(u)+1:i+1] == u and dp[i - len(u)]: + # print("" "", i, u, design[-len(u):], dp[i - len(u)]) + dp[i] = True + break + + # print(design, dp) + return dp[-1] + +ans = 0 +for d in designs: + if possible(d): + print(d) + ans += 1 + +print(ans) +",python:3.9.21-slim +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"def check_count(towels, pattern, cache): + if pattern == """": + return 1 + + if (block := cache.get(pattern, None)) is not None: + return block + + result = 0 + for towel in towels: + if towel == pattern[:len(towel)]: + result += check_count(towels, pattern[len(towel):], cache) + + cache[pattern] = result + return result + +def get_num_achievable_patterns(towels, patterns): + return sum([check_count(towels, pattern, {}) for pattern in patterns]) + +if __name__ == ""__main__"": + towels = [] + patterns = [] + # Open file 'day19-2.txt' in read mode + with open('day19-2.txt', 'r') as f: + vals = [] + for line in f: + line = line.strip() + if len(line) == 0: + continue + if len(towels) == 0: + towels = line.split(', ') + else: + patterns.append(line) + + print(""Number of ways to acheive patterns:"", get_num_achievable_patterns(towels, patterns))",python:3.9.21-slim +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"def num_possible_patterns(pattern, towels, memo): + if pattern == """": + return 1 + + if pattern in memo: + return memo[pattern] + + res = sum([num_possible_patterns(pattern[len(t):], towels, memo) if pattern.startswith(t) else 0 for t in towels]) + memo[pattern] = res + return res + + +with open('input.txt') as f: + lines = f.read().splitlines() + +towels = [s.strip() for s in lines[0].split("","")] + +patterns = lines[2:] + +print(sum([num_possible_patterns(p, towels, dict()) for p in patterns]))",python:3.9.21-slim +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from functools import cache + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +towels_trie = {} +for towel in input_text[0].split("", ""): + inner_dict = towels_trie + for letter in list(towel): + if letter not in inner_dict: + inner_dict[letter] = {} + inner_dict = inner_dict[letter] + inner_dict[None] = None + + +@cache +def pattern_possible(pattern): + if not pattern: + return 1 + patterns_needed = [] + trie = towels_trie + for i, letter in enumerate(pattern): + if letter in trie: + trie = trie[letter] + if None in trie: + patterns_needed.append(pattern[i + 1 :]) + else: + break + return sum(pattern_possible(sub_pattern) for sub_pattern in patterns_needed) + + +print(sum(pattern_possible(pattern) for pattern in input_text[2:])) +",python:3.9.21-slim +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from typing import List, Tuple +from collections import defaultdict +from part1 import parse_input + +def count_ways_to_construct_design(design: str, towel_patterns: List[str]) -> int: + """""" + Counts the number of ways to construct a given design using a list of towel patterns. + Args: + design (str): The design string that needs to be constructed. + towel_patterns (List[str]): A list of towel patterns that can be used to construct the design. + Returns: + int: The number of ways to construct the design using the given towel patterns. + """""" + n = len(design) + dp = defaultdict(int) + dp[0] = 1 # Base case: there's one way to construct an empty design + + for i in range(1, n + 1): + for pattern in towel_patterns: + if i >= len(pattern) and design[i - len(pattern):i] == pattern: + dp[i] += dp[i - len(pattern)] + + return dp[n] + +def total_ways_to_construct_designs(towel_patterns: List[str], desired_designs: List[str]) -> int: + """""" + Calculate the total number of ways to construct each design in the desired designs list + using the given towel patterns. + + Args: + towel_patterns (List[str]): A list of available towel patterns. + desired_designs (List[str]): A list of desired designs to be constructed. + + Returns: + int: The total number of ways to construct all the desired designs using the towel patterns. + """""" + return sum(count_ways_to_construct_design(design, towel_patterns) for design in desired_designs) + +if __name__ == ""__main__"": + file_path = 'input.txt' + towel_patterns, desired_designs = parse_input(file_path) + result = total_ways_to_construct_designs(towel_patterns, desired_designs) + print(result) +",python:3.9.21-slim +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from collections import defaultdict + + +def nb_possible_arrangements(design: str, towels: list[str]) -> int: + cache: defaultdict[str, int] = defaultdict(lambda: 0) + + cache[""""] = 1 + + for i in range(1, len(design) + 1): + design_i = design[-i:] + cache[design_i] = 0 + + for towel in towels: + if design_i.startswith(towel): + sub_design = design_i[len(towel) :] + cache[design_i] += cache[sub_design] + + return cache[design] + + +def main() -> None: + towels: list[str] = [] + designs: list[str] = [] + + with open(""input.txt"") as data: + towels = data.readline().strip().split("", "") + assert data.readline() == ""\n"" + + for line in data: + designs.append(line.strip()) + + count = 0 + for i, design in enumerate(designs): + nb = nb_possible_arrangements(design, towels) + count += nb + + print(count) + + +if __name__ == ""__main__"": + main() +",python:3.9.21-slim +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from itertools import permutations + +keypadSequences = open('input.txt').read().splitlines() + +keypad = { + '7': (0, 0), '8': (0, 1), '9': (0, 2), + '4': (1, 0), '5': (1, 1), '6': (1, 2), + '1': (2, 0), '2': (2, 1), '3': (2, 2), + '#': (3, 0), '0': (3, 1), 'A': (3, 2) +} +keypadBadPosition = (3,0) +startKeypad = (3, 2) + +directionalpad = { + '#': (0, 0), '^': (0, 1), 'A': (0, 2), + '<': (1, 0), 'v': (1, 1), '>': (1, 2) +} +directionalpadBadPosition = (0,0) +startdirectionalpad = (0, 2) + +def getNumericPart(code): + return ''.join([elem for elem in code if elem.isdigit()]) + +def getdirections(drow, dcol): + res = [] + if drow > 0: + res.append('v'*drow) + elif drow < 0: + res.append('^'*abs(drow)) + if dcol > 0: + res.append('>'*dcol) + elif dcol < 0: + res.append('<'*abs(dcol)) + return ''.join(res) + +def getPossiblePermutations(pos, directions, position): + perms = set(permutations(directions)) + validPerms = [] + for perm in perms: + if validatepath(pos, perm, position): + validPerms.append(''.join(perm)) + return validPerms + +def validatepath(pos, directions, position): + _pos = pos + for direction in directions: + if direction == 'v': + _pos = (_pos[0] + 1, _pos[1]) + elif direction == '^': + _pos = (_pos[0] - 1, _pos[1]) + elif direction == '>': + _pos = (_pos[0], _pos[1] + 1) + elif direction == '<': + _pos = (_pos[0], _pos[1] - 1) + + if _pos == position: + return False + return True + +def getDirectionToWriteCode(input): + pos = startKeypad + result = [] + for elem in input: + nextPos = keypad[elem] + drow = nextPos[0] - pos[0] + dcol = nextPos[1] - pos[1] + directions = getdirections(drow, dcol) + validPaths = getPossiblePermutations(pos, directions, keypadBadPosition) + if len(result) == 0: + for path in validPaths: + result.append(path + 'A') + elif len(result) >= 1: + temp = [] + for res in result: + for path in validPaths: + temp.append(res + path + 'A') + result = temp + pos = nextPos + + return result + + +def getDirectionToWriteDirection(input): + pos = startdirectionalpad + result = [] + for elem in input: + nextPos = directionalpad[elem] + drow = nextPos[0] - pos[0] + dcol = nextPos[1] - pos[1] + directions = getdirections(drow, dcol) + validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition) + if len(result) == 0: + for path in validPaths: + result.append(path + 'A') + elif len(result) >= 1: + temp = [] + for res in result: + for path in validPaths: + temp.append(res + path + 'A') + result = temp + pos = nextPos + + min_length = min(len(r) for r in result) + return [r for r in result if len(r) == min_length] + +def getDirectionToWriteDirectionSample(input): + pos = startdirectionalpad + result = [] + for elem in input: + nextPos = directionalpad[elem] + drow = nextPos[0] - pos[0] + dcol = nextPos[1] - pos[1] + directions = getdirections(drow, dcol) + validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition)[0] + result.append(validPaths) + result.append('A') + pos = nextPos + return ''.join(result) + + + +def calculateComplexity(code): + sol1 = getDirectionToWriteCode(code) + sol2 = [elem for sol in sol1 for elem in getDirectionToWriteDirection(sol)] + sol3 = [getDirectionToWriteDirectionSample(elem) for elem in sol2] + print(sol3[0]) + print(sol2[0]) + print(sol1[0]) + print(code) + min_length = min(len(r) for r in sol3) + num = getNumericPart(code) + print(f""Code: Numeric: {num}, minimum length: {min_length}"") + return min_length * int(num) + +total = 0 +for code in keypadSequences: + score = calculateComplexity(code) + total += score + print() +print(total) + +# >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +# <A>^AvAA<^A>A<>^AvA^A^A<^A>AAvA^A<A>^AAAvA<^A>A +# code = '029A' +# sol1 = getDirectionToWriteCode(code) +# sol2 = getDirectionToWriteDirection(sol1) +# sol3 = getDirectionToWriteDirection(sol2) +# print(sol3) +# print(sol2) +# print(sol1) +# print(code) + +# print(calculateComplexity(""029A""))",python:3.9.21-slim +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"NUMS = { + '0': (3, 1), + '1': (2, 0), + '2': (2, 1), + '3': (2, 2), + '4': (1, 0), + '5': (1, 1), + '6': (1, 2), + '7': (0, 0), + '8': (0, 1), + '9': (0, 2), + 'A': (3, 2), + '': (3, 0) +} + +ARROWS = { + '^': (0, 1), + 'A': (0, 2), + '<': (1, 0), + 'v': (1, 1), + '>': (1, 2), + '': (0, 0) +} + +DIR_TO_ARROW_MAP = { + (-1, 0): '^', + (1, 0): 'v', + (0, -1): '<', + (0, 1): '>' +} + +def get_shortest(keys, sequence): + path = [] + for i in range(len(sequence) - 1): + cur, target = keys[sequence[i]], keys[sequence[i + 1]] + next_path = [] + dirs = [] + + for y in range(cur[1] - 1, target[1] - 1, -1): + next_path.append((cur[0], y)) + dirs.append((0, -1)) + + for x in range(cur[0] + 1, target[0] + 1): + next_path.append((x, cur[1])) + dirs.append((1, 0)) + + for x in range(cur[0] - 1, target[0] - 1, -1): + next_path.append((x, cur[1])) + dirs.append((-1, 0)) + + for y in range(cur[1] + 1, target[1] + 1): + next_path.append((cur[0], y)) + dirs.append((0, 1)) + + if keys[''] in next_path: + dirs = list(reversed(dirs)) + + path += [DIR_TO_ARROW_MAP[d] for d in dirs] + ['A'] + + return """".join(path) + + +with open('input.txt') as f: + lines = f.read().splitlines() + +total_complexity = 0 + +for line in lines: + l1 = get_shortest(NUMS, 'A' + line) + l2 = get_shortest(ARROWS, 'A' + l1) + l3 = get_shortest(ARROWS, 'A' + l2) + + total_complexity += int(line[0:-1]) * len(l3) + +print(total_complexity) +",python:3.9.21-slim +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from abc import ABC +import argparse +from functools import cache +from itertools import product +from typing import Optional + +g_verbose = False + +CHR_A = ord('A') + +UP = ord('^') +DOWN = ord('v') +LEFT = ord('<') +RIGHT = ord('>') + +CHR_0 = ord('0') +CHR_1 = ord('1') +CHR_2 = ord('2') +CHR_3 = ord('3') +CHR_4 = ord('4') +CHR_5 = ord('5') +CHR_6 = ord('6') +CHR_7 = ord('7') +CHR_8 = ord('8') +CHR_9 = ord('9') + + +def get_dir_h(dx: int) -> int: + return LEFT if dx < 0 else RIGHT + + +def get_dir_v(dy: int) -> int: + return UP if dy < 0 else DOWN + + +class RobotPad(ABC): + id: int = 0 + dir_cache: dict[tuple[int, int], list[list[int]]] + pos_cache: dict[tuple[int, int], int] + child: Optional['RobotPad'] = None + + @cache + def cost_press_once(self, snapshot: tuple[int, ...]): + my_id = self.id + + if not self.child: + assert len(snapshot) == 1 + return 1, snapshot + + g_verbose and print(f'{"" "" * my_id}bot #{my_id} request parent press') + cost_moving, new_snapshot = self.child.cost_moving(CHR_A, snapshot[1:]) + cost_press, new_snapshot = self.child.cost_press_once(new_snapshot) + return cost_moving + cost_press, (snapshot[0], *new_snapshot) + + @cache + def cost_moving(self, target_button: int, snapshot: tuple[int, ...]): + my_id = self.id + current_button = snapshot[0] + + g_verbose and print(f'{"" "" * my_id}bot #{my_id} plan {chr(current_button)} -> {chr(target_button)}') + + if current_button == target_button: + g_verbose and print(f'{"" "" * my_id}bot #{my_id} not moving, already at {chr(target_button)}') + return 0, snapshot + + # Last layer + distance = self.pos_cache[current_button, target_button] + if not self.child: + g_verbose and print(f'{"" "" * my_id}bot #{my_id} move to {chr(target_button)}, cost={distance}') + assert len(snapshot) == 1 + return distance, (target_button,) + + # Move parent node to the direction I want + tracking = [] + for possible_routes in self.dir_cache[current_button, target_button]: + route_cost = 0 + route_snapshot = snapshot[1:] + for next_direction in possible_routes: + cost_moving, route_snapshot = self.child.cost_moving(next_direction, route_snapshot) + cost_press, route_snapshot = self.child.cost_press_once(route_snapshot) + route_cost += cost_moving + cost_press + tracking.append((route_cost, (target_button, *route_snapshot))) + best_cost, best_snapshot = min(tracking, key=lambda x: x[0]) + g_verbose and print(f'{"" "" * my_id}bot #{my_id} move to {chr(target_button)}, cost={best_cost}') + return best_cost, best_snapshot + + def move(self, dst: int, snapshot: tuple[int, ...]): + return self.cost_moving(dst, snapshot) + + +class NumPad(RobotPad): + def __init__(self, bot_id: int): + self.id = bot_id + self.board = [ + [0x37, 0x38, 0x39], + [0x34, 0x35, 0x36], + [0x31, 0x32, 0x33], + [0x00, 0x30, 0x41] + ] + self.pos_cache = {} + self.board_lookup = {value: (x, y) for y, row in enumerate(self.board) for x, value in enumerate(row) if value} + dir_cache: dict[tuple[int, int], list[list[int]]] = {} + for ((a, (x1, y1)), (b, (x2, y2))) in product(self.board_lookup.items(), repeat=2): + if a == b: continue + # Find the direction of move from a to b + dx = x2 - x1 + dy = y2 - y1 + + x_count = abs(dx) + y_count = abs(dy) + + # Only move in one direction + if dx == 0 or dy == 0: + dir_cache[a, b] = [[get_dir_h(dx) if dx else get_dir_v(dy)] * (x_count + y_count)] + elif a in (CHR_0, CHR_A) and b in (CHR_1, CHR_4, CHR_7): + # Can only move up and then left + dir_cache[a, b] = [[UP] * y_count + [LEFT] * x_count] + elif a in (CHR_1, CHR_4, CHR_7) and b in (CHR_0, CHR_A): + # Can only move right and then down + dir_cache[a, b] = [[RIGHT] * x_count + [DOWN] * y_count] + else: + # Can move both horizontally and vertically, any order + dir_h = get_dir_h(dx) + dir_v = get_dir_v(dy) + dir_cache[a, b] = [[dir_h] * x_count + [dir_v] * y_count, [dir_v] * y_count + [dir_h] * x_count] + + self.pos_cache[a, b] = abs(dx) + abs(dy) + self.dir_cache = dir_cache + + +class DirectionPad(RobotPad): + def __init__(self, bot_id: int): + self.id = bot_id + self.board = [ + [0x00, UP, CHR_A], + [LEFT, DOWN, RIGHT], + ] + self.board_lookup = {value: (x, y) for y, row in enumerate(self.board) for x, value in enumerate(row) if value} + self.pos_cache = {} + dir_cache: dict[tuple[int, int], list[list[int]]] = {} + for ((a, (x1, y1)), (b, (x2, y2))) in product(self.board_lookup.items(), repeat=2): + # Find the direction of move from a to b + dx = x2 - x1 + dy = y2 - y1 + self.pos_cache[a, b] = abs(dx) + abs(dy) + + x_count = abs(dx) + y_count = abs(dy) + + # Only move in one direction + if dx == 0 or dy == 0: + dir_cache[a, b] = [[get_dir_h(dx) if dx else get_dir_v(dy)] * (x_count + y_count)] + elif a == LEFT and b in (UP, CHR_A): + # Can only move right and then UP + dir_cache[a, b] = [[RIGHT] * x_count + [UP] * y_count] + elif a in (UP, CHR_A) and b == LEFT: + # Can only move down and then left + dir_cache[a, b] = [[DOWN] * y_count + [LEFT] * x_count] + else: + # Can move both horizontally and vertically, any order + dir_h = get_dir_h(dx) + dir_v = get_dir_v(dy) + dir_cache[a, b] = [[dir_h] * x_count + [dir_v] * y_count, [dir_v] * y_count + [dir_h] * x_count] + self.dir_cache = dir_cache + + +def solve_ex(codes: list[str], count: int) -> int: + root = NumPad(0) + node = root + for i in range(count): + bot = DirectionPad(i + 1) + node.child = bot + node = bot + + snapshot_init = tuple([CHR_A] * (count + 1)) + result = 0 + for code in codes: + snapshot = snapshot_init + total_cost = 0 + for current_chr in map(ord, code): + prev_char = snapshot[0] + cost, snapshot = root.cost_moving(current_chr, snapshot) + cost_press, snapshot = root.cost_press_once(snapshot) + g_verbose and print( + f""** move {chr(prev_char)} -> {chr(current_chr)} cost={cost + cost_press} pos={''.join(map(chr, snapshot))}"") + total_cost += cost + cost_press + numeric_part = int(code[:-1]) + print(f""{code} -> {total_cost} * {numeric_part}"") + result += total_cost * numeric_part + + return result + + +def solve(input_path: str, /, **_kwargs): + with open(input_path, ""r"", encoding='utf-8') as file: + input_text = file.read().strip().replace('\r', '').splitlines() + + p1 = solve_ex(input_text, 2) + print(f'p1: {p1}') + + +def main(): + global g_verbose + parser = argparse.ArgumentParser() + parser.add_argument(""input"", nargs=""?"", default=""sample.txt"") + parser.add_argument(""-v"", ""--verbose"", action=""store_true"") + parser.add_argument(""--threshold"", type=int, default=50, help=""Threshold (p2)"") + args = parser.parse_args() + g_verbose = args.verbose + solve(args.input) + + +if __name__ == ""__main__"": + main() +",python:3.9.21-slim +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"import functools +from typing import List, Tuple, Optional + +# Define the number pad and the direction pad +number_pad = [ + ""789"", + ""456"", + ""123"", + "" 0A"" +] + +direction_pad = [ + "" ^A"", + """" +] + +def parse_input(file_path: str) -> List[Tuple[str, int]]: + """""" + Parses the input file and returns a list of tuples. + + Each tuple contains a string (the stripped line) and an integer (the first three characters of the line). + + Args: + file_path (str): The path to the input file. + + Returns: + List[Tuple[str, int]]: A list of tuples where each tuple contains a string and an integer. + """""" + with open(file_path) as file: + return [(line.strip(), int(line[:3])) for line in file] + +def find_position(pad: List[str], char: str) -> Optional[Tuple[int, int]]: + """""" + Find the position of a character in a 2D list (pad). + + Args: + pad (List[str]): A 2D list representing the pad where each element is a string. + char (str): The character to find in the pad. + + Returns: + Optional[Tuple[int, int]]: A tuple containing the x and y coordinates of the character if found, + otherwise None. + """""" + for y, row in enumerate(pad): + for x, cell in enumerate(row): + if cell == char: + return x, y + return None + +def generate_path(pad: List[str], from_char: str, to_char: str) -> str: + """""" + Generate the shortest path from `from_char` to `to_char` in the given pad. + + The path is represented as a string of direction changes: + - '<' for left + - '>' for right + - '^' for up + - 'v' for down + - 'A' for arrival at the target position + + Args: + pad (List[str]): A 2D list representing the pad where each element is a character. + from_char (str): The character representing the starting position. + to_char (str): The character representing the target position. + + Returns: + str: The shortest path from `from_char` to `to_char` based on the number of direction changes. + """""" + from_x, from_y = find_position(pad, from_char) + to_x, to_y = find_position(pad, to_char) + + def move(x: int, y: int, path: str): + # If the current position is the target position, yield the path with 'A' appended + if (x, y) == (to_x, to_y): + yield path + 'A' + # Move left if possible and the target is to the left + if to_x < x and pad[y][x - 1] != ' ': + yield from move(x - 1, y, path + '<') + # Move up if possible and the target is above + if to_y < y and pad[y - 1][x] != ' ': + yield from move(x, y - 1, path + '^') + # Move down if possible and the target is below + if to_y > y and pad[y + 1][x] != ' ': + yield from move(x, y + 1, path + 'v') + # Move right if possible and the target is to the right + if to_x > x and pad[y][x + 1] != ' ': + yield from move(x + 1, y, path + '>') + + # Return the shortest path based on the number of direction changes + return min(move(from_x, from_y, """"), key=lambda p: sum(a != b for a, b in zip(p, p[1:]))) + +@functools.lru_cache(None) +def solve(sequence: str, level: int, max_level: int = 2) -> int: + """""" + Solve the problem recursively. + + Args: + sequence (str): The input sequence to process. + level (int): The current recursion level. + max_level (int, optional): The maximum recursion depth. Defaults to 2. + + Returns: + int: The result of the recursive computation. + """""" + if level > max_level: + return len(sequence) + pad = direction_pad if level else number_pad + return sum(solve(generate_path(pad, from_char, to_char), level + 1, max_level) for from_char, to_char in zip('A' + sequence, sequence)) + +if __name__ == ""__main__"": + input_data = parse_input('input.txt') + result = sum(solve(sequence, 0) * multiplier for sequence, multiplier in input_data) + print(result)",python:3.9.21-slim +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from functools import cache + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + + +@cache +def num_keypad_paths(start, end): + output = [] + x_diff = abs(end[0] - start[0]) + y_diff = abs(end[1] - start[1]) + horiz_char = "">"" if end[0] > start[0] else ""<"" + vert_char = ""v"" if end[1] > start[1] else ""^"" + for path in { + tuple([horiz_char] * x_diff + [vert_char] * y_diff), + tuple([vert_char] * y_diff + [horiz_char] * x_diff), + }: + if not ( + (start == (0, 0) and path[:3] == (""v"", ""v"", ""v"")) + or (start == (0, 1) and path[:2] == (""v"", ""v"")) + or (start == (0, 2) and path[:1] == (""v"",)) + or (start == (1, 3) and path[:1] == (""<"",)) + or (start == (2, 3) and path[:2] == (""<"", ""<"")) + ): + output.append(list(path) + [""A""]) + return output + + +@cache +def dir_keypad_paths(start, end): + output = [] + x_diff = abs(end[0] - start[0]) + y_diff = abs(end[1] - start[1]) + horiz_char = "">"" if end[0] > start[0] else ""<"" + vert_char = ""v"" if end[1] > start[1] else ""^"" + for path in { + tuple([horiz_char] * x_diff + [vert_char] * y_diff), + tuple([vert_char] * y_diff + [horiz_char] * x_diff), + }: + if not ( + (start == (1, 0) and path[:1] == (""<"",)) + or (start == (2, 0) and path[:2] == (""<"", ""<"")) + or (start == (0, 1) and path[:1] == (""^"",)) + ): + output.append(list(path) + [""A""]) + return output + + +num_keypad = { + ""7"": (0, 0), + ""8"": (1, 0), + ""9"": (2, 0), + ""4"": (0, 1), + ""5"": (1, 1), + ""6"": (2, 1), + ""1"": (0, 2), + ""2"": (1, 2), + ""3"": (2, 2), + ""0"": (1, 3), + ""A"": (2, 3), +} +directional_keypad = {""^"": (1, 0), ""A"": (2, 0), ""<"": (0, 1), ""v"": (1, 1), "">"": (2, 1)} + +total = 0 +for code in input_text: + current_pos = (2, 3) + solutions = [[]] + for character in code: + new_pos = num_keypad[character] + solutions = [ + solution + path + for solution in solutions + for path in num_keypad_paths(current_pos, new_pos) + ] + current_pos = new_pos + solutions_2_outer = [] + for solution in solutions: + current_pos = (2, 0) + solutions_2 = [[]] + for character in solution: + new_pos = directional_keypad[character] + solutions_2 = [ + partial_solution + path + for partial_solution in solutions_2 + for path in dir_keypad_paths(current_pos, new_pos) + ] + current_pos = new_pos + solutions_2_outer += solutions_2 + solutions_3_outer = [] + for solution in solutions_2_outer: + current_pos = (2, 0) + solutions_3 = [[]] + for character in solution: + new_pos = directional_keypad[character] + solutions_3 = [ + partial_solution + path + for partial_solution in solutions_3 + for path in dir_keypad_paths(current_pos, new_pos) + ] + current_pos = new_pos + solutions_3_outer += solutions_3 + total += min(len(x) for x in solutions_3_outer) * int(code[:3]) +print(total) +",python:3.9.21-slim +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"from part1 import parse_input, solve + +if __name__ == ""__main__"": + input_data = parse_input('input.txt') + result = sum(solve(sequence, 0, 25) * multiplier for sequence, multiplier in input_data) + print(result)",python:3.9.21-slim +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"from collections import defaultdict, Counter + +NUMS = { + '0': (3, 1), + '1': (2, 0), + '2': (2, 1), + '3': (2, 2), + '4': (1, 0), + '5': (1, 1), + '6': (1, 2), + '7': (0, 0), + '8': (0, 1), + '9': (0, 2), + 'A': (3, 2), + '': (3, 0) +} + +ARROWS = { + '^': (0, 1), + 'A': (0, 2), + '<': (1, 0), + 'v': (1, 1), + '>': (1, 2), + '': (0, 0) +} + +DIR_TO_ARROW_MAP = { + (-1, 0): '^', + (1, 0): 'v', + (0, -1): '<', + (0, 1): '>' +} + +memo = dict() + +def get_shortest(keys, sequence): + path = [] + for i in range(len(sequence) - 1): + cur, target = keys[sequence[i]], keys[sequence[i + 1]] + next_path = [] + dirs = [] + + for y in range(cur[1] - 1, target[1] - 1, -1): + next_path.append((cur[0], y)) + dirs.append((0, -1)) + + for x in range(cur[0] + 1, target[0] + 1): + next_path.append((x, cur[1])) + dirs.append((1, 0)) + + for x in range(cur[0] - 1, target[0] - 1, -1): + next_path.append((x, cur[1])) + dirs.append((-1, 0)) + + for y in range(cur[1] + 1, target[1] + 1): + next_path.append((cur[0], y)) + dirs.append((0, 1)) + + if keys[''] in next_path: + dirs = list(reversed(dirs)) + + to_append = [DIR_TO_ARROW_MAP[d] for d in dirs] + ['A'] + path += to_append + + return """".join(path).split(""A"")[0:-1] + +def count_parts(path): + return Counter([s +""A"" for s in path]) + + +with open('input.txt') as f: + lines = f.read().splitlines() + +total_complexity = 0 + +for line in lines: + counts = count_parts(get_shortest(NUMS, 'A' + line)) + + for i in range(25): + next_counts = defaultdict(int) + for seq, count in counts.items(): + for k, v in count_parts(get_shortest(ARROWS, 'A' + seq)).items(): + next_counts[k] += count * v + + counts = next_counts + + length = sum([len(k) * v for k, v in counts.items()]) + total_complexity += int(line[0:-1]) * length + +print(total_complexity)",python:3.9.21-slim +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"import functools + + +with open(""21.txt"") as i: + input = [x.strip() for x in i.readlines()] + +test_data = """"""029A +980A +179A +456A +379A"""""".split(""\n"") + +# input = test_data + +# +---+---+---+ +# | 7 | 8 | 9 | +# +---+---+---+ +# | 4 | 5 | 6 | +# +---+---+---+ +# | 1 | 2 | 3 | +# +---+---+---+ +# | 0 | A | +# +---+---+ +numeric_keys = { + ""7"": (0, 0), ""8"": (1, 0), ""9"": (2, 0), + ""4"": (0, 1), ""5"": (1, 1), ""6"": (2, 1), + ""1"": (0, 2), ""2"": (1, 2), ""3"": (2, 2), + ""0"": (1, 3), ""A"": (2, 3), +} + +# +---+---+ +# | ^ | A | +#+---+---+---+ +#| < | v | > | +#+---+---+---+ +directional_keys = { + ""^"": (1, 0), ""A"": (2, 0), + ""<"": (0, 1), ""v"": (1, 1), "">"": (2,1) +} + +allowed_num_pos = [v for v in numeric_keys.values()] +allowed_dir_pos = [v for v in directional_keys.values()] +pos = (2,3) +x, y = pos + + +def find_keystrokes(src, target, directional): + if src == target: return [""A""] + if not directional and not src in allowed_num_pos: return [] + if directional and not src in allowed_dir_pos: return [] + x1, y1 = src + x2, y2 = target + res = [] + if x1""+s for s in find_keystrokes((x1+1, y1), target, directional)]) + elif x1>x2: res.extend([""<""+s for s in find_keystrokes((x1-1, y1), target, directional)]) + if y1y2: res.extend([""^""+s for s in find_keystrokes((x1, y1-1), target, directional)]) + return res + + +@functools.cache +def find_shortest_to_click(a, b, depth=2): + # Assume we start at A always? + opts = find_keystrokes(directional_keys[a], directional_keys[b], True) + if depth == 1: + return min([len(x) for x in opts]) + + tmps = [] + for o in opts: + tmp = [] + tmp.append(find_shortest_to_click(""A"", o[0], depth-1)) + for i in range(1, len(o)): + tmp.append(find_shortest_to_click(o[i-1], o[i], depth-1)) + tmps.append(sum(tmp)) + + return min(tmps) + + +def find_shortest(code, levels): + pos = numeric_keys[""A""] + shortest = 0 + for key in code: + possible_key_sequences = find_keystrokes(pos, numeric_keys[key], False) + tmps = [] + for sequence in possible_key_sequences: + tmp = [] + tmp.append(find_shortest_to_click(""A"", sequence[0], levels)) + for i in range(1, len(sequence)): + tmp.append(find_shortest_to_click(sequence[i-1], sequence[i], levels)) + + tmps.append(sum(tmp)) + pos = numeric_keys[key] + shortest += min(tmps) + return shortest + + +def find_total_complexity(codes, levels): + complexities = [] + for code in input: + s = find_shortest(code, levels) + complexities.append(s*int(code[:-1])) + return sum(complexities) + + +print(find_total_complexity(input, 25))",python:3.9.21-slim +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"#!/usr/bin/env python3 + +import re +from collections import deque +from itertools import product + +myfile = open(""21.in"", ""r"") +lines = myfile.read().strip().splitlines() +myfile.close() + +part_two = 0 + +# fmt: off +num_pad = { + (0, 0): ""7"", (1, 0): ""8"", (2, 0): ""9"", + (0, 1): ""4"", (1, 1): ""5"", (2, 1): ""6"", + (0, 2): ""1"", (1, 2): ""2"", (2, 2): ""3"", + (1, 3): ""0"", (2, 3): ""A"", +} +num_pad_t = {v: k for k, v in num_pad.items()} + +dir_pad = { + (1, 0): ""^"", (2, 0): ""A"", + (0, 1): ""<"", (1, 1): ""v"", (2, 1): "">"", +} +dir_pad_t = {v: k for k, v in dir_pad.items()} +# fmt: on + +button_dirs = {""<"": (-1, 0), "">"": (1, 0), ""^"": (0, -1), ""v"": (0, 1)} + + +def dfs(start, end, use_dir_pad=True): + key_pad = dir_pad if use_dir_pad else num_pad + sequences = set() + seen = set() + q = deque([("""", start)]) + while q: + sequence, pos = q.popleft() + seen.add(pos) + if pos == end: + sequences.add(sequence + ""A"") + continue + + buttons = [""<"", ""^"", ""v"", "">""] + for btn in buttons: + d_x, d_y = button_dirs[btn] + next_pos = (pos[0] + d_x, pos[1] + d_y) + if next_pos not in seen and next_pos in key_pad: + q.append((sequence + btn, next_pos)) + + min_len = min(len(x) for x in sequences) + return {x for x in sequences if len(x) == min_len} + + +def get_sequences(sequence, use_dir_pad=True): + key_pad_t = dir_pad_t if use_dir_pad else num_pad_t + sub_sequences = [] + start = key_pad_t[""A""] + for c in sequence: + end = key_pad_t[c] + sub_sequences.append(dfs(start, end, use_dir_pad)) + start = end + sequences = {"""".join(x) for x in product(*sub_sequences)} + min_len = min(len(x) for x in sequences) + return {x for x in sequences if len(x) == min_len} + + +memo = {} + + +def solve(sequence, robots, is_code=False): + if robots == 0: + return len(sequence) + + if (sequence, robots) not in memo: + total = 0 + sub_sequences = list(re.findall(r"".*?A"", sequence)) + for sub_seq in sub_sequences: + total += min( + solve(s, robots - 1) for s in get_sequences(sub_seq, not is_code) + ) + memo[(sequence, robots)] = total + + return memo[(sequence, robots)] + + +for code in lines: + numeric_code = int(code[:-1]) + part_two += solve(code, 26, is_code=True) * numeric_code + +print(""Part Two:"", part_two)",python:3.9.21-slim +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"#day 21 +import os +from itertools import pairwise +from functools import cache + + +def reader(): + return open(f""input.txt"", 'r').read().splitlines() + + +def getPT(G, chars): + P = {c: (i, j) for i, r in enumerate(G) for j, c in enumerate(r)} + T = {c1: {c2: set() for c2 in chars} for c1 in chars} + for c1 in T: + for c2 in T[c1]: + (x1, y1), (x2, y2) = P[c1], P[c2] + v, vc = 'v' if x1 < x2 else '^', abs(x2 - x1) + h, hc = '>' if y1 < y2 else '<', abs(y2 - y1) + if G[x1][y2] in chars: + T[c1][c2].add(h * hc + v * vc) + if G[x2][y1] in chars: + T[c1][c2].add(v * vc + h * hc) + return P, T + + +def part2(): + f = reader() + G0 = [ + ['7', '8', '9'], + ['4', '5', '6'], + ['1', '2', '3'], + ['#', '0', 'A'], + ] + GC = [ + ['#', '^', 'A'], + ['<', 'v', '>'] + ] + + _, G0T = getPT(G0, '0123456789A') + _, GCT = getPT(GC, '<^>vA') + + def r(T, s, i=0, c='A'): + return [[t1] + t2 for t1 in T[c][s[i]] for t2 in r(T, s, i + 1, s[i])] if i < len(s) else [[]] + + @cache + def count(c1, c2, M): + return min(sum(count(cc1, cc2, M - 1) + for cc1, cc2 in pairwise('A' + t + 'A')) for t in GCT[c1][c2]) if M > 0 else 1 + + ans = 0 + for s0 in f: + l = min(sum(count(cc1, cc2, 25) + for cc1, cc2 in pairwise('A' + t + 'A')) for t in map(lambda l: 'A'.join(l), r(G0T, s0))) + ans += l * int(s0[:-1]) + print(ans) + + +part2()",python:3.9.21-slim +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"from collections import defaultdict + +with open('input.txt') as f: + lines = f.read().splitlines() + +connections = defaultdict(set) +pairs = [tuple(line.split(""-"")) for line in lines] +for pair in pairs: + connections[pair[0]].add(pair[1]) + connections[pair[1]].add(pair[0]) + +trios = set() +for pair in pairs: + intersection = connections[pair[0]].intersection(connections[pair[1]]) + for val in intersection: + trios.add(tuple(sorted((pair[0], pair[1], val)))) + +trios_with_t = [trio for trio in trios if any(v.startswith(""t"") for v in trio)] +print(len(trios_with_t))",python:3.9.21-slim +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"import argparse +import re +from collections import defaultdict +from typing import Iterable + + +class Network: + completed_networks: defaultdict[int, set[tuple[str, ...]]] + nodes: defaultdict[str, set[str]] + + def __init__(self, text: str): + cache: defaultdict[str, set[str]] = defaultdict(set) + for m in re.finditer(r'(..)-(..)', text): + a = m.group(1) + b = m.group(2) + cache[a].add(b) + cache[b].add(a) + self.nodes = cache + self.completed_networks = defaultdict(set) + + def get_names(self): + return self.nodes.keys() + + def get_largest_networks(self): + largest_network_length = max(*self.completed_networks.keys()) + return list(self.completed_networks[largest_network_length]) + + def get_complete_network_with_n_nodes(self, n: int): + return list(self.completed_networks[n]) + + def build_network_for(self, names: Iterable[str]): + networks = self.completed_networks + for name in names: + name_pool = set(self.nodes[name]) + + depth = 1 + work: set[tuple[str, ...]] = {(name,)} + while work: + next_work = set() + for network in work: + # Don't bother with already explored networks + if network in networks[depth]: continue + networks[depth].add(network) + + for next_name in name_pool.difference(network): + if self.nodes[next_name].issuperset(network): + next_work.add(tuple(sorted({*network, next_name}))) + depth += 1 + work = next_work + + +def solve(input_path: str, /, **_kwargs): + with open(input_path, ""r"", encoding='utf-8') as file: + input_text = file.read().strip().replace('\r', '') + + network = Network(input_text) + + names_with_t = [name for name in network.get_names() if name.startswith('t')] + network.build_network_for(names_with_t) + p1 = len(network.get_complete_network_with_n_nodes(3)) + print(f'p1 = {p1}') + + largest_networks = network.get_largest_networks() + assert len(largest_networks) == 1, ""p2 solution should have a single, unique answer"" + + p2 = ','.join(largest_networks[0]) + print(f'p2 = {p2}') + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument(""input"", nargs=""?"", default=""sample.txt"") + parser.add_argument(""-v"", ""--verbose"", action=""store_true"") + args = parser.parse_args() + solve(args.input, verbose=args.verbose) + + +if __name__ == ""__main__"": + main() +",python:3.9.21-slim +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"from collections import defaultdict + +with open(""./day_23.in"") as fin: + lines = fin.read().strip().split(""\n"") + +adj = defaultdict(list) +for line in lines: + a, b = line.split(""-"") + adj[a].append(b) + adj[b].append(a) + +triangles = set() +for a in dict(adj): + for i in adj[a]: + for j in adj[a]: + if j in adj[i]: + triangles.add(tuple(sorted([a, i, j]))) + +ans = 0 +for a, b, c in triangles: + if ""t"" in [a[0], b[0], c[0]]: + ans += 1 + +print(ans) +",python:3.9.21-slim +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"def readfile(): + file_name = ""23.txt"" + + mapping = {} + with open(file_name) as f: + tuples = [tuple(line.strip().split(""-"")) for line in f.readlines()] + + # Add reverse order as well + tuples += [(i[1], i[0]) for i in tuples] + + # Map all computers to which they are connected + for key, val in tuples: + if key in mapping: + mapping[key].append(val) + else: + mapping[key] = [val] + + return mapping + + +def make_mapping_part1(mapping, computer, depth, lan_party, lan_parties): + # We have reached 3 computers so make sure that we have closed the loop + if depth == 0: + if lan_party[0] == lan_party[-1] and any( + [i.startswith(""t"") for i in lan_party] + ): + lan_parties.add(tuple(sorted(lan_party[:3]))) + return + + # Check all computers that are connected to the current one + for val in mapping[computer]: + lan_party.append(val) + make_mapping_part1(mapping, val, depth - 1, lan_party, lan_parties) + del lan_party[-1] + + +def part1(mapping): + lan_parties = set() + # Find all lan parties with exactly 3 computers + for computer in mapping: + make_mapping_part1(mapping, computer, 3, [computer], lan_parties) + + print(len(lan_parties)) + +if __name__ == ""__main__"": + test_file = False + mapping = readfile() + + print(""Answer to part 1:"") + part1(mapping)",python:3.9.21-slim +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"#!/usr/bin/env python3 + +from collections import defaultdict +from itertools import combinations + +myfile = open(""23.in"", ""r"") +lines = myfile.read().strip().splitlines() +myfile.close() + +conns = defaultdict(set) + +part_one = 0 + +for line in lines: + a, b = line.split(""-"") + conns[a].add(b) + conns[b].add(a) + + +trios = set() +for comp, others in conns.items(): + pairs = combinations(others, 2) + for a, b in pairs: + if b in conns[a]: + trios.add(frozenset([comp, a, b])) + +for t in trios: + if any(x.startswith(""t"") for x in t): + part_one += 1 + + +print(""Part One:"", part_one)",python:3.9.21-slim +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +de-ta +ka-de +The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. + +What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict + +def bron_kerbosch(connections, R, P, X): + if len(P) == 0 and len(X) == 0: + yield R + + while len(P) > 0: + v = P.pop() + yield from bron_kerbosch(connections, R.union(set([v])), P.intersection(connections[v]), X.intersection(connections[v])) + X = X.union(set([v])) + + +with open('input.txt') as f: + lines = f.read().splitlines() + +connections = defaultdict(set) +pairs = [tuple(line.split(""-"")) for line in lines] +for pair in pairs: + connections[pair[0]].add(pair[1]) + connections[pair[1]].add(pair[0]) + +cliques = bron_kerbosch(connections, set(), set(connections.keys()), set()) + +print("","".join(sorted(max(cliques, key=len))))",python:3.9.21-slim +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +de-ta +ka-de +The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. + +What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","f = open(""input.23.txt"") + +graph = {} +for p in f: + [a,b] = p.strip().split(""-"") + if(a in graph.keys()): + graph[a].append(b) + else: + graph[a] = [b] + if(b in graph.keys()): + graph[b].append(a) + else: + graph[b] = [a] +f.close() + +triplets = [] + + + +v = [] #visited + +def gettriplet(n2,n1): + ret = [] + for n3 in graph[n2]: + if n1 in graph[n3]: + ret.append('-'.join(sorted([n1,n2,n3]))) + return ret + +for n in graph.keys(): + if n in v: + continue + v.append(n) + for nbr in graph[n]: + t = gettriplet(nbr,n) + if len(t) > 0: + triplets.extend(t) + +ans = 0 +triplets = list(set(triplets)) +for triplet in triplets: + if triplet.find('t') >= 0: + ans += 1 + print(triplet) + +print(ans)",python:3.9.21-slim +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +de-ta +ka-de +The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. + +What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict +import itertools + +def is_clique(connections, nodes): + for i, node1 in enumerate(nodes): + for _, node2 in enumerate(nodes[i+1:]): + if node2 not in connections[node1]: + return False + + return True + +def max_clique_starting_at(connections, node): + neighbors = connections[node] + for i in range(len(neighbors), 1, -1): + for group in itertools.combinations(neighbors, i): + if is_clique(connections, group): + return set([node, *group]) + + return set() + + +with open('input.txt') as f: + lines = f.read().splitlines() + +connections = defaultdict(set) +pairs = [tuple(line.split(""-"")) for line in lines] +for pair in pairs: + connections[pair[0]].add(pair[1]) + connections[pair[1]].add(pair[0]) + +cliques = [max_clique_starting_at(connections, node) for node in connections.keys()] +max_clique = max(cliques, key=len) + +print("","".join(sorted(max_clique)))",python:3.9.21-slim +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +de-ta +ka-de +The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. + +What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict +from copy import deepcopy + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +connections = defaultdict(set) +for connection in input_text: + person1, person2 = connection.split(""-"") + connections[person1].add(person2) + connections[person2].add(person1) + +max_clique_size = 0 +max_clique = set() + + +def bron_kerbosch(R, P, X): + global max_clique + global max_clique_size + if (not P) and (not X) and len(R) > max_clique_size: + max_clique = R + max_clique_size = len(R) + for person in deepcopy(P): + bron_kerbosch(R | {person}, P & connections[person], X & connections[person]) + P -= {person} + X |= {person} + + +bron_kerbosch(set(), set(connections.keys()), set()) +print("","".join(sorted(max_clique))) +",python:3.9.21-slim +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +de-ta +ka-de +The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. + +What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","def parse() -> list[tuple[str]]: + return [(line.strip().split(""-"")[0], line.strip().split(""-"")[1]) for line in open(""input.txt"").readlines()] + +def generate_graph(connections) -> dict: + nodes = {} + for connection in connections: + if nodes.get(connection[0]) == None: + nodes[connection[0]] = set() + if nodes.get(connection[1]) == None: + nodes[connection[1]] = set() + nodes[connection[0]].add(connection[1]) + nodes[connection[1]].add(connection[0]) + return nodes + +def part1(): + connections = parse() + graph = generate_graph(connections) + + # Finds a three length loop with at least one containg t + found = set() + for node, neighbors in graph.items(): + for neighbor in neighbors: + for neighbors_neighbor in graph[neighbor]: + if node in graph[neighbors_neighbor]: + if node.startswith(""t"") or neighbor.startswith(""t"") or neighbors_neighbor.startswith(""t""): + s = sorted([node, neighbor, neighbors_neighbor]) + found.add(tuple(s)) + + print(len(found)) + +def neighbors_all(node: str, graph: dict, subgraph: set) -> bool: + for n in subgraph: + if node not in graph[n]: + return False + return True + +def part2(): + connections = parse() + graph = generate_graph(connections) + + biggest_subgraph = set() + for node, neighbors in graph.items(): + result = set() + result.add(node) + for neighbor in neighbors: + if neighbors_all(neighbor, graph, result): + result.add(neighbor) + + if len(result) > len(biggest_subgraph): + biggest_subgraph = result + + in_order = sorted([x for x in biggest_subgraph]) + + print("","".join(in_order)) + +part2()",python:3.9.21-slim +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"import operator +from pprint import pprint +import re + + +with open(""input24.txt"") as i: + input = [x.strip() for x in i.readlines()] + +test_data_1 = """"""x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02"""""".split(""\n"") + +test_data_2 = """"""x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj"""""".split(""\n"") + +# input = test_data_1 +# input = test_data_2 + +wires = {} +i = 0 +while input[i]!="""": + n, v = input[i].split("": "") + wires[n] = int(v) + i += 1 + +operator_lookup = { ""AND"": operator.and_, ""OR"": operator.or_, ""XOR"": operator.xor } + +gates = {} +for l in input[i+1:]: + l, op, r, o = re.match(r""(.+) (AND|OR|XOR) (.+) -> (.+)"", l).groups() + gates[o] = (l, operator_lookup[op], r) + +def get_bit(name: str) -> int: + if name in wires.keys(): + return wires[name] + l, op, r = gates[name] + res = op(get_bit(l), get_bit(r)) + return res + +bit_count = max([int(x[1:]) for x in gates.keys() if x.startswith(""z"")])+1 + +res = 0 +for i in range(bit_count-1,-1, -1): + b = get_bit(f""z{i:02}"") + res = (res<<1) | b + +print(res) + + +def swap_gates(a, b): + t = gates[a] + gates[a] = gates[b] + gates[b] = t + + +def add(a: int, b: int) -> int: + for i in range(bit_count): + wires[f""x{i:02}""] = (a>>i)%2 + wires[f""y{i:02}""] = (b>>i)%2 + + res = 0 + try: + for i in range(bit_count-1,-1, -1): + c = get_bit(f""z{i:02}"") + res = (res<<1) | c + except RecursionError: + raise ""Loop detected"" + return res + + +def find_gate(a, op, b): + for k, v in gates.items(): + aa, opp, bb = v + if ((a==aa and b==bb) or (a==bb and b==aa)) and opp==op: + return k + + return None + +def find_gate2(a, op): + for k, v in gates.items(): + if (v[0]==a or v[2]==a) and op==v[1]: + return k + +print() + +# f[i] = x[i] xor y[i] +# g[i] = x[i] and y[i] + +# z[i] = (x[i] xor y[i]) xor r[i-1] +# z[i] = f[i] xor r[i-1] + +# r[i] = (x[i] and y[i]) or ((x[i] xor y[i]) and r[i-1]) +# r[i] = g[i] or (f[i] and r[i-1]) + +remainders = [find_gate(""x00"", operator.and_, ""y00"")] +f = [find_gate(f""x{i:02}"", operator.xor, f""y{i:02}"") for i in range(0, bit_count)] +g = [find_gate(f""x{i:02}"", operator.and_, f""y{i:02}"") for i in range(0, bit_count)] + +swaps = [] +for i in range(1, bit_count-1): + e = find_gate2(f[i], operator.xor) + if e is not None and e!=f""z{i:02}"": + swaps.append((e, f""z{i:02}"")) + elif e is None: + print(f""No swap found for bit {i}..."") + # e = find_gate2(remainders[i-1], operator.xor) + # print(e) + # print(remainders) + # swaps.append() + + # x = find_gate2(f[i], operator.and_) + # rr = find_gate2(g[i], operator.or_) + # print(x, rr) + remainders.append(find_gate2(g[i], operator.or_)) + +print("","".join(sorted([x for y in swaps for x in y]))) +",python:3.9.21-slim +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +states = {} +z_wires = [] +XOR = [] +OR = [] +AND = [] +for line in input_text: + if "":"" in line: + wire, value = line.split("": "") + states[wire] = bool(int(value)) + elif ""XOR"" in line: + wires, output = line.split("" -> "") + wire1, wire2 = wires.split("" XOR "") + XOR.append((wire1, wire2, output)) + if output[0] == ""z"": + z_wires.append(output) + elif ""OR"" in line: + wires, output = line.split("" -> "") + wire1, wire2 = wires.split("" OR "") + OR.append((wire1, wire2, output)) + if output[0] == ""z"": + z_wires.append(output) + elif ""AND"" in line: + wires, output = line.split("" -> "") + wire1, wire2 = wires.split("" AND "") + AND.append((wire1, wire2, output)) + if output[0] == ""z"": + z_wires.append(output) +while not all(z in states for z in z_wires): + for op_list, op in ((XOR, ""__xor__""), (OR, ""__or__""), (AND, ""__and__"")): + new_list = [] + for wire1, wire2, output in op_list: + if states.get(wire1) is not None and states.get(wire2) is not None: + states[output] = getattr(states[wire1], op)(states[wire2]) + else: + new_list.append((wire1, wire2, output)) + op_list = new_list +place = 0 +total = 0 +while f""z{place:02d}"" in states: + total += int(states[f""z{place:02d}""]) << place + place += 1 +print(total) +",python:3.9.21-slim +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"wires = {} +gates = [] + +with open(""day24-data.txt"") as f: + + initial = True + for line in f.readlines(): + if line == ""\n"": + initial = False + continue + + if initial: + wires[line.split()[0].strip(':')] = int(line.split()[1]) + else: + gate = line.strip('\n').split() + gates.append([gate[0], gate[1], gate[2], gate[4], False]) + + for gate in gates: + if gate[0] not in wires: + wires[gate[0]] = -1 + if gate[2] not in wires: + wires[gate[2]] = -1 + + all_done = False + while not all_done: + print('*', end='') + all_done = True + for gate in gates: + if wires[gate[0]] != -1 and wires[gate[2]] != -1 and gate[4] == False: + if gate[1] == ""AND"": + wires[gate[3]] = 1 if wires[gate[0]] + wires[gate[2]] == 2 else 0 + elif gate[1] == ""OR"": + wires[gate[3]] = 1 if wires[gate[0]] + wires[gate[2]] >= 1 else 0 + else: + wires[gate[3]] = 1 if wires[gate[0]] != wires[gate[2]] else 0 + gate[4] = True + print('.', end='') + elif gate[4] == False: + all_done = False + print() + +#print(sorted(wires.items())) +#print(gates) + +output = {} +for key, val in wires.items(): + if key[0] == 'z': + output[key] = val + +sorted_output = dict(sorted(output.items())) +power = 0 +dec = 0 +for key, val in sorted_output.items(): + print(key, val) + dec += val * (2**power) + power += 1 + +print(dec) +",python:3.9.21-slim +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"#!/usr/bin/python3 + +class Wire: + + def __init__(self, name, wire_val): + self.name = name + self.wire_val = wire_val + +class Gate: + + def __init__(self, logic:str, input_1:str, input_2:str): + self.logic = logic + self.input_1 = input_1 + self.input_2 = input_2 + + def get_output(self, wire_dict:dict) -> str: + if self.logic == ""AND"": + return (""1"" if wire_dict[self.input_1].wire_val == ""1"" + and wire_dict[self.input_2].wire_val == ""1"" + else ""0"") + elif self.logic == ""OR"": + return (""1"" if wire_dict[self.input_1].wire_val == ""1"" + or wire_dict[self.input_2].wire_val == ""1"" + else ""0"") + elif self.logic == ""XOR"": + return (""1"" if wire_dict[self.input_1].wire_val + != wire_dict[self.input_2].wire_val + else ""0"") + + +with open(""input.txt"") as file: + wires = {} + gates = {} + for line in file: + line = line.strip() + if "":"" in line: + wires[line.split("": "")[0]] = Wire(line.split("": "")[0], + line.split("": "")[1]) + elif ""->"" in line: + gates[line.split()[4]] = Gate(line.split()[1], + line.split()[0], line.split()[2]) + +while any(gate not in wires for gate in gates): + for gate in gates: + if (gates[gate].input_1 in wires.keys() + and gates[gate].input_2 in wires.keys()): + out_val = gates[gate].get_output(wires) + wires[gate] = Wire(gate, out_val) + +z_wires = sorted([wires[wire].name for wire in wires + if wires[wire].name.startswith(""z"")]) +z_bits = """".join([wires[z].wire_val for z in z_wires[::-1]]) + +print('Decimal number output on the wires starting with ""z"":', int(z_bits, 2)) +",python:3.9.21-slim +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"#!/usr/bin/env python3 + +from collections import deque + +myfile = open(""24.in"", ""r"") +lines = myfile.read().strip().split(""\n\n"") +myfile.close() +in_vals, out_vals = lines[0].splitlines(), lines[1].splitlines() + +wires = {} +for line in in_vals: + wire, val = line.split("": "") + wires[wire] = int(val) + +q = deque(out_vals) +while q: + curr = q.popleft() + wires_in, out_wire = curr.split("" -> "") + left, op, right = wires_in.split("" "") + + if left not in wires or right not in wires: + q.append(curr) + continue + + result = -1 + if op == ""XOR"": + result = wires[left] ^ wires[right] + elif op == ""OR"": + result = wires[left] | wires[right] + elif op == ""AND"": + result = wires[left] & wires[right] + + wires[out_wire] = result + +x_wires, y_wires, z_wires = [], [], [] +for wire in wires.keys(): + if ""x"" in wire: + x_wires.append(wire) + elif ""y"" in wire: + y_wires.append(wire) + elif ""z"" in wire: + z_wires.append(wire) + +x_wires.sort(reverse=True) +y_wires.sort(reverse=True) +z_wires.sort(reverse=True) +x_digits = [str(wires[w]) for w in x_wires] +y_digits = [str(wires[w]) for w in y_wires] +z_digits = [str(wires[w]) for w in z_wires] +x_dec = int("""".join(x_digits), 2) +y_dec = int("""".join(y_digits), 2) +z_dec = int("""".join(z_digits), 2) + +part_one = z_dec + +print(""Part One:"", part_one) + +# part two analysis for manual solving +print() +print(""Part Two Analysis"") +width = len(z_digits) +expected = f""{x_dec + y_dec:0{width}b}""[::-1] +actual = f""{z_dec:0{width}b}""[::-1] + +# z wires that must swap +must_swap = [] +for line in out_vals: + wires_in, out_wire = line.split("" -> "") + left, op, right = wires_in.split("" "") + if out_wire.startswith(""z""): + if out_wire != f""z{width - 1}"" and op != ""XOR"": + must_swap.append(out_wire) + elif out_wire == f""z{width - 1}"" and op != ""OR"": + must_swap.append(out_wire) +print(""Must swap:"") +print("", "".join(must_swap)) + +# z wires where something is wrong +wrong_z = [] +for i, digit in enumerate(expected): + if digit != actual[i]: + wrong_z.append(f""z{i:02}"") +print(""Investigate:"") +print("", "".join(wrong_z)) +",python:3.9.21-slim +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. + +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","class Gate: + def __init__(self, inputs, op, label): + self.inputs = inputs + self.op = op + self.label = label + + def __eq__(self, other): + if type(self) == type(other): + return self.op == other.op and self.inputs == other.inputs and self.label == self.label + else: + return False + + def __hash__(self): + return hash((self.op, self.inputs, self.label)) + + def __str__(self): + first, second = sorted(map(str, self.inputs)) + return f""({first} {self.op} {second})"" + + + +class Circuit: + def __init__(self, input_lines): + self.input_digit_xors = [] + self.input_digit_ands = [] + self.output_to_expr = {} + self.expr_to_output = {} + self.invalid_input_ands = {} + self.result_gates = [] + self.carry_gates = [] + self.__parse_input(input_lines) + + def __parse_input(self, input_lines): + for line in input_lines: + if ""->"" in line: + expr, wire = line.split("" -> "") + left, op, right = expr.split("" "") + + left, right = sorted((left, right)) + self.output_to_expr[wire] = (left, right, op) + self.expr_to_output[(left, right, op)] = wire + + input_exprs = dict({(k, v) for (k, v) in self.expr_to_output.items() if k[0].startswith(""x"")}) + + for input_expr in sorted(input_exprs.items()): + idx = int(input_expr[0][0][1:]) + op = input_expr[0][2] + res = input_expr[1] + if op == 'AND': + self.input_digit_ands.append(res) + if (res.startswith(""z"")): + self.invalid_input_ands[idx] = res + elif op == 'XOR': + self.input_digit_xors.append(res) + + for i in range(len(self.input_digit_xors) + 1): + input_bits_xor_gate = Gate((f""x{i:02}"", f""y{i:02}""), ""XOR"", None) + input_bits_and_gate = Gate((f""x{i:02}"", f""y{i:02}""), ""AND"", None) + if i == 0: + result_gate = input_bits_xor_gate + carry_gate = input_bits_and_gate + else: + result_gate = Gate((input_bits_xor_gate, self.carry_gates[i - 1]), ""XOR"", None) + carry_gate = Gate((input_bits_and_gate, Gate((input_bits_xor_gate, self.carry_gates[i - 1]), ""AND"", None)), ""OR"", None) + + self.result_gates.append(result_gate) + self.carry_gates.append(carry_gate) + + print(self.result_gates[-1]) + + +with open('input.txt') as f: + lines = f.read().splitlines() + +circuit = Circuit(lines) + +output_to_expr = dict() +expr_to_output = dict() + +for line in lines: + if ""->"" in line: + expr, wire = line.split("" -> "") + left, op, right = expr.split("" "") + + left, right = sorted((left, right)) + output_to_expr[wire] = (left, right, op) + expr_to_output[(left, right, op)] = wire + +input_exprs = dict({(k, v) for (k, v) in expr_to_output.items() if k[0].startswith(""x"")}) + +input_digit_xors = [] +input_digit_ands = [] +output_digit_carries = [] +output_digit_results = [] + +invalid_input_ands = {} + +for input_expr in sorted(input_exprs.items()): + idx = int(input_expr[0][0][1:]) + op = input_expr[0][2] + res = input_expr[1] + if op == 'AND': + input_digit_ands.append(res) + if (res.startswith(""z"")): + print(f""{res} is an AND!"") + invalid_input_ands[idx] = res + elif op == 'XOR': + input_digit_xors.append(res) + +print(input_digit_xors) +print(input_digit_ands) + +swaps = {} + +for i in range(len(input_digit_xors)): + if i == 0: + output_digit_results.append(input_digit_xors[0]) + output_digit_carries.append(input_digit_ands[0]) + else: + result_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), ""XOR"") + if result_op not in expr_to_output: + incorrect = output_to_expr[f""z{i:02}""] + swap1 = set(result_op).difference(set(incorrect)).pop() + swap2 = set(incorrect).difference(set(result_op)).pop() + print(f""need to swap {swap1} and {swap2}"") + swaps[swap1] = swap2 + swaps[swap2] = swap1 + result_output = expr_to_output[incorrect] + if input_digit_xors[i] == swap1: + print(""swapping input digit xors to"", swap2) + input_digit_xors[i] = swap2 + if input_digit_ands[i] == swap2: + print(""swapping input digit ands to"", swap1) + input_digit_ands[i] = swap1 + + else: + result_output = expr_to_output[result_op] + + if not result_output.startswith(""z""): + expected_output = f""z{i:02}"" + if i in invalid_input_ands and expected_output == invalid_input_ands[i]: + print(f""need to swap {expected_output} and {result_output}"") + swaps[result_output] = expected_output + swaps[expected_output] = result_output + print(""swapping input digit ands to"", result_output) + input_digit_ands[i] = result_output + print(""swapping result"") + result_output = expected_output + + else: + print(f""need to swap {expected_output} and {result_output}"") + swaps[result_output] = expected_output + swaps[expected_output] = result_output + print(""swapping result"") + result_output = expected_output + + elif int(result_output[1:]) != i: + if result_output in swaps: + expr_to_output[result_op] = swaps[result_output] + else: + expected_output = f""z{i:02}"" + print(f""need to swap {result_output} and {expected_output}"") + swaps[expected_output] = result_output + swaps[result_output] = expected_output + expr_to_output[result_op] = expected_output + + output_digit_results.append(result_output) + + rhs_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), ""AND"") + rhs_output = expr_to_output[rhs_op] + if rhs_output in swaps: + print(""swapping rhs"") + rhs_output = swaps[rhs_output] + + carry_op = (*sorted((input_digit_ands[i], rhs_output)), ""OR"") + carry_output = expr_to_output[carry_op] + if carry_output in swaps: + print(""swapping carry"") + carry_output = swaps[carry_output] + + output_digit_carries.append(carry_output) + + print(f""{i:02} is in {result_output} with carry {carry_output}"") + +print("","".join(sorted(swaps.keys()))) + +",python:3.9.21-slim +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. + +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","with open('input.txt') as f: + lines = f.read().splitlines() + +output_to_expr = dict() +expr_to_output = dict() + +for line in lines: + if ""->"" in line: + expr, wire = line.split("" -> "") + left, op, right = expr.split("" "") + + left, right = sorted((left, right)) + output_to_expr[wire] = (left, right, op) + expr_to_output[(left, right, op)] = wire + +input_exprs = dict({(k, v) for (k, v) in expr_to_output.items() if k[0].startswith(""x"")}) + +input_digit_xors = [] +input_digit_ands = [] +output_digit_carries = [] +output_digit_results = [] + +invalid_input_ands = {} + +for input_expr in sorted(input_exprs.items()): + idx = int(input_expr[0][0][1:]) + op = input_expr[0][2] + res = input_expr[1] + if op == 'AND': + input_digit_ands.append(res) + if (res.startswith(""z"")): + print(f""{res} is an AND!"") + invalid_input_ands[idx] = res + elif op == 'XOR': + input_digit_xors.append(res) + +print(input_digit_xors) +print(input_digit_ands) + +swaps = {} + +for i in range(len(input_digit_xors)): + if i == 0: + output_digit_results.append(input_digit_xors[0]) + output_digit_carries.append(input_digit_ands[0]) + else: + result_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), ""XOR"") + if result_op not in expr_to_output: + incorrect = output_to_expr[f""z{i:02}""] + swap1 = set(result_op).difference(set(incorrect)).pop() + swap2 = set(incorrect).difference(set(result_op)).pop() + print(f""need to swap {swap1} and {swap2}"") + swaps[swap1] = swap2 + swaps[swap2] = swap1 + result_output = expr_to_output[incorrect] + if input_digit_xors[i] == swap1: + print(""swapping input digit xors to"", swap2) + input_digit_xors[i] = swap2 + if input_digit_ands[i] == swap2: + print(""swapping input digit ands to"", swap1) + input_digit_ands[i] = swap1 + + else: + result_output = expr_to_output[result_op] + + if not result_output.startswith(""z""): + expected_output = f""z{i:02}"" + if i in invalid_input_ands and expected_output == invalid_input_ands[i]: + print(f""need to swap {expected_output} and {result_output}"") + swaps[result_output] = expected_output + swaps[expected_output] = result_output + print(""swapping input digit ands to"", result_output) + input_digit_ands[i] = result_output + print(""swapping result"") + result_output = expected_output + + else: + print(f""need to swap {expected_output} and {result_output}"") + swaps[result_output] = expected_output + swaps[expected_output] = result_output + print(""swapping result"") + result_output = expected_output + + elif int(result_output[1:]) != i: + if result_output in swaps: + expr_to_output[result_op] = swaps[result_output] + else: + expected_output = f""z{i:02}"" + print(f""need to swap {result_output} and {expected_output}"") + swaps[expected_output] = result_output + swaps[result_output] = expected_output + expr_to_output[result_op] = expected_output + + output_digit_results.append(result_output) + + rhs_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), ""AND"") + rhs_output = expr_to_output[rhs_op] + if rhs_output in swaps: + print(""swapping rhs"") + rhs_output = swaps[rhs_output] + + carry_op = (*sorted((input_digit_ands[i], rhs_output)), ""OR"") + carry_output = expr_to_output[carry_op] + if carry_output in swaps: + print(""swapping carry"") + carry_output = swaps[carry_output] + + output_digit_carries.append(carry_output) + + print(f""{i:02} is in {result_output} with carry {carry_output}"") + +print("","".join(sorted(swaps.keys()))) + +",python:3.9.21-slim +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. + +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","from typing import List, Dict +from collections import defaultdict +from part1 import parse_input + +def collect_outputs(wire_values: Dict[str, int], prefix: str) -> List[int]: + """""" + Collects and returns a list of output values from a dictionary of wire values + where the keys start with a given prefix. + + Args: + wire_values (Dict[str, int]): A dictionary containing wire names as keys and their corresponding values. + prefix (str): The prefix to filter the wire names. + + Returns: + List[int]: A list of values from the dictionary where the keys start with the specified prefix. + """""" + return [value for key, value in sorted(wire_values.items()) if key.startswith(prefix)] + +def is_input(operand: str) -> bool: + """""" + Checks if the given operand is an input variable. + + Args: + operand (str): The operand to check. + + Returns: + bool: True if the operand is an input variable ('x' or 'y'), False otherwise. + """""" + return operand[0] in 'xy' + +def get_usage_map(gates: List[str]) -> Dict[str, List[str]]: + """""" + Generates a usage map from a list of gate strings. + + Each gate string is expected to be in the format ""source -> destination"". + The function splits each gate string and maps both the source and destination + to the original gate string in the resulting dictionary. + + Args: + gates (List[str]): A list of gate strings. + + Returns: + Dict[str, List[str]]: A dictionary where each key is a gate (either source or destination) + and the value is a list of gate strings that include the key. + """""" + usage_map = defaultdict(list) + for gate in gates: + parts = gate.split(' ') + usage_map[parts[0]].append(gate) + usage_map[parts[2]].append(gate) + return usage_map + +def check_xor_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool: + """""" + Checks if the given conditions for XOR operations are met. + + Args: + left (str): The left operand of the XOR operation. + right (str): The right operand of the XOR operation. + result (str): The result of the XOR operation. + usage_map (Dict[str, List[str]]): A dictionary mapping results to a list of operations that use them. + + Returns: + bool: True if the conditions are met, False otherwise. + """""" + if is_input(left): + if not is_input(right) or (result[0] == 'z' and result != 'z00'): + return True + usage_ops = [op.split(' ')[1] for op in usage_map[result]] + if result != 'z00' and sorted(usage_ops) != ['AND', 'XOR']: + return True + elif result[0] != 'z': + return True + return False + +def check_and_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool: + """""" + Checks specific conditions based on the provided inputs and usage map. + + Args: + left (str): The left operand. + right (str): The right operand. + result (str): The result operand. + usage_map (Dict[str, List[str]]): A dictionary mapping result operands to a list of operations. + + Returns: + bool: True if the conditions are met, False otherwise. + + Conditions: + 1. If 'left' is an input and 'right' is not an input, return True. + 2. If the operations associated with 'result' in the usage_map are not all 'OR', return True. + """""" + if is_input(left) and not is_input(right): + return True + if [op.split(' ')[1] for op in usage_map[result]] != ['OR']: + return True + return False + +def check_or_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool: + """""" + Checks if the given conditions involving 'left', 'right', and 'result' meet certain criteria. + + Args: + left (str): The left operand. + right (str): The right operand. + result (str): The result operand. + usage_map (Dict[str, List[str]]): A dictionary mapping result operands to a list of operations. + + Returns: + bool: True if any of the conditions are met: + - Either 'left' or 'right' is an input. + - The operations associated with 'result' in 'usage_map' are not exactly 'AND' and 'XOR'. + Otherwise, returns False. + """""" + if is_input(left) or is_input(right): + return True + usage_ops = [op.split(' ')[1] for op in usage_map[result]] + if sorted(usage_ops) != ['AND', 'XOR']: + return True + return False + +def find_swapped_wires(wire_values: Dict[str, int], gates: List[str]) -> List[str]: + """""" + Identifies and returns a list of swapped wires based on the provided wire values and gate operations. + + Args: + wire_values (Dict[str, int]): A dictionary mapping wire names to their integer values. + gates (List[str]): A list of strings representing gate operations in the format ""left op right -> result"". + + Returns: + List[str]: A sorted list of wire names that are identified as swapped. + + The function processes each gate operation, checks the operation type (XOR, AND, OR), and applies specific conditions + to determine if the result wire is swapped. It skips gates where the result is 'z45' or the left operand is 'x00'. + """""" + usage_map = get_usage_map(gates) + swapped_wires = set() + + for gate in gates: + left, op, right, _, result = gate.split(' ') + if result == 'z45' or left == 'x00': + continue + + if op == 'XOR' and check_xor_conditions(left, right, result, usage_map): + swapped_wires.add(result) + elif op == 'AND' and check_and_conditions(left, right, result, usage_map): + swapped_wires.add(result) + elif op == 'OR' and check_or_conditions(left, right, result, usage_map): + swapped_wires.add(result) + else: + print(gate, 'unknown op') + + return sorted(swapped_wires) + +if __name__ == ""__main__"": + wire_values, gates = parse_input('input.txt') + swapped_wires = find_swapped_wires(wire_values, gates) + result = ','.join(swapped_wires) + print(result)",python:3.9.21-slim +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. + +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","def get_expr_for_output(output): + return output_to_expr[swaps.get(output, output)] + +def get_output_for_expr(expr): + output = expr_to_output[expr] + return swaps.get(output, output) + +def swap(out_a, out_b): + print(f""SWAP: {out_a} for {out_b}"") + swaps[out_a] = out_b + swaps[out_b] = out_a + +def find_matching_expr(output, op): + matching = [expr for expr in expr_to_output if expr[2] == op and output in (expr[0], expr[1])] + if len(matching) == 0: + return None + assert len(matching) == 1 + return matching[0] + +with open('input.txt') as f: + lines = f.read().splitlines() + +output_to_expr = dict() +expr_to_output = dict() +swaps = dict() +carries = [] + +max_input_bit_index = -1 + +for line in lines: + if ""->"" in line: + expr, wire = line.split("" -> "") + left, op, right = expr.split("" "") + + left, right = sorted((left, right)) + output_to_expr[wire] = (left, right, op) + expr_to_output[(left, right, op)] = wire + if "":"" in line: + max_input_bit_index = max(max_input_bit_index, int(line.split("":"")[0][1:])) + +num_input_bits = max_input_bit_index + 1 + +for i in range(num_input_bits): + z_output = f""z{i:02}"" + input_xor_expr = (f""x{i:02}"", f""y{i:02}"", ""XOR"") + input_and_expr = (f""x{i:02}"", f""y{i:02}"", ""AND"") + + input_xor_output = get_output_for_expr(input_xor_expr) + input_and_output = get_output_for_expr(input_and_expr) + + if i == 0: + if z_output == input_xor_output: + carries.append(input_and_output) + continue + else: + raise ValueError(""Error in first digits"") + + result_expr = find_matching_expr(input_xor_output, ""XOR"") + if result_expr == None: + result_expr = find_matching_expr(carries[i - 1], ""XOR"") + actual_input_xor_output = result_expr[1] if result_expr[0] == carries[i - 1] else result_expr[0] + swap(actual_input_xor_output, input_xor_output) + else: + carry_input = result_expr[1] if result_expr[0] == input_xor_output else result_expr[0] + if carry_input != carries[i - 1]: + swap(carry_input, carries[i - 1]) + carries[i - 1] = carry_input + + if z_output != get_output_for_expr(result_expr): + swap(z_output, get_output_for_expr(result_expr)) + + intermediate_carry_expr = (*sorted((get_output_for_expr(input_xor_expr), carries[i - 1])), ""AND"") + intermediate_carry_output = get_output_for_expr(intermediate_carry_expr) + + carry_expr = find_matching_expr(intermediate_carry_output, ""OR"") + if carry_expr == None: + print(""TODO"") + else: + expected_input_and_output = carry_expr[1] if carry_expr[0] == intermediate_carry_output else carry_expr[0] + if expected_input_and_output != get_output_for_expr(input_and_expr): + swap(get_output_for_expr(input_and_expr), expected_input_and_output) + + carry_expr = (*sorted((get_output_for_expr(input_and_expr), intermediate_carry_output)), ""OR"") + carry_output = get_output_for_expr(carry_expr) + + carries.append(carry_output) + +print(*sorted(swaps.keys()), sep="","") +",python:3.9.21-slim +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. + +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","#day 24 +import os +from functools import cache +import re +from itertools import chain + + +def reader(): + return open(f""24.txt"", 'r').read().splitlines() + + +def part2(): + f = '\n'.join(reader()).split('\n\n') + B = {} + for l in f[0].split('\n'): + v, b = l.split(': ') + B[v] = int(b) + F = {} + D = {} + for l in f[1].split('\n'): + f, v = l.split(' -> ') + v1, op, v2 = f.split(' ') + v1, v2 = sorted((v1, v2)) + D[v] = {v1, v2} + op = {'XOR': '^', 'AND': '&', 'OR': '|'}[op] + F[v] = f""{v1} {op} {v2}"" + for vv in [v, v1, v2]: + if vv not in B: + B[vv] = None + + def swap(s1, s2): + F[s1], F[s2] = F[s2], F[s1] + D[s1], D[s2] = D[s2], D[s1] + + # swap('z15', 'jgc') + # swap('z22', 'drg') + # swap('z35', 'jbp') + # swap('qjb', 'gvw') + + def r(v): + if B[v] is None: + for dv in D[v]: + r(dv) + B[v] = eval(F[v], None, B) + return B[v] + + def getNum(s): return int(''.join(map(lambda t: str(t[1]), sorted( + filter(lambda t: t[0][0] == s, B.items()), reverse=True))), base=2) + + for v in B: + r(v) + + @cache + def getFullFormula(v): + if v[0] in {'x', 'y'}: + return v + v1, op, v2 = F[v].split(' ') + v1, v2 = sorted((v1, v2)) + return f""({getFullFormula(v1)}) {op} ({getFullFormula(v2)})"" + + FD = {} + for v in D: + formula = getFullFormula(v) + FD[v] = set(re.findall(r'x\d{2}|y\d{2}', formula)) + + problems = [] + for i in range(1, len(list(filter(lambda t: t[0][0] == 'z', B.items()))) - 1): + p = f'((x{i:02}) ^ (y{i:02}))' + formula = getFullFormula(f'z{i:02}') + if f'{p} ^' not in formula and f'^ {p}' not in formula: + problems.append(i) + + swaps = [] + for p in problems: + x = f'x{p:02}' + y = f'y{p:02}' + z = f'z{p:02}' + start = f'{x} ^ {y}' + p1 = next(filter(lambda t: t[1] == start, F.items()))[0] + v1, op, v2 = F[z].split(' ') + if op != '^': + p2 = next( + filter(lambda t: f'^ {p1}' in t[1] or f'{p1} ^' in t[1], F.items()))[0] + swaps.append((z, p2)) + else: + swaps.append( + (p1, sorted((v1, v2), key=lambda v: len(getFullFormula(v)))[0])) + + print(','.join(sorted(chain(*swaps)))) + + +part2()",python:3.9.21-slim +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"#!/usr/bin/env python3 + +myfile = open(""25.in"", ""r"") +lines = myfile.read().strip().split(""\n\n"") +myfile.close() + +schematics = [line.split(""\n"") for line in lines] + +part_one = 0 + +keys = set() +locks = set() +for schematic in schematics: + is_lock = schematic[0][0] == ""#"" + width = len(schematic[0]) + + cols = [[row[i] for row in schematic] for i in range(width)] + + heights = tuple(c.count(""#"") - 1 for c in cols) + if is_lock: + locks.add(heights) + else: + keys.add(heights) + +for lock in locks: + for key in keys: + max_key = tuple(5 - h for h in lock) + if all(h <= max_key[i] for i, h in enumerate(key)): + part_one += 1 + +print(""Part One:"", part_one) +",python:3.9.21-slim +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"with open(""./day_25.in"") as fin: + lines = fin.read().strip().split(""\n\n"") + +def parse(s): + lock = s[0][0] == ""#"" + + if lock: + vals = [] + for j in range(5): + for i in range(7): + if s[i][j] == ""."": + vals.append(i) + break + return vals, lock + + vals = [] + for j in range(5): + for i in range(6, -1, -1): + if s[i][j] == ""."": + vals.append(6 - i) + break + return vals, lock + +locks = [] +keys = [] +for s in lines: + vals, lock = parse(s.split(""\n"")) + if lock: + locks.append(vals) + else: + keys.append(vals) + +ans = 0 +for lock in locks: + for key in keys: + good = True + + for j in range(5): + if lock[j] + key[j] > 7: + good = False + break + + ans += good + +print(ans)",python:3.9.21-slim +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"import time + + +def parse(lines) -> set[tuple[int, int]]: + return { + (x, y) + for y, line in enumerate(lines) + for x, char in enumerate(line) + if char == ""#"" + } + + +def solve_part_1(text: str): + blocks = text.split(""\n\n"") + locks = [] + keys = [] + for b in blocks: + lines = b.splitlines() + schema = parse(lines[1:-1]) + locks.append(schema) if lines[0] == ""#####"" else keys.append(schema) + + r = 0 + for lock in locks: + for key in keys: + r += len(lock & key) == 0 + return r + + +def solve_part_2(text: str): + return 0 + + +if __name__ == ""__main__"": + with open(""input.txt"", ""r"") as f: + quiz_input = f.read() + start = time.time() + p_1_solution = int(solve_part_1(quiz_input)) + middle = time.time() + print(f""Part 1: {p_1_solution} (took {(middle - start) * 1000:.3f}ms)"") + p_2_solution = int(solve_part_2(quiz_input)) + end = time.time() + print(f""Part 2: {p_2_solution} (took {(end - middle) * 1000:.3f}ms)"") +",python:3.9.21-slim +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"locks = [] +keys = [] +with open(""day25-data.txt"") as file: + lines = file.readlines() + for i in range(0, len(lines), 8): + schematic = [line.strip('\n') for line in lines[i+1:i+6]] + schematic_transposed = [[schematic[j][i] for j in range(len(schematic))] for i in range(len(schematic[0]))] + pins = [a.count('#') for a in schematic_transposed] + if (lines[i] == ""#####\n""): + locks.append(pins) # lock + elif lines[i] == "".....\n"": + keys.append(pins) # key + + sum = 0 + for lock in locks: + for key in keys: + test = [lock[i] + key[i] for i in range(0, len(lock))] + if max(test) < 6: + sum += 1 + + print(""Day 25 part 1, sum ="", sum)",python:3.9.21-slim +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"import itertools + +def get_lock(block): + col_counts = [5] * 5 + for line in block[1:6]: + for i in range(5): + if line[i] == ""."": + col_counts[i] -= 1 + return col_counts + +def get_key(block): + col_counts = [0] * 5 + for line in block[1:6]: + for i in range(5): + if line[i] == ""#"": + col_counts[i] += 1 + return col_counts + + +with open('input.txt') as f: + lines = f.read().splitlines() + +locks = [] +keys = [] + +for i in range(0, len(lines), 8): + block = lines[i:i+7] + + if block[0][0] == ""#"": + locks.append(get_lock(block)) + + elif block[0][0] == ""."": + keys.append(get_key(block)) + +ct_fit = sum([all([lock[i] + key[i] <= 5 for i in range(5)]) for lock, key in itertools.product(locks, keys)]) + +print(ct_fit) + +",python:3.9.21-slim +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"data = open('input.txt').read().strip().split('\n') + + +def generateNextNumber(num): + res1 = num + temp = (num * 64) + res1 = (res1 ^ temp) % 16777216 + + res2 = res1 + temp = (res1 // 32) + res2 = (res2 ^ temp) % 16777216 + + res3 = res2 + temp = (res2 * 2048) + res3 = (res3 ^ temp) % 16777216 + + return res3 + +total = 0 +for i in range(0, len(data)): + num = int(data[i]) + for i in range(2000): + num = generateNextNumber(num) + total += num + +print(total)",python:3.9.21-slim +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"from typing import List + +def parse_input(file_path: str) -> List[int]: + """""" + Reads a file containing integers, one per line, and returns a list of these integers. + + Args: + file_path (str): The path to the input file. + + Returns: + List[int]: A list of integers read from the file. + """""" + with open(file_path) as f: + return [int(line.strip()) for line in f] + +def next_secret_number(secret: int) -> int: + """""" + Calculate the next secret number based on the given secret number. + + The function performs a series of bitwise operations and modular arithmetic + to generate a new secret number from the input secret number. + + Steps: + 1. Multiply the secret by 64, mix with XOR, and prune with modulo 16777216. + 2. Divide the result by 32, mix with XOR, and prune with modulo 16777216. + 3. Multiply the result by 2048, mix with XOR, and prune with modulo 16777216. + + Args: + secret (int): The input secret number. + + Returns: + int: The next secret number. + """""" + # Step 1: Multiply by 64, mix, and prune + secret = (secret ^ (secret * 64)) % 16777216 + # Step 2: Divide by 32, mix, and prune + secret = (secret ^ (secret // 32)) % 16777216 + # Step 3: Multiply by 2048, mix, and prune + secret = (secret ^ (secret * 2048)) % 16777216 + return secret + +def generate_2000th_secret(initial_secret: int) -> int: + """""" + Generates the 2000th secret number starting from the given initial secret. + + Args: + initial_secret (int): The initial secret number to start from. + + Returns: + int: The 2000th secret number. + """""" + secret = initial_secret + for _ in range(2000): + secret = next_secret_number(secret) + return secret + +if __name__ == ""__main__"": + input_data = parse_input('input.txt') + total = sum(generate_2000th_secret(secret) for secret in input_data) + print(total) +",python:3.9.21-slim +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"def step(num): + num = (num ^ (num * 64)) % 16777216 + num = (num ^ (num // 32)) % 16777216 + num = (num ^ (num * 2048)) % 16777216 + return num + +def process_buyers(file_path): + total = 0 + + with open(file_path) as file: + for line in file: + num = int(line) + buyer = [num % 10] + for _ in range(2000): + num = step(num) + buyer.append(num % 10) + total += num + + return total + + + +def main(): + total = process_buyers(""i.txt"") + print(total) + +if __name__ == ""__main__"": + main() + ",python:3.9.21-slim +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"from collections import defaultdict +import numpy as np + +with open(""input.txt"") as f: + ns = list(map(int, f.read().strip().split(""\n""))) + + +def hsh(secret): + for _ in range(2000): + secret ^= secret << 6 & 0xFFFFFF + secret ^= secret >> 5 & 0xFFFFFF + secret ^= secret << 11 & 0xFFFFFF + yield secret + + +secrets = list(map(list, map(hsh, ns))) + +# Part 1 +print(sum(s[-1] for s in secrets))",python:3.9.21-slim +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"def step(num): + num = (num ^ (num * 64)) % 16777216 + num = (num ^ (num // 32)) % 16777216 + num = (num ^ (num * 2048)) % 16777216 + return num + +def process_buyers(file_path): + total = 0 + + with open(file_path) as file: + for line in file: + num = int(line) + buyer = [num % 10] + for _ in range(2000): + num = step(num) + buyer.append(num % 10) + total += num + + return total + + + +def main(): + total = process_buyers(""22.txt"") + print(total) + +if __name__ == ""__main__"": + main() + ",python:3.9.21-slim +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"from collections import defaultdict +import numpy as np + +with open(""input.txt"") as f: + ns = list(map(int, f.read().strip().split(""\n""))) + + +def hsh(secret): + for _ in range(2000): + secret ^= secret << 6 & 0xFFFFFF + secret ^= secret >> 5 & 0xFFFFFF + secret ^= secret << 11 & 0xFFFFFF + yield secret + + +# Part 2 +result = defaultdict(int) +for n in ns: + ss = [s % 10 for s in hsh(n)] + diffs = np.diff(ss) + changes = set() + for i in range(1996): + if (change := tuple(diffs[i : i + 4])) not in changes: + changes.add(change) + result[change] += ss[i + 4] + +print(max(result.values()))",python:3.9.21-slim +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"def step(num): + num = (num ^ (num * 64)) % 16777216 + num = (num ^ (num // 32)) % 16777216 + num = (num ^ (num * 2048)) % 16777216 + return num + +def process_buyers(file_path): + buyers = [] + + with open(file_path) as file: + for line in file: + num = int(line) + buyer = [num % 10] + for _ in range(2000): + num = step(num) + buyer.append(num % 10) + buyers.append(buyer) + + return buyers + +def calculate_sorok(buyers): + sorok = {} + + for b in buyers: + seen = set() + for i in range(len(b) - 4): + a1, a2, a3, a4, a5 = b[i:i+5] + sor = (a2 - a1, a3 - a2, a4 - a3, a5 - a4) + if sor in seen: + continue + seen.add(sor) + + if sor not in sorok: + sorok[sor] = 0 + sorok[sor] += a5 + + return sorok + +def main(): + buyers = process_buyers(""22.txt"") + sorok = calculate_sorok(buyers) + print(max(sorok.values())) + +if __name__ == ""__main__"": + main() + ",python:3.9.21-slim +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"import time + +N = 2000 + + +def next_secret(s): + """"""3-step pseudorandom transformation for a 24-bit integer."""""" + s = (s ^ ((s << 6) & 0xFFFFFF)) & 0xFFFFFF + s = (s ^ (s >> 5)) & 0xFFFFFF + s = (s ^ ((s << 11) & 0xFFFFFF)) & 0xFFFFFF + return s + + +def pack_diffs_into_key(d0, d1, d2, d3): + """""" + Each diff is offset by +9 to fit into [0..18] (5 bits each). + Combine them into a single 20-bit integer. + """""" + return (d0 << 15) | (d1 << 10) | (d2 << 5) | d3 + + + +def solve_part_2(text: str): + buyers = list(map(int, text.splitlines())) + size = 1 << 20 # total possible 4-diff combinations + seen = [0] * size + results = [0] * size + buyer_id = 1 + + secrets_arr = [0] * (N + 1) + prices_arr = [0] * (N + 1) + deltas_arr = [0] * (N + 1) + + for secret_number in buyers: + # Fill arrays with generated secrets, prices, and deltas + secrets_arr[0] = secret_number + prices_arr[0] = secrets_arr[0] % 10 + for i in range(1, N + 1): + secrets_arr[i] = next_secret(secrets_arr[i - 1]) + prices_arr[i] = secrets_arr[i] % 10 + deltas_arr[i] = prices_arr[i] - prices_arr[i - 1] + + # From index 4 onward, we have a valid window of 4 consecutive deltas + for i in range(4, N + 1): + # We gather the 4 consecutive deltas leading to prices_arr[i]. + d0 = deltas_arr[i - 3] + 9 + d1 = deltas_arr[i - 2] + 9 + d2 = deltas_arr[i - 1] + 9 + d3 = deltas_arr[i] + 9 + key = pack_diffs_into_key(d0, d1, d2, d3) + + # Only record the first time this buyer sees this pattern + if seen[key] != buyer_id: + seen[key] = buyer_id + results[key] += prices_arr[i] + + buyer_id += 1 + + return max(results) + + +if __name__ == ""__main__"": + with open(""22.txt"", ""r"") as f: + quiz_input = f.read() + p_2_solution = int(solve_part_2(quiz_input)) + print(f""Part 2: {p_2_solution}"")",python:3.9.21-slim +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"import time, re, itertools as itt, collections as coll + + +def load(file): + with open(file) as f: + return map(int, re.findall('\d+', f.read())) + + +def mix_prune(s): + s = (s ^ (s * 64)) % 16777216 + s = (s ^ (s // 32)) % 16777216 + return (s ^ (s * 2048)) % 16777216 + + +def solve(p): + part1 = part2 = 0 + bananas = coll.defaultdict(int) + + for s in p: + nums = [s := mix_prune(s) for _ in range(2000)] + + diffs = [b % 10 - a % 10 for a, b in itt.pairwise(nums)] + first_seen_pat = set() + for i in range(len(nums) - 4): + pat = tuple(diffs[i:i + 4]) + if pat in first_seen_pat: continue + bananas[pat] += nums[i + 4] % 10 + first_seen_pat.add(pat) + + part2 = max(bananas.values()) + + return part2 + + +print(f'Solution: {solve(load(""22.txt""))}')",python:3.9.21-slim +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"with open(""input.txt"", ""r"") as file: + lines = file.readlines() + +def secretStep(secret): + # Cleaned up + secret = (secret * 64 ^ secret) % 16777216 + secret = (secret // 32 ^ secret) % 16777216 + secret = (secret * 2048 ^ secret) % 16777216 + return secret + +# Custom implementation of max function +def findMax(sequence_totals): + max_key = None + max_value = float('-inf') # Start with the smallest possible value + + for key, value in sequence_totals.items(): + if value > max_value: + max_value = value + max_key = key + + return max_key + +def findMaxBananas(lines): + sequence_totals = {} + + for line in lines: + secret_number = int(line) + price_list = [secret_number % 10] # Store last digit of secret numbers + + # Generate 2000 price steps + for _ in range(2000): + secret_number = secretStep(secret_number) + price_list.append(secret_number % 10) + + tracked_sequences = set() + + # Examine all sequences of 4 consecutive price changes + for index in range(len(price_list) - 4): + p1, p2, p3, p4, p5 = price_list[index:index + 5] # Extract 5 consecutive prices + price_change = (p2 - p1, p3 - p2, p4 - p3, p5 - p4) # Calculate changes + + if price_change in tracked_sequences: # Skip since we wont choose same again + continue + tracked_sequences.add(price_change) + + if price_change not in sequence_totals: + sequence_totals[price_change] = 0 + sequence_totals[price_change] += p5 # Add the price to the total + + # Find highest total + # best_sequence = max(sequence_totals, key=sequence_totals.get) + best_sequence = findMax(sequence_totals) + max_bananas = sequence_totals[best_sequence] + + return best_sequence, max_bananas + +best_sequence, max_bananas = findMaxBananas(lines) + +print(max_bananas)",python:3.9.21-slim +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"import time +from enum import Enum +import heapq + +file = open(""20.txt"", ""r"") +start_time = time.time() + +class Direction(Enum): + UP = 0 + RIGHT = 1 + DOWN = 2 + LEFT = 3 + +class Position: + def __init__(self, x, y): + self.x = x + self.y = y + + def __repr__(self): + return f""{self.__dict__}"" + + def __eq__(self, other): + return self.x == other.x and self.y == other.y + + def __hash__(self): + return hash(f""{self.x}_{self.y}"") + + @classmethod + def list(cls): + return list(map(lambda c: c.value, cls)) + +class TrackNode: + def __init__(self, position, order): + self.position = position + self.order = order + + def __repr__(self): + return f""{self.__dict__}"" + + def __eq__(self, other): + return self.position == other.position and self.order == other.order + + def __hash__(self): + return hash(f""{self.position}_{self.order}"") + +class Cheat: + def __init__(self, s, e): + self.s = s + self.e = e + + def __repr__(self): + return f""{self.__dict__}"" + + def __eq__(self, other): + return self.s == other.s and self.e == other.e + + def __hash__(self): + return hash(f""{self.s}_{self.e}"") + +space = 0 +wall = 1 + +def import_matrix(matrix_string): + matrix = [] + start_position = None + goal_position = None + for line_index, line in enumerate(matrix_string.split(""\n"")): + matrix.append([]) + # print(line) + for column_index, tile in enumerate(line): + if tile == ""."": + matrix[line_index].append(space) + elif tile == ""#"": + matrix[line_index].append(wall) + elif tile == ""S"": + matrix[line_index].append(space) + start_position = Position(column_index, line_index) + elif tile == ""E"": + matrix[line_index].append(space) + goal_position = Position(column_index, line_index) + return (matrix, start_position, goal_position) + +map, start, goal = import_matrix(file.read()) + +def print_map(path = set()): + for line_index, line in enumerate(map): + string = [] + for column_index, tile in enumerate(line): + if Position(column_index, line_index) == start: + string.append(""S"") + elif Position(column_index, line_index) == goal: + string.append(""E"") + elif Position(column_index, line_index) in path: + string.append(""O"") + elif tile == wall: + string.append(""#"") + else: + string.append(""."") + print("""".join(string)) + +def get_valid_in_direction(current_position, direction): + match direction: + case Direction.UP: + p = Position(current_position.x, current_position.y-1) + case Direction.LEFT: + p = Position(current_position.x-1, current_position.y) + case Direction.RIGHT: + p = Position(current_position.x+1, current_position.y) + case Direction.DOWN: + p = Position(current_position.x, current_position.y+1) + + if p.x < 0 or p.x >= len(map[0]) or p.y < 0 or p.y >= len(map): + return None + + return (p, direction) + +def get_neighbors_and_cheats(current_position): + directions = [Direction.LEFT, Direction.RIGHT, Direction.UP, Direction.DOWN] + neighbors_in_map = [get_valid_in_direction(current_position, d) for d in directions] + neighbors = [] + walls_with_direction = [] + for n in neighbors_in_map: + if n is None: + continue + if map[n[0].y][n[0].x] == space: + neighbors.append(n[0]) + else: + walls_with_direction.append(n) + + cheats = [] + for wd in walls_with_direction: + possible_cheat = get_valid_in_direction(wd[0], wd[1]) + if possible_cheat is None: + continue + if map[possible_cheat[0].y][possible_cheat[0].x] == space: + cheats.append(Cheat(wd[0], possible_cheat[0])) + + return (neighbors, cheats) + +print(""~~~~~~~~~~RESULT 1~~~~~~~~~~"") +def create_track_1(): + graph = {} + cheats_dict = {} + for line_index, line in enumerate(map): + for column_index, tile in enumerate(line): + if tile == wall: + continue + position = Position(column_index, line_index) + (neighbors, cheats) = get_neighbors_and_cheats(position) + graph[position] = neighbors + cheats_dict[position] = cheats + + # track = {} # step: position + track = {} # position: step + cheats = {} # step: [Cheat] + ignore = set() # tracks what steps to ignore in track building; should contain whole path + current_position = start + current_step = 0 + while True: + ignore.add(current_position) + # track[current_step] = current_position + track[current_position] = current_step + + if current_position == goal: + break + + # ignore already traversed track (backward cheat is not a cheat) + valid_cheats = [c for c in cheats_dict[current_position] if c.e not in ignore] + cheats[current_step] = valid_cheats + + neighbors = graph[current_position] + # assuming only one valid path forward (or none if end) + for neighbor in neighbors: + if neighbor not in ignore: # ignore already traversed track + current_position = neighbor + continue + + current_step += 1 + + return (track, cheats, current_step) + +(track, cheats, total_steps) = create_track_1() + +solution = 0 +for step in cheats.keys(): + for cheat in cheats[step]: + length_up_to_cheat = step + step_at_cheat_end = track[cheat.e] + resulting_length = length_up_to_cheat + 2 + (total_steps - step_at_cheat_end) + steps_saved = total_steps - resulting_length + if steps_saved >= 100: + solution += 1 +print(solution) +",python:3.9.21-slim +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"grid = [[elem for elem in line.strip()] for line in open('input.txt')] + +def get_start(grid): + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 'S': + return (i, j) + +def get_end(grid): + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 'E': + return (i, j) + +start = get_start(grid) +end = get_end(grid) + +def get_neighbors(grid, pos): + i, j = pos + neighbors = [] + if i > 0 and grid[i-1][j] != '#': + neighbors.append((i-1, j)) + if i < len(grid) - 1 and grid[i+1][j] != '#': + neighbors.append((i+1, j)) + if j > 0 and grid[i][j-1] != '#': + neighbors.append((i, j-1)) + if j < len(grid[i]) - 1 and grid[i][j+1] != '#': + neighbors.append((i, j+1)) + return neighbors + +def get_race_track(grid, start, end): + visited = [] + queue = [start] + while queue: + pos = queue.pop(0) + visited.append(pos) + if pos == end: + return visited + neighbors = get_neighbors(grid, pos) + for neighbor in neighbors: + if neighbor not in visited: + queue.append(neighbor) + return [] + +def print_path(grid, path): + grid_copy = [line.copy() for line in grid] + for pos in path[:10]: + i, j = pos + grid_copy[i][j] = 'X' + for line in grid_copy: + print(''.join(line)) + +def print_cheat(grid, first, second): + grid_copy = [line.copy() for line in grid] + grid_copy[first[0]][first[1]] = '1' + grid_copy[second[0]][second[1]] = '2' + for line in grid_copy: + print(''.join(line)) + +def get_cheats(path,grid): + cheats = {} + for i in range(len(path)): + for j in range(i,len(path)): + if (path[i][0] == path[j][0] and abs(path[i][1]-path[j][1]) == 2 and grid[path[i][0]][(path[i][1]+path[j][1])//2] == '#') or (path[i][1] == path[j][1] and abs(path[i][0]-path[j][0]) == 2 and grid[(path[i][0]+path[j][0])//2][path[i][1]] == '#'): + savedTime = j - i - 2 + if savedTime not in cheats: + cheats[savedTime] = 1 + else: + cheats[savedTime] += 1 + + return cheats + +path = get_race_track(grid, start, end) +cheats = get_cheats(path,grid) +#rint(cheats) +count = 0 +for key in cheats: + if key >= 100: + count += cheats[key] + +print(count)",python:3.9.21-slim +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from collections import defaultdict, deque +from tqdm import tqdm +import copy + +with open(""./day_20.in"") as fin: + grid = [list(line) for line in fin.read().strip().split(""\n"")] + +N = len(grid) +def in_grid(i, j): + return 0 <= i < N and 0 <= j < N + +for i in range(N): + for j in range(N): + if grid[i][j] == ""S"": + si, sj = i, j + elif grid[i][j] == ""E"": + ei, ej = i, j + +dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] + +# Determine OG path +path = [(si, sj)] +while path[-1] != (ei, ej): + i, j = path[-1] + for di, dj in dd: + ii, jj = i + di, j + dj + if not in_grid(ii, jj): + continue + if len(path) > 1 and (ii, jj) == path[-2]: + continue + if grid[ii][jj] == ""#"": + continue + + path.append((ii, jj)) + break + +og = len(path) - 1 + +times = {} +for t, coord in enumerate(path): + times[coord] = og - t + +counts = defaultdict(int) +saved = {} +for t, coord in enumerate(tqdm(path, ncols=80)): + i, j = coord + for di1, dj1 in dd: + for di2, dj2 in dd: + ii, jj = i + di1 + di2, j + dj1 + dj2 + if not in_grid(ii, jj) or grid[ii][jj] == ""#"": + continue + + rem_t = times[(ii, jj)] + saved[(i, j, ii, jj)] = og - (t + rem_t + 2) + +ans = 0 +for v in saved.values(): + if v >= 0: counts[v] += 1 + if v >= 100: ans += 1 + +print(ans)",python:3.9.21-slim +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from collections import Counter + +def find_shortcuts(map, p): + y, x = p + for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]: + if in_direction(map, p, direction, 1) == '#': + shortcut_to = in_direction(map, p, direction, 2) + if shortcut_to == '#' or shortcut_to == '.': + continue + #print(f""Shortcut found from {p} to {shortcut_to}"") + yield map[y][x] - shortcut_to - 2 + +def in_direction(map, f, d, count): + y = f[0] + x = f[1] + for _ in range(count): + y += d[0] + x += d[1] + if 0 > y or y >= len(map) or 0 > x or x >= len(map[0]): + return '#' + return map[y][x] + + +def step(map, p, steps): + y, x = p + for r, c in [(y+1,x), (y-1,x), (y,x+1), (y,x-1)]: + if map[r][c] == '.': + map[r][c] = steps + return (r, c) + +map = [] + +with open('input') as input: + row = 0 + for l in input: + l = l.strip() + map.append(list(l)) + if 'S' in l: + start = (row, l.find('S')) + if 'E' in l: + end = (row, l.find('E')) + row += 1 + +print(f""Race from {start} to {end}"") +p = start +shortcuts = [] +steps = 0 +map[start[0]][start[1]] = 0 +map[end[0]][end[1]] = '.' +while p != end: + steps += 1 + #print(f""Step {steps} from {p}"") + shortcuts.extend(find_shortcuts(map, p)) + p = step(map, p, steps) + +# And also shortcuts straight to the end +shortcuts.extend(find_shortcuts(map, p)) + +for l, count in sorted(Counter(shortcuts).items(), key=lambda x: x[0]): + print(f""{l}: {count}"") +print(sum(1 for s in shortcuts if s >= 100))",python:3.9.21-slim +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from dataclasses import dataclass +from pathlib import Path + +TEST = False +if TEST: + text = Path(""20_test.txt"").read_text().strip() +else: + text = Path(""20.txt"").read_text().strip() + +grid = [list(l) for l in text.split(""\n"")] +width = len(grid[0]) +height = len(grid) + +def get_grid(p): + x = p.x + y = p.y + if x < 0 or x > width: + return None + if y < 0 or x > height: + return None + return grid[y][x] + +@dataclass(frozen=True) +class Position: + x: int + y: int + + def __add__(self, other): + x = self.x + other.x + y = self.y + other.y + return Position(x=x, y=y) + + def manhattan_distance(self, other): + d_x = self.x - other.x + d_y = self.y - other.y + return abs(d_x) + abs(d_y) + +def neighbours(position): + directions = [ + Position(1, 0), + Position(-1, 0), + Position(0, 1), + Position(0, -1) + ] + + for d in directions: + new_position = position + d + if get_grid(new_position) == '.': + yield new_position + +# Find the 'S', and the path from the 'S' to the 'E' - we're told there's a unique path. +for x in range(len(grid[0])): + for y in range(len(grid)): + p = Position(x=x, y=y) + if get_grid(p) == 'S': + start_position = p + grid[y][x] = '.' + elif get_grid(p) == 'E': + end_position = p + grid[y][x] = '.' + +path = {start_position: 0} +last_position = start_position +while last_position != end_position: + next_ = [x for x in neighbours(last_position) if x not in path] + assert len(next_) == 1 + next_ = next_[0] + path[next_] = len(path) + last_position = next_ + +# Part 1: How many jumps of length 2 save at least 100 picoseconds? +directions = [ + Position(2, 0), + Position(-2, 0), + Position(0, 2), + Position(0, -2) +] + +count = 0 +for point in path: + for d in directions: + next_point = point + d + if next_point in path: + time_saved = path[next_point] - path[point] - 2 + if time_saved >= 100: + count += 1 +print(count)",python:3.9.21-slim +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"from collections import defaultdict + +with open(""input.txt"") as input_file: + input_text = input_file.read().splitlines() + +start = (-1, -1) +end = (-1, -1) +walls = set() +for row in range(len(input_text)): + for col in range(len(input_text[0])): + match input_text[row][col]: + case ""S"": + start = (row, col) + case ""E"": + end = (row, col) + case ""#"": + walls.add((row, col)) + +moves = ((1, 0), (-1, 0), (0, 1), (0, -1)) +no_cheat_move_count = {start: 0} +current_pos = start +move_count = 0 +while current_pos != end: + for row_move, col_move in moves: + new_pos = (current_pos[0] + row_move, current_pos[1] + col_move) + if new_pos not in walls and new_pos not in no_cheat_move_count: + move_count += 1 + current_pos = new_pos + no_cheat_move_count[current_pos] = move_count + break +cheat_moves = [] +for delta_row in range(-20, 21): + for delta_col in range(-(20 - abs(delta_row)), 21 - abs(delta_row)): + cheat_moves.append((delta_row, delta_col)) +cheats = defaultdict(int) +for (initial_row, initial_col), step in no_cheat_move_count.items(): + for row_move, col_move in cheat_moves: + cheat_pos = (initial_row + row_move, initial_col + col_move) + if no_cheat_move_count.get(cheat_pos, 0) > step + abs(row_move) + abs(col_move): + cheats[ + no_cheat_move_count[cheat_pos] - step - abs(row_move) - abs(col_move) + ] += 1 +print(sum(count for saving, count in cheats.items() if saving >= 100))",python:3.9.21-slim +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"def readfile(test_file): + file_name = ""test.txt"" if test_file else ""input.txt"" + + with open(file_name) as f: + maze = [list(line.strip()) for line in f.readlines()] + + start = (-1, -1) + end = (-1, -1) + + # Create the maze with 1 as blocks and 0 as free + for r, row in enumerate(maze): + for c, _ in enumerate(row): + symbol = maze[r][c] + if symbol == ""S"": + # Keep track of start + start = (r, c) + maze[r][c] = 0 + elif symbol == ""E"": + # Keep track of end + end = (r, c) + maze[r][c] = 0 + elif symbol == ""."": + maze[r][c] = 0 + else: + maze[r][c] = 1 + + return maze, start, end + + +def part2(maze, start, end): + path, costs = cheapest_path(maze, start, end) + cheats = [] + + # Find all possible cheats with max duration of 20 picoseconds by pairwise matching of path + for i in range(0, len(path)): + for j in range(i, len(path)): + start = path[i] + end = path[j] + diff = abs(end[1] - start[1]) + abs(end[0] - start[0]) + if 0 < diff <= 20: + cheats.append((start, end, diff)) + + time_saved = {} + # For each cheat keep track of how much time is saved + for cheat in cheats: + start = cheat[0] + end = cheat[1] + steps = cheat[2] + diff = costs[end] - costs[start] - steps + + # Ignore cheats saving less than 100 picoseconds + if diff < 100: + continue + elif diff in time_saved: + time_saved[diff] += 1 + else: + time_saved[diff] = 1 + + print(sum(time_saved.values())) + + +if __name__ == ""__main__"": + test_file = False + maze, start, end = readfile(test_file) + + print(""\nAnswer to part 2:"") + part2(maze, start, end)",python:3.9.21-slim +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"with open(""input20.txt"") as i: + input = [x.strip() for x in i.readlines()] + +test_data = """"""############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +###############"""""".split(""\n"") + +# input = test_data + +map = """".join(input) +w, h = len(input[0]), len(input) +start, end = map.index(""S""), map.index(""E"") + +def print_map(): + for r in range(h): + print(map[r*w:(r+1)*w]) + +distances = [None]*w*h +working_set = [end] +current = 0 +while len(working_set)>0: + next = [] + for i in working_set: + if distances[i] is None: + distances[i] = current + next = [x for x in [i-1, i-w, i+1, i+w] if map[x]!=""#"" and distances[x] is None] + working_set = next + current += 1 + +original = distances[start] + +def get_cheats(cheat_length, limit): + count = 0 + for i in range(0, w*h): + if distances[i] is None: continue + for j in range(i+1, w*h): + if distances[j] is None: continue + x1, y1, x2, y2 = i%w, i//w, j%w, j//w + if abs(x1-x2) + abs(y1-y2)<=cheat_length: + k = 0 + if distances[i] > distances[j]: + k = distances[start]-distances[i] + distances[j] + abs(x1-x2) + abs(y1-y2) + elif distances[i] < distances[j]: + k = distances[start]-distances[j] + distances[i] + abs(x1-x2) + abs(y1-y2) + if original-k>=limit: + count += 1 + return count + +print(get_cheats(20, 100))",python:3.9.21-slim +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"from collections import defaultdict +import heapq + +def parse_input(filename): + grid = [] + + with open(filename, 'r') as file: + for line in file: + line = line.strip() + grid.append([char for char in line]) + + return grid + + +def solve1(grid, minsave): + si, sj, ei, ej = 0,0,0,0 + N, M = len(grid), len(grid[0]) + def inside(i,j): + return 0<=i= minsave and grid[ti][tj] == '#': + savings[(i,j,ni,nj)] = cost[(ni,nj)] - cost[(i,j)] - 2 + count += 1 + + print(f""Part One - {count}"") # 1518 + + + +def solve2(grid, minsave): + si, sj, ei, ej = 0,0,0,0 + N, M = len(grid), len(grid[0]) + def inside(i,j): + return 0<=i= minsave: + savings[(i,j,ni,nj)] = cost[(ni,nj)] - cost[(i,j)] - step + count += 1 + + print(f""Part Two - {count}"") # 1032257 + + +# grid = parse_input('./inputs/day20toy.txt') +# solve1(grid, 0) +# solve2(grid, 50) + +grid = parse_input('./inputs/day20.txt') +solve1(grid, 100) +solve2(grid, 100)",python:3.9.21-slim +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"#!/usr/bin/env python3 + +from collections import defaultdict, deque + +myfile = open(""20.txt"", ""r"") +lines = myfile.read().strip().splitlines() +myfile.close() + +end = start = (-1, -1) +grid = defaultdict(str) +for y in range(len(lines)): + for x in range(len(lines[y])): + if lines[y][x] == ""S"": + start = (x, y) + elif lines[y][x] == ""E"": + end = (x, y) + grid[(x, y)] = lines[y][x] + +part_one = 0 +part_two = 0 + +visited = set() +scores = defaultdict(lambda: float(""inf"")) +scores[start] = 0 +q = deque([start]) +while q: + pos = q.popleft() + visited.add(pos) + + for dir in [(1, 0), (0, -1), (-1, 0), (0, 1)]: + next_pos = (pos[0] + dir[0], pos[1] + dir[1]) + if next_pos not in visited and grid[next_pos] != ""#"" and grid[next_pos] != """": + scores[next_pos] = scores[pos] + 1 + q.append(next_pos) + +for a in visited: + for i in range(-20, 21): + for j in range(-20, 21): + dist = abs(i) + abs(j) + if dist > 20: + continue + b = (a[0] + i, a[1] + j) + if b not in visited: + continue + savings = scores[b] - scores[a] - dist + if savings < 100: + continue + + if dist <= 2: + part_one += 1 + part_two += 1 + +print(""Part One:"", part_one) +print(""Part Two:"", part_two)",python:3.9.21-slim \ No newline at end of file