diff --git "a/aoc.csv" "b/aoc.csv" --- "a/aoc.csv" +++ "b/aoc.csv" @@ -1,5 +1,5 @@ -year,day,part,question,answer,solution,language -2024,2,1,"--- Day 2: Red-Nosed Reports --- +,year,day,part,question,answer,solution,language +0,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. @@ -66,8 +66,8 @@ if __name__ == ""__main__"": if tmpSafe: safe += 1 - print(safe)",python:3.9 -2024,2,1,"--- Day 2: Red-Nosed Reports --- + print(safe)",python +1,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. @@ -135,8 +135,8 @@ def solve(input): print(counter) -solve(input_path)",python:3.9 -2024,2,1,"--- Day 2: Red-Nosed Reports --- +solve(input_path)",python +2,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. @@ -170,8 +170,8 @@ 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 -2024,2,2,"--- Day 2: Red-Nosed Reports --- +print (safe)",python +7,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. @@ -572,8 +572,8 @@ def solve(input_path: str): print(counter) -solve(input_path)",python:3.9 -2024,2,2,"--- Day 2: Red-Nosed Reports --- +solve(input_path)",python +8,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. @@ -657,8 +657,8 @@ with open('input.txt', 'r') as file: count += 1 break -print(count)",python:3.9 -2024,2,2,"--- Day 2: Red-Nosed Reports --- +print(count)",python +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. @@ -749,8 +749,8 @@ with open('02.input', 'r') as file: print(line) valid_count += 1 -print(f""Number of valid sequences: {valid_count}"")",python:3.9 -2024,1,1,"--- Day 1: Historian Hysteria --- +print(f""Number of valid sequences: {valid_count}"")",python +10,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. @@ -818,8 +818,8 @@ if __name__ == ""__main__"": sumDist = 0 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 -2024,1,1,"--- Day 1: Historian Hysteria --- + print(sumDist)",python +11,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. @@ -882,8 +882,8 @@ def main(): a, b = read_input_file('input2.txt') print(find_min_diff(a, b)) -main()",python:3.9 -2024,1,1,"--- Day 1: Historian Hysteria --- +main()",python +12,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. @@ -938,8 +938,8 @@ right_list.sort() for i in range(len(left_list)): distance += abs(left_list[i] - right_list[i]) -print(f""The total distance between the lists is {distance}"")",python:3.9 -2024,1,1,"--- Day 1: Historian Hysteria --- +print(f""The total distance between the lists is {distance}"")",python +13,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. @@ -1011,8 +1011,8 @@ if __name__ == ""__main__"": input_file = 'input.txt' pairs = read_input(input_file) result = calculate_sum_of_differences(pairs) - print(result)",python:3.9 -2024,1,1,"--- Day 1: Historian Hysteria --- + print(result)",python +14,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. @@ -1078,8 +1078,8 @@ for i in range(len(liste_paires)): total += abs(int(liste_paires[i][0]) - int(liste_paires[i][1])) print(total) -#the answer was 3508942",python:3.9 -2024,1,2,"--- Day 1: Historian Hysteria --- +#the answer was 3508942",python +15,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. @@ -1181,8 +1181,8 @@ if __name__ == '__main__': left, right = build_lists(contents) score = calculate_similarity_score(left, right) - print(score)",python:3.9 -2024,1,2,"--- Day 1: Historian Hysteria --- + print(score)",python +16,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. @@ -1264,8 +1264,8 @@ total = 0 for i in range(len(leftNums)): total += leftNums[i] * rightNums.count(leftNums[i]) -print(f""total: {total}"")",python:3.9 -2024,1,2,"--- Day 1: Historian Hysteria --- +print(f""total: {total}"")",python +17,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. @@ -1355,8 +1355,8 @@ for num in list1: if num in list2Count: similarityScore += num * list2Count[num] -print(similarityScore)",python:3.9 -2024,1,2,"--- Day 1: Historian Hysteria --- +print(similarityScore)",python +18,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. @@ -1447,8 +1447,8 @@ for x in b: for x in a: ans += x * counts[x] -print(ans)",python:3.9 -2024,1,2,"--- Day 1: Historian Hysteria --- +print(ans)",python +19,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. @@ -1538,8 +1538,8 @@ for i in range(len(list1)): if num2 > num1: break total+= (num1*simscore) -print(total)",python:3.9 -2024,3,1,"--- Day 3: Mull It Over --- +print(total)",python +20,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. @@ -1589,8 +1589,8 @@ def part2(): sum += runOps(op) print(sum) -part1()",python:3.9 -2024,3,1,"--- Day 3: Mull It Over --- +part1()",python +21,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. @@ -1620,8 +1620,8 @@ mul_inp = [instruction.split("","") for instruction in instructions] mul_results = [int(instruction[0]) * int(instruction[1]) for instruction in mul_inp] mul_total = sum(mul_results) -print(""Sum of all multiplications:"", mul_total)",python:3.9 -2024,3,1,"--- Day 3: Mull It Over --- +print(""Sum of all multiplications:"", mul_total)",python +22,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. @@ -1660,8 +1660,8 @@ def main(): max = max + (int(match[0]) * int(match[1])) print(""max"", max) -main()",python:3.9 -2024,3,1,"--- Day 3: Mull It Over --- +main()",python +23,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. @@ -1687,8 +1687,8 @@ 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 -2024,3,1,"--- Day 3: Mull It Over --- + print(sum)",python +24,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. @@ -1723,8 +1723,8 @@ for match in matches: result += int(nums[0]) * int(nums[1]) -print(result)",python:3.9 -2024,3,2,"--- Day 3: Mull It Over --- +print(result)",python +25,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. @@ -1785,8 +1785,8 @@ for row in data: else: sum += int(mul.group(1)) * int(mul.group(2)) * current -print(sum)",python:3.9 -2024,3,2,"--- Day 3: Mull It Over --- +print(sum)",python +26,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. @@ -1837,8 +1837,8 @@ for res in findall(r""mul\((\d+),(\d+)\)|(don't\(\))|(do\(\))"", input_text): do = False elif (not do) and res[3]: do = True -print(total)",python:3.9 -2024,3,2,"--- Day 3: Mull It Over --- +print(total)",python +27,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. @@ -1901,8 +1901,8 @@ def main(): print(f""total: {total}"") if __name__ == ""__main__"": - main()",python:3.9 -2024,3,2,"--- Day 3: Mull It Over --- + main()",python +28,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. @@ -1964,8 +1964,8 @@ with open('input.txt', 'r') as f: if doCompute: nums = re.findall(num_pattern, match) res += reduce(lambda x, y: int(x) * int(y), nums) - print(res)",python:3.9 -2024,3,2,"--- Day 3: Mull It Over --- + print(res)",python +29,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. @@ -2039,8 +2039,8 @@ 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 -2024,4,1,"--- Day 4: Ceres Search --- + print(sum)",python +30,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! @@ -2116,8 +2116,8 @@ with open(""04_input.txt"", ""r"") as f: width = len(words[0]) height = len(words) -main()",python:3.9 -2024,4,1,"--- Day 4: Ceres Search --- +main()",python +31,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! @@ -2209,8 +2209,8 @@ def main(): pprint.pprint(result) if __name__ == ""__main__"": - main()",python:3.9 -2024,4,1,"--- Day 4: Ceres Search --- + main()",python +32,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! @@ -2282,8 +2282,8 @@ for i in range(n): for d in dd: ans += has_xmas(i, j, d) -print(ans)",python:3.9 -2024,4,1,"--- Day 4: Ceres Search --- +print(ans)",python +33,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! @@ -2399,8 +2399,8 @@ if __name__ == ""__main__"": 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 -2024,4,1,"--- Day 4: Ceres Search --- + print(f""Part 2: {p_2_solution} (took {(end - middle) * 1000:.3f}ms)"")",python +34,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! @@ -2478,8 +2478,8 @@ 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 -2024,4,2,"--- Day 4: Ceres Search --- +print(total)",python +35,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! @@ -2585,8 +2585,8 @@ def count_word_for_pos(matrix: list[list], pos: tuple[int, int], word: str) -> i return count if __name__ == ""__main__"": - main()",python:3.9 -2024,4,2,"--- Day 4: Ceres Search --- + main()",python +36,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! @@ -2729,8 +2729,8 @@ def part2(): total = find_x_mas(input) print(total) -part2()",python:3.9 -2024,4,2,"--- Day 4: Ceres Search --- +part2()",python +37,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! @@ -2931,8 +2931,8 @@ def main(): if __name__ == ""__main__"": main() -# -----------------------------------------------------------------------------",python:3.9 -2024,4,2,"--- Day 4: Ceres Search --- +# -----------------------------------------------------------------------------",python +38,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! @@ -3021,8 +3021,8 @@ for grid in grids_3x3: (re.match(r""M.S"", grid[0]) and re.match(r""M.S"", grid[2])): count+=1 -print(count)",python:3.9 -2024,4,2,"--- Day 4: Ceres Search --- +print(count)",python +39,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! @@ -3125,8 +3125,8 @@ for x in range(len(cont)): t += check(matrix) -print(t)",python:3.9 -2024,5,1,"--- Day 5: Print Queue --- +print(t)",python +40,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. @@ -3243,8 +3243,8 @@ def correct_order(page_update): if __name__ == ""__main__"": - main()",python:3.9 -2024,5,1,"--- Day 5: Print Queue --- + main()",python +41,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. @@ -3401,8 +3401,8 @@ for update in correct_updates: print(f""Tally: {tally}"") total = sum(tally) -print(f""Result: {total}"")",python:3.9 -2024,5,1,"--- Day 5: Print Queue --- +print(f""Result: {total}"")",python +42,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. @@ -3532,8 +3532,8 @@ 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 -2024,5,1,"--- Day 5: Print Queue --- +print(sum(midNums))",python +43,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. @@ -3757,8 +3757,8 @@ def main(): if __name__ == ""__main__"": main() -# -----------------------------------------------------------------------------",python:3.9 -2024,5,1,"--- Day 5: Print Queue --- +# -----------------------------------------------------------------------------",python +44,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. @@ -3874,8 +3874,8 @@ 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 -2024,5,2,"--- Day 5: Print Queue --- + print(total)",python +45,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. @@ -4022,8 +4022,8 @@ for update in updates: seq = sort_correctly(update) ans += seq[len(seq) // 2] -print(ans)",python:3.9 -2024,5,2,"--- Day 5: Print Queue --- +print(ans)",python +46,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. @@ -4146,8 +4146,8 @@ with open(""05_input.txt"", ""r"") as f: continue break -print(result)",python:3.9 -2024,5,2,"--- Day 5: Print Queue --- +print(result)",python +47,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. @@ -4289,8 +4289,8 @@ for update in updates: update = fix_update(order, update) total += update[len(update)//2] -print(total)",python:3.9 -2024,5,2,"--- Day 5: Print Queue --- +print(total)",python +48,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. @@ -4431,8 +4431,8 @@ for update in updates: fixed = fix(update, rules) total += fixed[len(fixed) // 2] -print(total)",python:3.9 -2024,5,2,"--- Day 5: Print Queue --- +print(total)",python +49,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. @@ -4570,8 +4570,8 @@ for update in updates: middle = fixed[len(fixed)//2] total += middle -print(total)",python:3.9 -2024,6,1,"--- Day 6: Guard Gallivant --- +print(total)",python +50,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. @@ -4706,8 +4706,8 @@ 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 -2024,6,1,"--- Day 6: Guard Gallivant --- + print(""Number of unique positions: "" + str(get_unique_positions(grid)))",python +51,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. @@ -4835,8 +4835,8 @@ def main(): def turn_right(x: int) -> int: return (x + 1) % 4 -main()",python:3.9 -2024,6,1,"--- Day 6: Guard Gallivant --- +main()",python +52,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. @@ -4973,8 +4973,8 @@ while 0 <= pos[0] < n_rows and 0 <= pos[1] < n_cols: pos = next_pos -print(len(visited))",python:3.9 -2024,6,1,"--- Day 6: Guard Gallivant --- +print(len(visited))",python +53,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. @@ -5124,8 +5124,8 @@ with open(""input.txt"", ""r"") as f: next = direction.next_pos(pos) pos = next - print(len(visited))",python:3.9 -2024,6,1,"--- Day 6: Guard Gallivant --- + print(len(visited))",python +54,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. @@ -5256,8 +5256,8 @@ while True: cord = (newx,newy) -print(len(visited))",python:3.9 -2024,6,2,"--- Day 6: Guard Gallivant --- +print(len(visited))",python +55,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. @@ -5503,8 +5503,8 @@ result = len(valid_positions) execution_time = time.time() - start_time print(result) -print(f""Time: {execution_time:.3f} seconds"")",python:3.9 -2024,6,2,"--- Day 6: Guard Gallivant --- +print(f""Time: {execution_time:.3f} seconds"")",python +56,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. @@ -5854,8 +5854,8 @@ for i, obs in enumerate(possible_obstacles): if check_loop(m, i + 1, len(possible_obstacles)): cont += 1 -print(cont)",python:3.9 -2024,6,2,"--- Day 6: Guard Gallivant --- +print(cont)",python +57,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. @@ -6094,8 +6094,8 @@ 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 -2024,6,2,"--- Day 6: Guard Gallivant --- + print(""Number of possible obstacles: "" + str(get_possible_obstacles(grid)))",python +58,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. @@ -6341,8 +6341,8 @@ def main(): print(f""Amount of possible places for obstructions to put guard in a loop: {get_obstructions(puzzle)}"") if __name__ == ""__main__"": - main()",python:3.9 -2024,6,2,"--- Day 6: Guard Gallivant --- + main()",python +59,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. @@ -6587,8 +6587,8 @@ for i in range(n_rows): loop_ct += 1 grid[i][j] = '.' -print(loop_ct)",python:3.9 -2024,7,1,"--- Day 7: Bridge Repair --- +print(loop_ct)",python +60,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? @@ -6670,8 +6670,8 @@ class Solution: solution = Solution() -print(solution.calibration_result())",python:3.9 -2024,7,1,"--- Day 7: Bridge Repair --- +print(solution.calibration_result())",python +61,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? @@ -6735,8 +6735,8 @@ for res,nums in data: p1 += gen(nums) -print(p1)",python:3.9 -2024,7,1,"--- Day 7: Bridge Repair --- +print(p1)",python +62,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? @@ -6784,8 +6784,8 @@ def find_solution(answer, terms): return find_solution(answer, [terms[0]+terms[1]]+terms[2:]) \ or find_solution(answer, [terms[0]*terms[1]]+terms[2:]) -main()",python:3.9 -2024,7,1,"--- Day 7: Bridge Repair --- +main()",python +63,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? @@ -6844,8 +6844,8 @@ for line in f: total += test_value -print(total)",python:3.9 -2024,7,1,"--- Day 7: Bridge Repair --- +print(total)",python +64,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? @@ -6893,8 +6893,8 @@ for line in lines: if is_valid(test_val, 0, vals): total += test_val -print(total)",python:3.9 -2024,7,2,"--- Day 7: Bridge Repair --- +print(total)",python +65,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? @@ -7021,8 +7021,8 @@ if __name__ == ""__main__"": data = f.readlines() data = [line.strip() for line in data] #part1(data) - part2(data)",python:3.9 -2024,7,2,"--- Day 7: Bridge Repair --- + part2(data)",python +66,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? @@ -7108,8 +7108,8 @@ for res, nums in data: p2 += gen(nums) -print(p2)",python:3.9 -2024,7,2,"--- Day 7: Bridge Repair --- +print(p2)",python +67,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? @@ -7161,8 +7161,8 @@ from part1 import read_input, sum_valid_expressions if __name__ == ""__main__"": expressions = read_input('input.txt') - print( sum_valid_expressions(expressions, ['+', '*', '||']))",python:3.9 -2024,7,2,"--- Day 7: Bridge Repair --- + print( sum_valid_expressions(expressions, ['+', '*', '||']))",python +68,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? @@ -7264,8 +7264,8 @@ with open(input,'r') as f: elif (a3 == items[0]): total=total+a3 -print(f""Total = {total}"")",python:3.9 -2024,7,2,"--- Day 7: Bridge Repair --- +print(f""Total = {total}"")",python +69,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? @@ -7341,8 +7341,8 @@ for i, line in enumerate(lines): break -print(ans)",python:3.9 -2024,8,1,"--- Day 8: Resonant Collinearity --- +print(ans)",python +70,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7452,8 +7452,8 @@ def main(): print(len(antinodes)) -main()",python:3.9 -2024,8,1,"--- Day 8: Resonant Collinearity --- +main()",python +71,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7567,8 +7567,8 @@ for freq in all_locs: antinodes.add(antinode) -print(len(antinodes))",python:3.9 -2024,8,1,"--- Day 8: Resonant Collinearity --- +print(len(antinodes))",python +72,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7692,8 +7692,8 @@ for key, coordinates in antennas.items(): if node not in antinodes: antinodes.append(node) -print(len(antinodes))",python:3.9 -2024,8,1,"--- Day 8: Resonant Collinearity --- +print(len(antinodes))",python +73,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7794,8 +7794,8 @@ for frequency in antenna_map: antinodes.add(antinode) del antennas[0] -print(f""There's {len(antinodes)} unique locations containing an antinode"")",python:3.9 -2024,8,1,"--- Day 8: Resonant Collinearity --- +print(f""There's {len(antinodes)} unique locations containing an antinode"")",python +74,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -7938,8 +7938,8 @@ for frequency in unique_frequencies: print(grid) -print(len(grid.antinode_locations))",python:3.9 -2024,8,2,"--- Day 8: Resonant Collinearity --- +print(len(grid.antinode_locations))",python +75,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8099,8 +8099,8 @@ for a in uniq: ans += 1 nodes.add(node_b) -print(ans)",python:3.9 -2024,8,2,"--- Day 8: Resonant Collinearity --- +print(ans)",python +76,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8290,8 +8290,8 @@ for frequency in unique_frequencies: print(grid) -print(len(grid.antinode_locations))",python:3.9 -2024,8,2,"--- Day 8: Resonant Collinearity --- +print(len(grid.antinode_locations))",python +77,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8443,8 +8443,8 @@ for frequencies in dictionary.values(): print(frequencies) add_antinodes(frequencies) -print(len(anti_nodes))",python:3.9 -2024,8,2,"--- Day 8: Resonant Collinearity --- +print(len(anti_nodes))",python +78,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8634,8 +8634,8 @@ for key in char_to_coord_map.keys(): print(len(antinodes)) -# print(antinodes)",python:3.9 -2024,8,2,"--- Day 8: Resonant Collinearity --- +# print(antinodes)",python +79,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -8801,8 +8801,8 @@ def solve(filename): if __name__ == ""__main__"": res = solve(""i.txt"") - print(res)",python:3.9 -2024,9,1,"--- Day 9: Disk Fragmenter --- + print(res)",python +80,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. @@ -8886,8 +8886,8 @@ while file_structure: current_index += length if buffer: total += int(buffer[0] * buffer[1] * (current_index + (buffer[1] - 1) / 2)) -print(total)",python:3.9 -2024,9,1,"--- Day 9: Disk Fragmenter --- +print(total)",python +81,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. @@ -8992,8 +8992,8 @@ def main(): print(f'Result: {checksum(sorted_input)}') if __name__ == ""__main__"": - main()",python:3.9 -2024,9,1,"--- Day 9: Disk Fragmenter --- + main()",python +82,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. @@ -9090,8 +9090,8 @@ def compute_checksum(array): 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 -2024,9,1,"--- Day 9: Disk Fragmenter --- +print(compute_checksum(disk_blocks))",python +83,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. @@ -9186,8 +9186,8 @@ def checksum(arr): return ans ans = checksum(move(filesystem)) -print(ans)",python:3.9 -2024,9,1,"--- Day 9: Disk Fragmenter --- +print(ans)",python +84,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. @@ -9283,8 +9283,8 @@ result = [item for sublist in result for item in sublist] # print("""".join(result)) compressed = compressFile(result) # print("""".join(compressed)) -print(calculateCheckSum(compressed))",python:3.9 -2024,9,2,"--- Day 9: Disk Fragmenter --- +print(calculateCheckSum(compressed))",python +85,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. @@ -9445,8 +9445,8 @@ def main(): print(f'Result: {checksum(list_input)}') if __name__ == ""__main__"": - main()",python:3.9 -2024,9,2,"--- Day 9: Disk Fragmenter --- + main()",python +86,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. @@ -9561,8 +9561,8 @@ def main(): print(checksum(layout)) if __name__ == ""__main__"": - main()",python:3.9 -2024,9,2,"--- Day 9: Disk Fragmenter --- + main()",python +87,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. @@ -9703,8 +9703,8 @@ def compute_checksum(array): 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 -2024,9,2,"--- Day 9: Disk Fragmenter --- +print(compute_checksum(disk_blocks))",python +88,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. @@ -9835,8 +9835,8 @@ 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 -2024,9,2,"--- Day 9: Disk Fragmenter --- +print(f""Checksum: {calculateCheckSum(compacted_file)}"")",python +89,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. @@ -9944,8 +9944,8 @@ for file_id, file_length in file_structure: if file_id != -1: total += int(file_id * file_length * (idx + (file_length - 1) / 2)) idx += file_length -print(total)",python:3.9 -2024,10,1,"--- Day 10: Hoof It --- +print(total)",python +90,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. @@ -10064,8 +10064,8 @@ 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 -2024,10,1,"--- Day 10: Hoof It --- +print(res)",python +91,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. @@ -10157,8 +10157,8 @@ for height in range(8, -1, -1): new_nine_reachable_from[nine_point] = new_reachable_froms nine_reachable_from = new_nine_reachable_from -print(sum(len(starting_points) for starting_points in nine_reachable_from.values()))",python:3.9 -2024,10,1,"--- Day 10: Hoof It --- +print(sum(len(starting_points) for starting_points in nine_reachable_from.values()))",python +92,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. @@ -10270,8 +10270,8 @@ for yi in range(ymax): if lines[yi][xi] == '0': score += Trail(xi, yi).score() -print(score)",python:3.9 -2024,10,1,"--- Day 10: Hoof It --- +print(score)",python +93,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. @@ -10377,8 +10377,8 @@ trailheads = 0 for start in starts: trailheads += dfs(start, 0, set()) -print(trailheads)",python:3.9 -2024,10,1,"--- Day 10: Hoof It --- +print(trailheads)",python +94,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. @@ -10478,8 +10478,8 @@ for trailHead in TrailHeads: print(f""first trail head score: {calculateTrailHeadScore(TrailHeads[0])}"") print(TrailHeads) -print(score)",python:3.9 -2024,10,2,"--- Day 10: Hoof It --- +print(score)",python +95,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. @@ -10634,8 +10634,8 @@ You're not sure how, but the reindeer seems to have crafted some tiny flags out if __name__ == '__main__': - main()",python:3.9 -2024,10,2,"--- Day 10: Hoof It --- + main()",python +96,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. @@ -10787,8 +10787,8 @@ for trailHead in TrailHeads: print(f""first trail head score: {calculateTrailHeadScore(TrailHeads[0])}"") print(TrailHeads) -print(score)",python:3.9 -2024,10,2,"--- Day 10: Hoof It --- +print(score)",python +97,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. @@ -11022,8 +11022,8 @@ print(total_score2) # Save timestamp end = time.time() print(""~~~~~~~~~~ RUNTIME ~~~~~~~~~~~~~~"") -print(round(end - start, 3))",python:3.9 -2024,10,2,"--- Day 10: Hoof It --- +print(round(end - start, 3))",python +98,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. @@ -11187,8 +11187,8 @@ for row in range(len(trail_map)): for col in range(len(trail_map[row])): if trail_map[row][col] == 0: answer += bfs(trail_map, (row, col)) -print(answer)",python:3.9 -2024,10,2,"--- Day 10: Hoof It --- +print(answer)",python +99,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. @@ -11354,8 +11354,8 @@ for y in range(h): # if res > 0: # exit(0) -print(res)",python:3.9 -2024,11,1,"--- Day 11: Plutonian Pebbles --- +print(res)",python +100,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. @@ -11430,8 +11430,8 @@ for i in range(25): get_next_stones() -print(len(stones))",python:3.9.21-slim -2024,11,1,"--- Day 11: Plutonian Pebbles --- +print(len(stones))",python +101,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. @@ -11502,8 +11502,8 @@ 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 --- +print(res)",python +102,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. @@ -11580,8 +11580,8 @@ if __name__ == ""__main__"": 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 --- + print(""Number of Stones: "" + str(get_num_stones(stones)))",python +103,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. @@ -11659,8 +11659,8 @@ with open('input.txt') as f: 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 --- +print(len(stones))",python +104,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. @@ -11734,8 +11734,8 @@ def blink(value, times): 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 --- + print(result)",python +105,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. @@ -11816,8 +11816,8 @@ def stones_created(num, rounds): 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 --- +print(sum(stones_created(x, 75) for x in nums))",python +106,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. @@ -11899,8 +11899,8 @@ def blink(value, times): 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 --- + print(result)",python +107,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. @@ -12009,8 +12009,8 @@ for iter in range(75): total_nums = new_total_nums total = sum(total_nums.values()) -print(total)",python:3.9.21-slim -2024,11,2,"--- Day 11: Plutonian Pebbles --- +print(total)",python +108,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. @@ -12104,8 +12104,8 @@ for i in range(75): ans = 0 for x in nums: ans += nums[x] -print(ans)",python:3.9.21-slim -2024,11,2,"--- Day 11: Plutonian Pebbles --- +print(ans)",python +109,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. @@ -12226,8 +12226,8 @@ 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 --- +print(res)",python +110,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. @@ -12367,8 +12367,8 @@ width = len(garden[0]) height = len(garden) if __name__ == '__main__': - main()",python:3.9.21-slim -2024,12,1,"--- Day 12: Garden Groups --- + main()",python +111,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. @@ -12527,8 +12527,8 @@ for region in regions: 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 --- +print(total_price)",python +112,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. @@ -12643,8 +12643,8 @@ for i in range(len(input)): 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 --- +print(f""The total price of fencing all the regions is {total}"")",python +113,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. @@ -12774,8 +12774,8 @@ for yi in range(ymax): total += calc_plot(xi, yi) -print(total)",python:3.9.21-slim -2024,12,1,"--- Day 12: Garden Groups --- +print(total)",python +114,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. @@ -12925,8 +12925,8 @@ def main(): print(f'Cost: {calculateCosts(plots)}') if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,12,2,"--- Day 12: Garden Groups --- + main()",python +115,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. @@ -13118,8 +13118,8 @@ for i in range(len(input)): 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 --- +print(f""The total price of fencing all the regions is {total}"")",python +116,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. @@ -13356,8 +13356,8 @@ 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 --- +print(total_price)",python +117,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. @@ -13577,8 +13577,8 @@ for yi in range(ymax): total += calc_plot(xi, yi) -print(total)",python:3.9.21-slim -2024,12,2,"--- Day 12: Garden Groups --- +print(total)",python +118,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. @@ -13786,8 +13786,8 @@ width = len(garden[0]) height = len(garden) if __name__ == '__main__': - main()",python:3.9.21-slim -2024,12,2,"--- Day 12: Garden Groups --- + main()",python +119,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. @@ -14007,8 +14007,8 @@ if __name__ == ""__main__"": 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 --- + print(""Total fencing cost: "" + str(get_total_cost(farm)))",python +120,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. @@ -14086,8 +14086,8 @@ for problem in range((len(input_text) + 1) // 4): 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 --- +print(total)",python +121,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. @@ -14165,8 +14165,8 @@ for a, b, p in [parse(line) for line in lines]: spent = 0 -print(sum(prices))",python:3.9.21-slim -2024,13,1,"--- Day 13: Claw Contraption --- +print(sum(prices))",python +122,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. @@ -14284,8 +14284,8 @@ def main(): print(f""Result: {sum(costs_list)}"") if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,13,1,"--- Day 13: Claw Contraption --- + main()",python +123,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. @@ -14358,8 +14358,8 @@ for machine in machines: cost = get_cost(solution) total += cost -print(total)",python:3.9.21-slim -2024,13,1,"--- Day 13: Claw Contraption --- +print(total)",python +124,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. @@ -14436,8 +14436,8 @@ def part1(): t += l[1] print(t) -part1()",python:3.9.21-slim -2024,13,2,"--- Day 13: Claw Contraption --- +part1()",python +125,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. @@ -14565,8 +14565,8 @@ if __name__ == ""__main__"": 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 --- + print(""Fewest number of tokens: "" + str(get_fewest_tokens(machines)))",python +126,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. @@ -14668,8 +14668,8 @@ for machine in machines: cost = get_cost(solution) total += cost -print(total)",python:3.9.21-slim -2024,13,2,"--- Day 13: Claw Contraption --- +print(total)",python +127,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. @@ -14800,8 +14800,8 @@ 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 --- + print(sum(results))",python +128,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. @@ -14917,8 +14917,8 @@ for claw in claw_data: if res[0]: total_cost += res[1] -print(total_cost)",python:3.9.21-slim -2024,13,2,"--- Day 13: Claw Contraption --- +print(total_cost)",python +129,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. @@ -15043,8 +15043,8 @@ for problem in range((len(input_text) + 1) // 4): ): total += 3 * sol_a + sol_b -print(total)",python:3.9.21-slim -2024,14,1,"--- Day 14: Restroom Redoubt --- +print(total)",python +130,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. @@ -15242,8 +15242,8 @@ if __name__ == ""__main__"": 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 --- + solve_part2(robots, width, height)",python +131,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. @@ -15413,8 +15413,8 @@ for robot in robots: 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 --- +print(counter[1] * counter[2] * counter[3] * counter[4])",python +132,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. @@ -15581,8 +15581,8 @@ 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 --- + len(quadrant_1) * len(quadrant_2) * len(quadrant_3) * len(quadrant_4))",python +133,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. @@ -15795,8 +15795,8 @@ def main(): print(safety_score(robots)) if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,14,1,"--- Day 14: Restroom Redoubt --- + main()",python +134,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. @@ -15946,8 +15946,8 @@ for robot in robots: 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 --- +print(reduce(mul, quadrants.values()))",python +135,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. @@ -16102,8 +16102,8 @@ def simulate_motion(positions, velocities, num_x=101, num_y=103, steps=10000): if __name__ == ""__main__"": positions, velocities = read_input(""input.txt"") - simulate_motion(positions, velocities)",python:3.9.21-slim -2024,14,2,"--- Day 14: Restroom Redoubt --- + simulate_motion(positions, velocities)",python +136,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. @@ -16252,8 +16252,8 @@ for counter in range(10000): 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 --- + initial_positions = new_initial_positions",python +137,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. @@ -16392,8 +16392,8 @@ for T in range(R*C): while '#'*t in S: t += 1 if t > B[0]: B = (t, T) if T == 100: print('Part 1:', Z[0]*Z[1]*Z[2]*Z[3]) -print('Part 2:', B[1])",python:3.9.21-slim -2024,14,2,"--- Day 14: Restroom Redoubt --- +print('Part 2:', B[1])",python +138,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. @@ -16585,8 +16585,8 @@ print(""at second: "", found_at_second) # O(WIDE * TALL * n) so kindof O(n) :) # Total space complexity -# O(WIDE * TALL + n) so kindof O(n) :)",python:3.9.21-slim -2024,14,2,"--- Day 14: Restroom Redoubt --- +# O(WIDE * TALL + n) so kindof O(n) :)",python +139,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. @@ -16765,8 +16765,8 @@ for i in range(1, 100000): #the tree picture has 31 robots in a single row if max_sum > 30: print(i) - break",python:3.9.21-slim -2024,15,1,"--- Day 15: Warehouse Woes --- + break",python +140,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? @@ -17045,8 +17045,8 @@ for i 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 --- +print(total)",python +141,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? @@ -17406,8 +17406,8 @@ for direction in commands: 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 --- +print(sum(x.score for x in boxes))",python +142,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? @@ -17727,8 +17727,8 @@ if __name__ == ""__main__"": 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 --- + print(f""\nSum of all boxes' GPS coordinates: {gps_sum}"")",python +143,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? @@ -18018,8 +18018,8 @@ for i in range(len(warehouse_map)): 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 --- +print(f""The sum of all boxes' GPS coordinates is {total}"")",python +144,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? @@ -18322,8 +18322,8 @@ if __name__ == ""__main__"": 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 --- + print(""Final Coordinates of Boxes: "" + str(get_box_coords(grid, instructions)))",python +145,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? @@ -18888,8 +18888,8 @@ def part2(): 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 --- +part2()",python +146,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? @@ -19412,8 +19412,8 @@ for i in range(len(grid)): if grid[i][j] == '[': total += 100 * i + j -print(total)",python:3.9.21-slim -2024,15,2,"--- Day 15: Warehouse Woes --- +print(total)",python +147,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? @@ -19930,8 +19930,8 @@ boxes = set() moves = [] if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,15,2,"--- Day 15: Warehouse Woes --- + main()",python +148,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? @@ -20528,8 +20528,8 @@ 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 --- +print(warehouse.sum_of_box_locations())",python +149,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? @@ -21036,8 +21036,8 @@ for i in range(len(warehouse_map)): 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 --- +print(f""The sum of all boxes' final GPS coordinates is {total}"")",python +150,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. @@ -21173,8 +21173,8 @@ if __name__ == ""__main__"": 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 --- + print(""Lowest Score:"", get_lowest_score(maze))",python +151,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. @@ -21294,8 +21294,8 @@ def dijkstra(grid): 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 --- +print(dijkstra(grid))",python +152,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. @@ -21419,8 +21419,8 @@ while len(q) > 0: (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 --- + heappush(q, nbr)",python +153,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. @@ -21611,8 +21611,8 @@ if __name__ == ""__main__"": 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 --- + print(score)",python +154,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. @@ -21749,8 +21749,8 @@ while len(q) > 0: 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 --- + heappush(q, nbr)",python +155,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. @@ -21950,8 +21950,8 @@ while len(stack) > 0: for nbr in deps[top]: stack.append(nbr) -print(len(seen_pos))",python:3.9.21-slim -2024,16,2,"--- Day 16: Reindeer Maze --- +print(len(seen_pos))",python +156,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. @@ -22144,8 +22144,8 @@ 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 --- +res",python +157,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. @@ -22323,8 +22323,8 @@ while pq and pq[0][0] <= best_score: seats = set() for path in paths: seats |= set(path) -print(len(seats))",python:3.9.21-slim -2024,16,2,"--- Day 16: Reindeer Maze --- +print(len(seats))",python +158,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. @@ -22587,8 +22587,8 @@ def tilesApartFromMaze() -> int: print(len(spaces)) -tilesApartFromMaze()",python:3.9.21-slim -2024,16,2,"--- Day 16: Reindeer Maze --- +tilesApartFromMaze()",python +159,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. @@ -22789,8 +22789,8 @@ def solve_part_2(text: str): 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 --- + p_2_solution = int(solve_part_2(quiz_input))",python +160,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. @@ -22910,8 +22910,8 @@ while instr_ptr < len(instructions): if not jump: instr_ptr += 2 -print("","".join(map(str, output)))",python:3.9.21-slim -2024,17,1,"--- Day 17: Chronospatial Computer --- +print("","".join(map(str, output)))",python +161,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. @@ -23020,8 +23020,8 @@ def main() -> None: if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,17,1,"--- Day 17: Chronospatial Computer --- + main()",python +162,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. @@ -23147,8 +23147,8 @@ while instruction_pointer < len(program): instruction_pointer += 2 -print(""Program output:"", "","".join(output))",python:3.9.21-slim -2024,17,1,"--- Day 17: Chronospatial Computer --- +print(""Program output:"", "","".join(output))",python +163,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. @@ -23302,8 +23302,8 @@ if __name__ == ""__main__"": 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 --- + print(""Result String:"", get_result_string(regs, instructions))",python +164,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. @@ -23438,8 +23438,8 @@ 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 --- + main()",python +165,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. @@ -23592,8 +23592,8 @@ if __name__ == ""__main__"": 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 --- + print(""Lowest value of Register A:"", get_lowest_a(regs, instructions))",python +166,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. @@ -23751,8 +23751,8 @@ if __name__ == ""__main__"": 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 --- + print(""No initial value found that produces the target output within the given attempts."")",python +167,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. @@ -23851,8 +23851,8 @@ while position < len(program): offsets[-1] += 1 -print(a // 8)",python:3.9.21-slim -2024,17,2,"--- Day 17: Chronospatial Computer --- +print(a // 8)",python +168,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. @@ -23999,8 +23999,8 @@ while current>0: solutions = next_solutions part2 = min(solutions) -print(part2)",python:3.9.21-slim -2024,17,2,"--- Day 17: Chronospatial Computer --- +print(part2)",python +169,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. @@ -24125,8 +24125,8 @@ def part2(): print(backtrack()) -part2()",python:3.9.21-slim -2024,18,1,"--- Day 18: RAM Run --- +part2()",python +170,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! @@ -24215,8 +24215,8 @@ while True: 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 --- + heappush(discovered, (distance + 1, *new_position))",python +171,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! @@ -24357,8 +24357,8 @@ if __name__ == ""__main__"": 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 --- + print(f""Minimum number of steps needed to reach the exit: {steps}"")",python +172,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! @@ -24474,8 +24474,8 @@ if __name__ == ""__main__"": 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 --- + print(""Minimum steps:"", get_min_steps(bytes))",python +173,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! @@ -24572,8 +24572,8 @@ 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 --- +print(len(bfs(set(byte_locs[0:1024]), x_len, y_len)) - 1)",python +174,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! @@ -24664,8 +24664,8 @@ while len(q) > 0: 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 --- + heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj))",python +175,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! @@ -24794,8 +24794,8 @@ while bytes_needed_lower < bytes_needed_upper: 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 --- +print("","".join([str(x) for x in bytes_list[bytes_needed_lower - 1]]))",python +176,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! @@ -24935,8 +24935,8 @@ while lower <= upper: 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 --- +print(byte_locs[mid])",python +177,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! @@ -25072,8 +25072,8 @@ while hi > lo: else: hi = mid -print("","".join(map(str, coords[lo-1])))",python:3.9.21-slim -2024,18,2,"--- Day 18: RAM Run --- +print("","".join(map(str, coords[lo-1])))",python +178,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! @@ -25205,8 +25205,8 @@ def P2(): 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 --- +print(P2())",python +179,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! @@ -25352,8 +25352,8 @@ while blocked - unblocked > 1: 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 --- +print(""Part Two:"", part_two)",python +180,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. @@ -25515,8 +25515,8 @@ for design in designs: if pattern_found: results.append((design, patterns)) else: - impossible_designs.append(design)",python:3.9.21-slim -2024,19,1,"--- Day 19: Linen Layout --- + impossible_designs.append(design)",python +181,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. @@ -25587,8 +25587,8 @@ def pattern_possible(pattern): 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 --- +print(sum(pattern_possible(pattern) for pattern in input_text[2:]))",python +182,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. @@ -25644,8 +25644,8 @@ 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 --- +print(sum([is_pattern_possible(p, towels, set()) for p in patterns]))",python +183,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. @@ -25807,8 +25807,8 @@ for design in designs: if pattern_found: results.append((design, patterns)) else: - impossible_designs.append(design)",python:3.9.21-slim -2024,19,1,"--- Day 19: Linen Layout --- + impossible_designs.append(design)",python +184,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. @@ -25878,8 +25878,8 @@ for d in designs: print(d) ans += 1 -print(ans)",python:3.9.21-slim -2024,19,2,"--- Day 19: Linen Layout --- +print(ans)",python +185,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. @@ -25988,8 +25988,8 @@ if __name__ == ""__main__"": 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 --- + print(""Number of ways to acheive patterns:"", get_num_achievable_patterns(towels, patterns))",python +186,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. @@ -26084,8 +26084,8 @@ 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 --- +print(sum([num_possible_patterns(p, towels, dict()) for p in patterns]))",python +187,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. @@ -26192,8 +26192,8 @@ def pattern_possible(pattern): 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 --- +print(sum(pattern_possible(pattern) for pattern in input_text[2:]))",python +188,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. @@ -26311,8 +26311,8 @@ 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 --- + print(result)",python +189,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. @@ -26428,8 +26428,8 @@ def main() -> None: if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,21,1,"--- Day 21: Keypad Conundrum --- + main()",python +190,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. @@ -26667,8 +26667,8 @@ print(total) # print(sol1) # print(code) -# print(calculateComplexity(""029A""))",python:3.9.21-slim -2024,21,1,"--- Day 21: Keypad Conundrum --- +# print(calculateComplexity(""029A""))",python +191,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. @@ -26828,8 +26828,8 @@ for line in lines: total_complexity += int(line[0:-1]) * len(l3) -print(total_complexity)",python:3.9.21-slim -2024,21,1,"--- Day 21: Keypad Conundrum --- +print(total_complexity)",python +192,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. @@ -27128,8 +27128,8 @@ def main(): if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,21,1,"--- Day 21: Keypad Conundrum --- + main()",python +193,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. @@ -27327,8 +27327,8 @@ def solve(sequence: str, level: int, max_level: int = 2) -> int: 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 --- + print(result)",python +194,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. @@ -27516,8 +27516,8 @@ for code in input_text: 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 --- +print(total)",python +195,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. @@ -27776,8 +27776,8 @@ def main(): if __name__ == '__main__': - main()",python:3.9.21-slim -2024,21,2,"--- Day 21: Keypad Conundrum --- + main()",python +196,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. @@ -27971,8 +27971,8 @@ for line in lines: 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 --- +print(total_complexity)",python +197,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. @@ -28181,8 +28181,8 @@ def find_total_complexity(codes, levels): return sum(complexities) -print(find_total_complexity(input, 25))",python:3.9.21-slim -2024,21,2,"--- Day 21: Keypad Conundrum --- +print(find_total_complexity(input, 25))",python +198,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. @@ -28377,8 +28377,8 @@ 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 --- +print(""Part Two:"", part_two)",python +199,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. @@ -28540,8 +28540,8 @@ def part2(): print(ans) -part2()",python:3.9.21-slim -2024,23,1,"--- Day 23: LAN Party --- +part2()",python +200,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). @@ -28624,8 +28624,8 @@ for pair in pairs: 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 --- +print(len(trios_with_t))",python +201,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). @@ -28768,8 +28768,8 @@ def main(): if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,23,1,"--- Day 23: LAN Party --- + main()",python +202,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). @@ -28857,8 +28857,8 @@ 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 --- +print(ans)",python +203,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). @@ -28972,8 +28972,8 @@ if __name__ == ""__main__"": mapping = readfile() print(""Answer to part 1:"") - part1(mapping)",python:3.9.21-slim -2024,23,1,"--- Day 23: LAN Party --- + part1(mapping)",python +204,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). @@ -29069,8 +29069,8 @@ for t in trios: part_one += 1 -print(""Part One:"", part_one)",python:3.9.21-slim -2024,23,2,"--- Day 23: LAN Party --- +print(""Part One:"", part_one)",python +205,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). @@ -29178,8 +29178,8 @@ for pair in pairs: 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 --- +print("","".join(sorted(max(cliques, key=len))))",python +206,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). @@ -29308,8 +29308,8 @@ for triplet in triplets: ans += 1 print(triplet) -print(ans)",python:3.9.21-slim -2024,23,2,"--- Day 23: LAN Party --- +print(ans)",python +207,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). @@ -29427,8 +29427,8 @@ for pair in pairs: 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 --- +print("","".join(sorted(max_clique)))",python +208,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). @@ -29542,8 +29542,8 @@ def bron_kerbosch(R, P, X): bron_kerbosch(set(), set(connections.keys()), set()) -print("","".join(sorted(max_clique)))",python:3.9.21-slim -2024,23,2,"--- Day 23: LAN Party --- +print("","".join(sorted(max_clique)))",python +209,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). @@ -29683,8 +29683,8 @@ def part2(): print("","".join(in_order)) -part2()",python:3.9.21-slim -2024,24,1,"--- Day 24: Crossed Wires --- +part2()",python +210,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. @@ -29973,8 +29973,8 @@ for i in range(1, bit_count-1): # 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 --- +print("","".join(sorted([x for y in swaps for x in y])))",python +211,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. @@ -30140,8 +30140,8 @@ 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 --- +print(total)",python +212,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. @@ -30320,8 +30320,8 @@ for key, val in sorted_output.items(): dec += val * (2**power) power += 1 -print(dec)",python:3.9.21-slim -2024,24,1,"--- Day 24: Crossed Wires --- +print(dec)",python +213,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. @@ -30496,8 +30496,8 @@ 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 --- +print('Decimal number output on the wires starting with ""z"":', int(z_bits, 2))",python +214,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. @@ -30702,8 +30702,8 @@ 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 --- +print("", "".join(wrong_z))",python +215,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. @@ -31075,8 +31075,8 @@ for i in range(len(input_digit_xors)): 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 --- +print("","".join(sorted(swaps.keys())))",python +216,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. @@ -31375,8 +31375,8 @@ for i in range(len(input_digit_xors)): 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 --- +print("","".join(sorted(swaps.keys())))",python +217,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. @@ -31722,8 +31722,8 @@ 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 --- + print(result)",python +218,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. @@ -31998,8 +31998,8 @@ for i in range(num_input_bits): carries.append(carry_output) -print(*sorted(swaps.keys()), sep="","")",python:3.9.21-slim -2024,24,2,"--- Day 24: Crossed Wires --- +print(*sorted(swaps.keys()), sep="","")",python +219,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. @@ -32278,8 +32278,8 @@ def part2(): print(','.join(sorted(chain(*swaps)))) -part2()",python:3.9.21-slim -2024,25,1,"--- Day 25: Code Chronicle --- +part2()",python +220,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. @@ -32411,8 +32411,8 @@ for lock in locks: 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 --- +print(""Part One:"", part_one)",python +221,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. @@ -32558,8 +32558,8 @@ for lock in locks: ans += good -print(ans)",python:3.9.21-slim -2024,25,1,"--- Day 25: Code Chronicle --- +print(ans)",python +222,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. @@ -32702,8 +32702,8 @@ if __name__ == ""__main__"": 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 --- + print(f""Part 2: {p_2_solution} (took {(end - middle) * 1000:.3f}ms)"")",python +223,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. @@ -32825,8 +32825,8 @@ with open(""day25-data.txt"") as file: 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 --- + print(""Day 25 part 1, sum ="", sum)",python +224,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. @@ -32964,8 +32964,8 @@ for i in range(0, len(lines), 8): 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 --- +print(ct_fit)",python +225,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. @@ -33043,8 +33043,8 @@ for i in range(0, len(data)): num = generateNextNumber(num) total += num -print(total)",python:3.9.21-slim -2024,22,1,"--- Day 22: Monkey Market --- +print(total)",python +226,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. @@ -33156,8 +33156,8 @@ def generate_2000th_secret(initial_secret: int) -> int: 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 --- + print(total)",python +227,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. @@ -33237,8 +33237,8 @@ def main(): print(total) if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,22,1,"--- Day 22: Monkey Market --- + main()",python +228,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. @@ -33309,8 +33309,8 @@ def hsh(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 --- +print(sum(s[-1] for s in secrets))",python +229,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. @@ -33390,8 +33390,8 @@ def main(): print(total) if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,22,2,"--- Day 22: Monkey Market --- + main()",python +230,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. @@ -33530,8 +33530,8 @@ for n in ns: changes.add(change) result[change] += ss[i + 4] -print(max(result.values()))",python:3.9.21-slim -2024,22,2,"--- Day 22: Monkey Market --- +print(max(result.values()))",python +231,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. @@ -33688,8 +33688,8 @@ def main(): print(max(sorok.values())) if __name__ == ""__main__"": - main()",python:3.9.21-slim -2024,22,2,"--- Day 22: Monkey Market --- + main()",python +232,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. @@ -33867,8 +33867,8 @@ 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 --- + print(f""Part 2: {p_2_solution}"")",python +233,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. @@ -34015,8 +34015,8 @@ def solve(p): return part2 -print(f'Solution: {solve(load(""22.txt""))}')",python:3.9.21-slim -2024,22,2,"--- Day 22: Monkey Market --- +print(f'Solution: {solve(load(""22.txt""))}')",python +234,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. @@ -34187,8 +34187,8 @@ def findMaxBananas(lines): best_sequence, max_bananas = findMaxBananas(lines) -print(max_bananas)",python:3.9.21-slim -2024,20,1,"--- Day 20: Race Condition --- +print(max_bananas)",python +235,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! @@ -34496,8 +34496,8 @@ for step in cheats.keys(): 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 --- +print(solution)",python +236,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! @@ -34693,8 +34693,8 @@ for key in cheats: if key >= 100: count += cheats[key] -print(count)",python:3.9.21-slim -2024,20,1,"--- Day 20: Race Condition --- +print(count)",python +237,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! @@ -34870,8 +34870,8 @@ 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 --- +print(ans)",python +238,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! @@ -35047,8 +35047,8 @@ 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 --- +print(sum(1 for s in shortcuts if s >= 100))",python +239,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! @@ -35250,8 +35250,8 @@ for 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 --- +print(count)",python +240,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! @@ -35469,8 +35469,8 @@ for (initial_row, initial_col), step in no_cheat_move_count.items(): 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 --- +print(sum(count for saving, count in cheats.items() if saving >= 100))",python +241,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! @@ -35712,8 +35712,8 @@ if __name__ == ""__main__"": 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 --- + part2(maze, start, end)",python +242,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! @@ -35949,8 +35949,8 @@ def get_cheats(cheat_length, limit): count += 1 return count -print(get_cheats(20, 100))",python:3.9.21-slim -2024,20,2,"--- Day 20: Race Condition --- +print(get_cheats(20, 100))",python +243,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! @@ -36243,8 +36243,8 @@ def solve2(grid, minsave): grid = parse_input('./inputs/day20.txt') solve1(grid, 100) -solve2(grid, 100)",python:3.9.21-slim -2024,20,2,"--- Day 20: Race Condition --- +solve2(grid, 100)",python +244,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! @@ -36473,8 +36473,8 @@ for a in visited: part_two += 1 print(""Part One:"", part_one) -print(""Part Two:"", part_two)",python:3.9.21-slim -2024,1,1,"--- Day 1: Historian Hysteria --- +print(""Part Two:"", part_two)",python +245,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. @@ -36538,8 +36538,8 @@ for (let i = 0; i < leftList.length; i++) { totalDistance += Math.abs(leftList[i] - rightList[i]); } -console.log('Total Distance:', totalDistance);",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- +console.log('Total Distance:', totalDistance);",javascript +246,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. @@ -36609,8 +36609,8 @@ const total_distance = left_list.reduce((accumulator, item, index) => { return accumulator + Math.abs(right_list[index] - item); }, 0); -console.log({ total_distance });",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- +console.log({ total_distance });",javascript +247,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. @@ -36689,8 +36689,8 @@ function calculateSimilarityScore(leftList, rightList) { const totalDistance = calculateTotalDistance(leftList, rightList); console.log('Part 1 - Total Distance:', totalDistance); const similarityScore = calculateSimilarityScore(leftList, rightList); -console.log('Part 2 - Similarity Score:', similarityScore);",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- +console.log('Part 2 - Similarity Score:', similarityScore);",javascript +248,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. @@ -36800,8 +36800,8 @@ fs.readFile('input.txt', 'utf-8', (err, data) => { // Output the result console.log('Total Distance:', totalDistance); -});",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- +});",javascript +249,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. @@ -36867,8 +36867,8 @@ sortedFirstLocations.forEach((location, index) => { accumulatedDistance += difference; }); -console.log(accumulatedDistance);",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- +console.log(accumulatedDistance);",javascript +250,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. @@ -37032,8 +37032,8 @@ module.exports = { }; // main1(); -main2();",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- +main2();",javascript +251,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. @@ -37137,8 +37137,8 @@ const part2 = (lists) => { similarityScore += (lists[1].filter(item => item === num).length * num); }) return similarityScore; -}",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- +}",javascript +252,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. @@ -37228,8 +37228,8 @@ for (let i = 0; i < leftNumbers.length; i++) { similarityScore += counter * leftNumbers[i]; } -console.log(similarityScore);",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- +console.log(similarityScore);",javascript +253,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. @@ -37328,8 +37328,8 @@ const secondSolution = () => { return similarity.reduce((acc, value) => acc + value, 0); }; -console.log(""second part result:"", secondSolution());",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- +console.log(""second part result:"", secondSolution());",javascript +254,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. @@ -37422,8 +37422,8 @@ firstLocations.forEach((firstLocation) => { similarityScore += locationSimilarityScore; }); -console.log(similarityScore);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +console.log(similarityScore);",javascript +255,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. @@ -37453,8 +37453,8 @@ while ((match = pattern.exec(input)) !== null) { sum += match[1] * match[2]; } -console.log(sum);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +console.log(sum);",javascript +256,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. @@ -37528,8 +37528,8 @@ const arrayofMarchesPart2Bis = (arrayofMarchesPart2.map((el => (el.match(regex)) const arrayMultipliedPart2 = arrayofMarchesPart2Bis.map((el => el.reduce((a , b) => a * b))); const arraySummedPart2 = arrayMultipliedPart2.reduce((a, b) => a + b); -console.log(arraySummedPart2);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +console.log(arraySummedPart2);",javascript +257,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. @@ -37562,8 +37562,8 @@ multiplications.forEach((thisMul) => { total += mulValue; }) -console.log(total);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +console.log(total);",javascript +258,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. @@ -37609,8 +37609,8 @@ const multiply_sum = rows.reduce((accumulator, row) => { return accumulator + sum; }, 0); -console.log({ multiply_sum });",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +console.log({ multiply_sum });",javascript +259,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. @@ -37649,8 +37649,8 @@ lines.forEach(line => { totalSum += number1 * number2; } }); -console.log(`Total sum of all multiplied numbers: ${totalSum}`);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +console.log(`Total sum of all multiplied numbers: ${totalSum}`);",javascript +260,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. @@ -37709,8 +37709,8 @@ parts.forEach((part) => { if (part.substring(0, 3) == 'don') doing = false; }); -console.log(total);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +console.log(total);",javascript +261,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. @@ -37775,8 +37775,8 @@ while ((match = instructionRegex.exec(inputString)) !== null) { } } -console.log(`Total sum of all multiplied numbers: ${totalSum}`);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +console.log(`Total sum of all multiplied numbers: ${totalSum}`);",javascript +262,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. @@ -37850,8 +37850,8 @@ const main2 = () => { module.exports = { parseInput, multiplyPairsTotal, parseAndMultiplyInput }; // main1(); -main2();",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +main2();",javascript +263,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. @@ -37928,8 +37928,8 @@ function question2() { }); } -question2();",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +question2();",javascript +264,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. @@ -38014,8 +38014,8 @@ function main() { } } -main(); // Run the main function to start the process",node:14 -2024,4,1,"--- Day 4: Ceres Search --- +main(); // Run the main function to start the process",javascript +265,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! @@ -38149,8 +38149,8 @@ let count = 0; Object.values(values).forEach((item) => { count += item; }); -console.log(count);",node:14 -2024,4,1,"--- Day 4: Ceres Search --- +console.log(count);",javascript +266,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! @@ -38258,8 +38258,8 @@ count++; } const wordCount = findWordCount(puzzleInput, ""XMAS""); -console.log(`Part 1: ${wordCount}`);",node:14 -2024,4,1,"--- Day 4: Ceres Search --- +console.log(`Part 1: ${wordCount}`);",javascript +267,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! @@ -38339,8 +38339,8 @@ for (let row = 0; row < numRows; row++) { } } -console.log(`The word ""XMAS"" appears ${count} times in the grid.`);",node:14 -2024,4,1,"--- Day 4: Ceres Search --- +console.log(`The word ""XMAS"" appears ${count} times in the grid.`);",javascript +268,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! @@ -38486,8 +38486,8 @@ const countXmasOccurrences = (inputFilePath) => { }; const totalXmasOccurrences = countXmasOccurrences(""./puzzle-input.txt""); -console.log(totalXmasOccurrences);",node:14 -2024,4,1,"--- Day 4: Ceres Search --- +console.log(totalXmasOccurrences);",javascript +269,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! @@ -38572,8 +38572,8 @@ rows.forEach((row, rowIndex) => { } }); -console.log(runningTotal);",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +console.log(runningTotal);",javascript +270,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! @@ -38689,8 +38689,8 @@ data.forEach((_, vertIdx) => { } }); }); -console.log(count);",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +console.log(count);",javascript +271,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! @@ -38839,8 +38839,8 @@ for (let i = 0; i < rows.length; i++) { } } -console.log({ found_xmass });",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +console.log({ found_xmass });",javascript +272,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! @@ -38969,8 +38969,8 @@ function main() { console.log(totalPatterns); } -main(); // Run the main function",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +main(); // Run the main function",javascript +273,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! @@ -39069,8 +39069,8 @@ rows.forEach((row, rowIndex) => { } }); -console.log(runningTotal);",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +console.log(runningTotal);",javascript +274,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! @@ -39190,8 +39190,8 @@ if ( } } - console.log(`Number of X-MAS patterns found: ${count}`);",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- + console.log(`Number of X-MAS patterns found: ${count}`);",javascript +275,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. @@ -39349,8 +39349,8 @@ while (guardRunning) { } } -console.log(visited.size); // The number of distinct positions visited",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- +console.log(visited.size); // The number of distinct positions visited",javascript +276,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. @@ -39550,8 +39550,8 @@ const part2 = (rows, guardLocation) => { rows[obstacleX][obstacleY] = "".""; } return infiniteLoops; -}",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- +}",javascript +277,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. @@ -39721,8 +39721,8 @@ const map = input.split('\n'); // Simulate the guard's movement and print the result const distinctPositions = simulateGuardMovement(map); -console.log(`Number of distinct positions visited: ${distinctPositions}`);",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- +console.log(`Number of distinct positions visited: ${distinctPositions}`);",javascript +278,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. @@ -39913,8 +39913,8 @@ const map = input.split('\n'); // Simulate the guard's movement and print the result const distinctPositions = simulateGuardMovement(map); -console.log(`Number of distinct positions visited: ${distinctPositions}`);",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- +console.log(`Number of distinct positions visited: ${distinctPositions}`);",javascript +279,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. @@ -40078,8 +40078,8 @@ while (true) { } // Output the number of distinct positions visited -console.log(visited.size);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +console.log(visited.size);",javascript +280,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. @@ -40369,8 +40369,8 @@ const map = input.split('\n'); // Count valid obstruction positions and print the result const validPositions = countValidObstructionPositions(map); -console.log(`Number of valid obstruction positions: ${validPositions}`);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +console.log(`Number of valid obstruction positions: ${validPositions}`);",javascript +281,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. @@ -40681,8 +40681,8 @@ class Solution { // Instantiate the solution class and solve the problem const solution = new Solution('input.txt'); -solution.solve();",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +solution.solve();",javascript +282,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. @@ -40946,8 +40946,8 @@ for (let k of visited) { } } } -console.log(blocks.size);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +console.log(blocks.size);",javascript +283,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. @@ -41234,8 +41234,8 @@ for (let i = 0; i < numRows; i++) { } // Output the total count -console.log(count);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +console.log(count);",javascript +284,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. @@ -41530,8 +41530,8 @@ const solve = (filePath) => { }; // Run the solution -solve('input.txt');",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +solve('input.txt');",javascript +285,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -41660,8 +41660,8 @@ for (const freq in antennas) { } } -console.log(antinodes.size);",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +console.log(antinodes.size);",javascript +286,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -41799,8 +41799,8 @@ function main() { console.log(antinodes.size); } -main();",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +main();",javascript +287,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -41933,8 +41933,8 @@ const calculateAntinodes = (grid) => { }; // Calculate and print the number of unique antinode locations -console.log(calculateAntinodes(grid));",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +console.log(calculateAntinodes(grid));",javascript +288,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -42078,8 +42078,8 @@ function solve(filePath) { } // Run the solution -solve('input.txt');",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +solve('input.txt');",javascript +289,2024,8,1,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -42214,8 +42214,8 @@ const main = () => { }; // Execute the main function -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +main();",javascript +290,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -42379,8 +42379,8 @@ const findAntinodes = (grid) => { return antinodeSet.size; }; -console.log(findAntinodes(grid));",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +console.log(findAntinodes(grid));",javascript +291,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -42566,8 +42566,8 @@ const main = () => { }; // Run the program -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +main();",javascript +292,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -42771,8 +42771,8 @@ const main = () => { }; // Run the program -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +main();",javascript +293,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -42960,8 +42960,8 @@ const main = () => { }; // Run the main function -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +main();",javascript +294,2024,8,2,"--- Day 8: Resonant Collinearity --- You find yourselves on the roof of a top-secret Easter Bunny installation. @@ -43143,8 +43143,8 @@ for (const freq in antennas) { } } -console.log(antinodes.size);",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +console.log(antinodes.size);",javascript +295,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. @@ -43262,8 +43262,8 @@ const main = () => { }; // Run the program -main();",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +main();",javascript +296,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. @@ -43396,8 +43396,8 @@ const calculateDiskChecksum = (filePath) => { // Output the resulting checksum const checksum = calculateDiskChecksum('input.txt'); -console.log(checksum);",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +console.log(checksum);",javascript +297,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. @@ -43523,8 +43523,8 @@ const processDisk = (filePath) => { // Run the function and print the resulting checksum const checksum = processDisk('input.txt'); -console.log(checksum);",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +console.log(checksum);",javascript +298,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. @@ -43628,8 +43628,8 @@ const main = () => { }; // Run the program -main();",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +main();",javascript +299,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. @@ -43739,8 +43739,8 @@ for (let i = 0; i < disk.length; i++) { } // Output the resulting checksum -console.log(checksum);",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +console.log(checksum);",javascript +300,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. @@ -43950,8 +43950,8 @@ function main() { } // Execute the program -main();",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +main();",javascript +301,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. @@ -44097,8 +44097,8 @@ const part2 = (data) => { } } return checkSum(rawData.flat()); -}",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +}",javascript +302,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. @@ -44360,8 +44360,8 @@ function main() { } // Execute the main function -main();",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +main();",javascript +303,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. @@ -44548,8 +44548,8 @@ const findMatchingFreeSpace = (rawData, currentIndex) => { }; // Execute the program -processFile(inputText);",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +processFile(inputText);",javascript +304,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. @@ -44715,8 +44715,8 @@ async function main() { } // Run the main function -main();",node:14 -2024,10,1,"--- Day 10: Hoof It --- +main();",javascript +305,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. @@ -44901,8 +44901,8 @@ try { } catch (error) { console.error('Failed to solve puzzle:', error); process.exit(1); -}",node:14 -2024,10,1,"--- Day 10: Hoof It --- +}",javascript +306,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. @@ -45040,8 +45040,8 @@ try { console.log(`Sum of trailhead scores: ${result}`); } catch (error) { console.error('Error:', error.message); -}",node:14 -2024,10,1,"--- Day 10: Hoof It --- +}",javascript +307,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. @@ -45184,8 +45184,8 @@ const main = () => { console.log(`Sum of trailhead scores: ${result}`); // Output the result }; -main();",node:14 -2024,10,1,"--- Day 10: Hoof It --- +main();",javascript +308,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. @@ -45303,8 +45303,8 @@ for (const [i, j] of trailheads) { totalScore += reachable9s.size; } -console.log(totalScore);",node:14 -2024,10,1,"--- Day 10: Hoof It --- +console.log(totalScore);",javascript +309,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. @@ -45456,8 +45456,8 @@ const main = () => { }; // Run the program -main();",node:14 -2024,10,2,"--- Day 10: Hoof It --- +main();",javascript +310,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. @@ -45642,8 +45642,8 @@ const getTotalValidTrails = (data, cumulative) => { totalValidTrails += validTrails; } return totalValidTrails; -}",node:14 -2024,10,2,"--- Day 10: Hoof It --- +}",javascript +311,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. @@ -45859,8 +45859,8 @@ try { } catch (error) { console.error('Error:', error); process.exit(1); -}",node:14 -2024,10,2,"--- Day 10: Hoof It --- +}",javascript +312,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. @@ -46076,8 +46076,8 @@ try { } catch (error) { console.error('Error:', error); process.exit(1); -}",node:14 -2024,10,2,"--- Day 10: Hoof It --- +}",javascript +313,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. @@ -46244,8 +46244,8 @@ let part2 = 0; for (let trailhead of trailheads) { part2 += getScore(trailhead, true); } -log(part2);",node:14 -2024,10,2,"--- Day 10: Hoof It --- +log(part2);",javascript +314,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. @@ -46419,8 +46419,8 @@ for (const [i, j] of trailheads) { totalRating += countTrails(i, j); } -console.log(totalRating);",node:14 -2024,11,1,"--- Day 11: Plutonian Pebbles --- +console.log(totalRating);",javascript +315,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. @@ -46535,8 +46535,8 @@ try { } catch (error) { console.error('Error:', error); process.exit(1); -}",node:14 -2024,11,1,"--- Day 11: Plutonian Pebbles --- +}",javascript +316,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. @@ -46613,8 +46613,8 @@ for (let i = 0; i < blinks; i++) { stones = newStones; } -console.log(stones.length);",node:14 -2024,11,1,"--- Day 11: Plutonian Pebbles --- +console.log(stones.length);",javascript +317,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. @@ -46718,8 +46718,8 @@ try { } catch (error) { console.error('Error:', error); process.exit(1); -}",node:14 -2024,11,1,"--- Day 11: Plutonian Pebbles --- +}",javascript +318,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. @@ -46804,8 +46804,8 @@ const main = () => { }; // Execute the program -main();",node:14 -2024,11,1,"--- Day 11: Plutonian Pebbles --- +main();",javascript +319,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. @@ -46890,8 +46890,8 @@ const main = () => { console.log(stones.length); }; -main();",node:14 -2024,11,2,"--- Day 11: Plutonian Pebbles --- +main();",javascript +320,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. @@ -47034,8 +47034,8 @@ const main = () => { }; // Execute the main function -main();",node:14 -2024,11,2,"--- Day 11: Plutonian Pebbles --- +main();",javascript +321,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. @@ -47178,8 +47178,8 @@ function main() { } // Execute the solution -main();",node:14 -2024,11,2,"--- Day 11: Plutonian Pebbles --- +main();",javascript +322,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. @@ -47318,8 +47318,8 @@ const main = () => { }; // Run the program -main();",node:14 -2024,11,2,"--- Day 11: Plutonian Pebbles --- +main();",javascript +323,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. @@ -47453,8 +47453,8 @@ function main() { } // Run the program -main();",node:14 -2024,11,2,"--- Day 11: Plutonian Pebbles --- +main();",javascript +324,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. @@ -47551,8 +47551,8 @@ for (let i = 0; i < blinks; i++) { let totalStones = Object.values(stoneCounts).reduce((a, b) => a + b, 0n); -console.log(totalStones.toString());",node:14 -2024,12,1,"--- Day 12: Garden Groups --- +console.log(totalStones.toString());",javascript +325,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. @@ -47689,8 +47689,8 @@ function main() { console.log(totalPrice); } -main();",node:14 -2024,12,1,"--- Day 12: Garden Groups --- +main();",javascript +326,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. @@ -47845,8 +47845,8 @@ const main = () => { console.log(totalCost); }; -main();",node:14 -2024,12,1,"--- Day 12: Garden Groups --- +main();",javascript +327,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. @@ -47996,8 +47996,8 @@ function main() { console.log(totalCost); } -main();",node:14 -2024,12,1,"--- Day 12: Garden Groups --- +main();",javascript +328,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. @@ -48147,8 +48147,8 @@ function main() { console.log(totalCost); } -main();",node:14 -2024,12,1,"--- Day 12: Garden Groups --- +main();",javascript +329,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. @@ -48294,8 +48294,8 @@ function main() { console.log(totalPrice); } -main();",node:14 -2024,12,2,"--- Day 12: Garden Groups --- +main();",javascript +330,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. @@ -48636,8 +48636,8 @@ function findNumberOfSidesThisList(list) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 17ms",node:14 -2024,12,2,"--- Day 12: Garden Groups --- +console.timeEnd(""execution time"") // 17ms",javascript +331,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. @@ -48851,8 +48851,8 @@ for (let yi = 0; yi < ymax; yi++) { } } -console.log(totalCost);",node:14 -2024,12,2,"--- Day 12: Garden Groups --- +console.log(totalCost);",javascript +332,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. @@ -49132,8 +49132,8 @@ for (const region of regions) { totalPrice += price; } -console.log(totalPrice);",node:14 -2024,12,2,"--- Day 12: Garden Groups --- +console.log(totalPrice);",javascript +333,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. @@ -49348,8 +49348,8 @@ for (let yi = 0; yi < ymax; yi++) { } } -console.log(total);",node:14 -2024,12,2,"--- Day 12: Garden Groups --- +console.log(total);",javascript +334,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. @@ -49563,8 +49563,8 @@ for (let yi = 0; yi < ymax; yi++) { } } -console.log(total);",node:14 -2024,13,1,"--- Day 13: Claw Contraption --- +console.log(total);",javascript +335,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. @@ -49642,8 +49642,8 @@ input.forEach(machine => { } }); -console.log(totalTokens);",node:14 -2024,13,1,"--- Day 13: Claw Contraption --- +console.log(totalTokens);",javascript +336,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. @@ -49741,8 +49741,8 @@ function calculateTotalMinTokens(filePath) { } const total = calculateTotalMinTokens('input.txt'); -console.log(`Minimum total tokens required: ${total}`);",node:14 -2024,13,1,"--- Day 13: Claw Contraption --- +console.log(`Minimum total tokens required: ${total}`);",javascript +337,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. @@ -49843,8 +49843,8 @@ const calculateTotalTokens = (filePath) => { }; const totalTokens = calculateTotalTokens('input.txt'); -console.log(`Total minimum tokens required: ${totalTokens}`);",node:14 -2024,13,1,"--- Day 13: Claw Contraption --- +console.log(`Total minimum tokens required: ${totalTokens}`);",javascript +338,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. @@ -49931,8 +49931,8 @@ function main() { console.log(totalTokens); } -main();",node:14 -2024,13,1,"--- Day 13: Claw Contraption --- +main();",javascript +339,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. @@ -50004,8 +50004,8 @@ function calculateMinimumTokens(machines) { const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); const result = calculateMinimumTokens(input); -console.log(result);",node:14 -2024,13,2,"--- Day 13: Claw Contraption --- +console.log(result);",javascript +340,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. @@ -50138,8 +50138,8 @@ function calculateTotalMinTokens(filePath) { } const total = calculateTotalMinTokens('input.txt'); -console.log(`Minimum total tokens required: ${total}`);",node:14 -2024,13,2,"--- Day 13: Claw Contraption --- +console.log(`Minimum total tokens required: ${total}`);",javascript +341,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. @@ -50261,8 +50261,8 @@ const input = fs.readFileSync('input.txt', 'utf8').trim(); console.log(""Part One:"", solveClawMachines(input)); // Part Two -console.log(""Part Two:"", solveClawMachines(input, true));",node:14 -2024,13,2,"--- Day 13: Claw Contraption --- +console.log(""Part Two:"", solveClawMachines(input, true));",javascript +342,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. @@ -50422,8 +50422,8 @@ const main = () => { }; // Run the program -main();",node:14 -2024,13,2,"--- Day 13: Claw Contraption --- +main();",javascript +343,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. @@ -50559,8 +50559,8 @@ machines.forEach(machine => { } }) -console.log(part2);",node:14 -2024,13,2,"--- Day 13: Claw Contraption --- +console.log(part2);",javascript +344,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. @@ -50711,8 +50711,8 @@ const part1 = calculatePart1(machines); const part2 = calculatePart2(machines); log(part1); -log(part2);",node:14 -2024,14,1,"--- Day 14: Restroom Redoubt --- +log(part2);",javascript +345,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. @@ -50874,8 +50874,8 @@ function countQuadrants(positions) { const positionsAfter100 = simulate(robots, 100); const quadrantCounts = countQuadrants(positionsAfter100); const safetyFactor = quadrantCounts.reduce((a, b) => a * b, 1); -console.log(`Safety Factor after 100 seconds: ${safetyFactor}`);",node:14 -2024,14,1,"--- Day 14: Restroom Redoubt --- +console.log(`Safety Factor after 100 seconds: ${safetyFactor}`);",javascript +346,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. @@ -51032,8 +51032,8 @@ for (const robot of robots) { const safetyFactor = q1 * q2 * q3 * q4; -console.log(safetyFactor);",node:14 -2024,14,1,"--- Day 14: Restroom Redoubt --- +console.log(safetyFactor);",javascript +347,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. @@ -51200,8 +51200,8 @@ function calculateSafetyFactor(input) { // Read input, process, and output the result const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); const safetyFactor = calculateSafetyFactor(input); -console.log(safetyFactor);",node:14 -2024,14,1,"--- Day 14: Restroom Redoubt --- +console.log(safetyFactor);",javascript +348,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. @@ -51355,8 +51355,8 @@ const robots = parseRobots(input); const quadrants = calculateQuadrants(robots); const safetyFactor = quadrants.q1 * quadrants.q2 * quadrants.q3 * quadrants.q4; -console.log(safetyFactor);",node:14 -2024,14,1,"--- Day 14: Restroom Redoubt --- +console.log(safetyFactor);",javascript +349,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. @@ -51519,8 +51519,8 @@ robots.forEach(robot => { // Calculate safety factor const safetyFactor = quadrants.Q1 * quadrants.Q2 * quadrants.Q3 * quadrants.Q4; -console.log('Safety Factor after 100 seconds:', safetyFactor);",node:14 -2024,14,2,"--- Day 14: Restroom Redoubt --- +console.log('Safety Factor after 100 seconds:', safetyFactor);",javascript +350,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. @@ -51683,8 +51683,8 @@ for (let i = 0; i < 100000; i++) { console.log(matrix.map(x => x.join("""")).join(""\n"") + ""\n"") break; } -}",node:14 -2024,14,2,"--- Day 14: Restroom Redoubt --- +}",javascript +351,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. @@ -51876,8 +51876,8 @@ for (let i = 1; i < 100000; i++) { console.log(""Tree appears at second:"", i); break; } -}",node:14 -2024,14,2,"--- Day 14: Restroom Redoubt --- +}",javascript +352,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. @@ -52079,8 +52079,8 @@ for (let i = SECONDS; i < 19000; i++) { grid.forEach(row => console.log(row.join(''))); break; } -}",node:14 -2024,14,2,"--- Day 14: Restroom Redoubt --- +}",javascript +353,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. @@ -52292,8 +52292,8 @@ for (let i = SECONDS; i < 19000; i++) { console.log(arr[x].join('')); } } -}",node:14 -2024,14,2,"--- Day 14: Restroom Redoubt --- +}",javascript +354,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. @@ -52465,8 +52465,8 @@ for (let counter = 0; counter < 10000; counter++) { } initialPositions = newInitialPositions; -}",node:14 -2024,16,1,"--- Day 16: Reindeer Maze --- +}",javascript +355,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. @@ -52631,8 +52631,8 @@ fs.readFile(filePath, 'utf8', (err, data) => { const result = dijkstra(grid); console.log(result); -});",node:14 -2024,16,1,"--- Day 16: Reindeer Maze --- +});",javascript +356,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. @@ -52896,8 +52896,8 @@ while (pq.size() > 0) { // If no path is found, output a message console.log('No path found'); -console.log(""Score of Reindeer (shortest movement):"",cost);",node:14 -2024,16,1,"--- Day 16: Reindeer Maze --- +console.log(""Score of Reindeer (shortest movement):"",cost);",javascript +357,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. @@ -53056,8 +53056,8 @@ fs.readFile(filePath, 'utf8', (err, data) => { const maze = data.split('\n').map(line => line.trim().split('')); const lowestScore = getLowestScore(maze); console.log(""Lowest Score:"", lowestScore); -});",node:14 -2024,16,1,"--- Day 16: Reindeer Maze --- +});",javascript +358,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. @@ -53229,8 +53229,8 @@ const filePath = 'input.txt'; const parsedData = parseInput(filePath); const [i, j] = findStartingPosition(parsedData); const score = findLowestScore(parsedData, i, j, 'E'); -console.log(score);",node:14 -2024,16,1,"--- Day 16: Reindeer Maze --- +console.log(score);",javascript +359,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. @@ -53413,8 +53413,8 @@ fs.readFile(filePath, 'utf8', (err, data) => { const result = dijkstra(grid); console.log(result); -});",node:14 -2024,16,2,"--- Day 16: Reindeer Maze --- +});",javascript +360,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. @@ -53626,8 +53626,8 @@ fs.readFile('input.txt', 'utf8', (error, input) => { }); console.log(uniquePositions.size); -});",node:14 -2024,16,2,"--- Day 16: Reindeer Maze --- +});",javascript +361,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. @@ -53851,8 +53851,8 @@ fs.readFile('input.txt', 'utf8', (error, content) => { // Output the count of distinct visited positions console.log(visitedPositions.size); -});",node:14 -2024,16,2,"--- Day 16: Reindeer Maze --- +});",javascript +362,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. @@ -54064,8 +54064,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { }); console.log(seats.size); -});",node:14 -2024,16,2,"--- Day 16: Reindeer Maze --- +});",javascript +363,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. @@ -54277,8 +54277,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { }); console.log(seats.size); -});",node:14 -2024,16,2,"--- Day 16: Reindeer Maze --- +});",javascript +364,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. @@ -54500,8 +54500,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { const result = part2(data); console.log(result); -});",node:14 -2024,2,1,"--- Day 2: Red-Nosed Reports --- +});",javascript +365,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. @@ -54584,8 +54584,8 @@ const main = () => { }; // Execute the program -main();",node:14 -2024,2,1,"--- Day 2: Red-Nosed Reports --- +main();",javascript +366,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. @@ -54669,8 +54669,8 @@ puzzleInput.forEach((report) => { } }); -console.log(safeCount);",node:14 -2024,2,1,"--- Day 2: Red-Nosed Reports --- +console.log(safeCount);",javascript +367,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. @@ -54759,8 +54759,8 @@ const main = () => { }; // Execute the program -main();",node:14 -2024,2,1,"--- Day 2: Red-Nosed Reports --- +main();",javascript +368,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. @@ -54832,8 +54832,8 @@ fs.readFile('input.txt', 'utf-8', (err, data) => { const safeReports = analyzeReports(data); console.log('Number of safe reports:', safeReports); -});",node:14 -2024,2,1,"--- Day 2: Red-Nosed Reports --- +});",javascript +369,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. @@ -54916,8 +54916,8 @@ const safe_reports = rows.reduce((accumulator, row) => { return accumulator + (valid ? 1 : 0); }, 0); -console.log({ safe_reports });",node:14 -2024,2,2,"--- Day 2: Red-Nosed Reports --- +console.log({ safe_reports });",javascript +370,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. @@ -55030,8 +55030,8 @@ fs.readFile('input.txt', 'utf-8', (err, data) => { console.log('Part 1: Safe Reports:', safeReports); console.log('Part 2: Safe Reports with Dampener:', safeReportsWithDampener); -});",node:14 -2024,2,2,"--- Day 2: Red-Nosed Reports --- +});",javascript +371,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. @@ -55152,8 +55152,8 @@ puzzleInput.forEach((report) => { } }); -console.log(safeCount);",node:14 -2024,2,2,"--- Day 2: Red-Nosed Reports --- +console.log(safeCount);",javascript +372,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. @@ -55280,8 +55280,8 @@ function main() { } // Run the program -main();",node:14 -2024,2,2,"--- Day 2: Red-Nosed Reports --- +main();",javascript +373,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. @@ -55400,8 +55400,8 @@ const part2 = (data) => { } } return safeReports; -}",node:14 -2024,2,2,"--- Day 2: Red-Nosed Reports --- +}",javascript +374,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. @@ -55558,8 +55558,8 @@ puzzleInput.forEach(element => { } }); -console.log(`Part 2: ${safeAfterDampening} safe levels after dampening`)",node:14 -2024,5,1,"--- Day 5: Print Queue --- +console.log(`Part 2: ${safeAfterDampening} safe levels after dampening`)",javascript +375,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. @@ -55684,8 +55684,8 @@ const calculateMiddlePageSum = (rules, updates) => { const { rules, updates } = getRulesAndUpdates(puzzleInput); const result = calculateMiddlePageSum(rules, updates); -console.log(result);",node:14 -2024,5,1,"--- Day 5: Print Queue --- +console.log(result);",javascript +376,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. @@ -55791,8 +55791,8 @@ const middlePageNumbers = updates const result = middlePageNumbers.reduce((sum, number) => sum + parseInt(number), 0); // Output the result -console.log(result);",node:14 -2024,5,1,"--- Day 5: Print Queue --- +console.log(result);",javascript +377,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. @@ -55914,8 +55914,8 @@ const middlePageNumbers = updates const result = calculateTotal(middlePageNumbers); -console.log(result);",node:14 -2024,5,1,"--- Day 5: Print Queue --- +console.log(result);",javascript +378,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. @@ -56032,8 +56032,8 @@ middlePageNumbers.forEach((number) => { result += parseInt(number); }); -console.log(result);",node:14 -2024,5,1,"--- Day 5: Print Queue --- +console.log(result);",javascript +379,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. @@ -56172,8 +56172,8 @@ for (let i = 0; i < rows.length - 1; i++) { // console.table(rows); // console.dir(after_check_object, { depth: null }); -console.log({ valid_instructions });",node:14 -2024,5,2,"--- Day 5: Print Queue --- +console.log({ valid_instructions });",javascript +380,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. @@ -56361,8 +56361,8 @@ for (const update of updates) { } } -console.log(sum);",node:14 -2024,5,2,"--- Day 5: Print Queue --- +console.log(sum);",javascript +381,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. @@ -56499,8 +56499,8 @@ let result = 0; fixedUpdates.forEach((update) => result += parseInt(update[Math.floor(update.length / 2)])); -console.log(result);",node:14 -2024,5,2,"--- Day 5: Print Queue --- +console.log(result);",javascript +382,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. @@ -56665,8 +56665,8 @@ const part2 = (instructions, invalidUpdates) => { const reorderedUpdate = reorderUpdate(update, instructions); return reorderedMiddlePages + Number(reorderedUpdate[Math.floor(reorderedUpdate.length / 2)]); }, 0); -}",node:14 -2024,5,2,"--- Day 5: Print Queue --- +}",javascript +383,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. @@ -56841,8 +56841,8 @@ const calculateReorderedUpdatesSum = (instructions, invalidUpdates) => { const reorderedUpdate = reorderUpdate(update, instructions); return sum + Number(reorderedUpdate[Math.floor(reorderedUpdate.length / 2)]); }, 0); -};",node:14 -2024,5,2,"--- Day 5: Print Queue --- +};",javascript +384,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. @@ -57034,8 +57034,8 @@ const sum = updates.reduce((total, update) => { return total; }, 0); -console.log(sum);",node:14 -2024,7,1,"--- Day 7: Bridge Repair --- +console.log(sum);",javascript +385,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? @@ -57111,8 +57111,8 @@ for (const line of lines) { } } -console.log(totalCalibration);",node:14 -2024,7,1,"--- Day 7: Bridge Repair --- +console.log(totalCalibration);",javascript +386,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? @@ -57199,8 +57199,8 @@ const calculateTotalCalibration = (filePath) => { }; // Run the solution -console.log(`Total calibration result: ${calculateTotalCalibration('input.txt')}`);",node:14 -2024,7,1,"--- Day 7: Bridge Repair --- +console.log(`Total calibration result: ${calculateTotalCalibration('input.txt')}`);",javascript +387,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? @@ -57286,8 +57286,8 @@ const calculateTotalCalibration = (filePath) => { // Call the main function and print the result const result = calculateTotalCalibration('input.txt'); -console.log(result);",node:14 -2024,7,1,"--- Day 7: Bridge Repair --- +console.log(result);",javascript +388,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? @@ -57365,8 +57365,8 @@ const solveChallenge = (path) => { // Run the solution const result = solveChallenge('input.txt'); -console.log(result);",node:14 -2024,7,1,"--- Day 7: Bridge Repair --- +console.log(result);",javascript +389,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? @@ -57465,8 +57465,8 @@ const solve = (filePath) => { }; // Run the solution -solve('input.txt');",node:14 -2024,7,2,"--- Day 7: Bridge Repair --- +solve('input.txt');",javascript +390,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? @@ -57557,8 +57557,8 @@ let total = 0; for (const line of input) { total += solve(line); } -console.log(total);",node:14 -2024,7,2,"--- Day 7: Bridge Repair --- +console.log(total);",javascript +391,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? @@ -57676,8 +57676,8 @@ const calculateCalibrationResult = (filePath) => { // Output the total calibration result const calibrationResult = calculateCalibrationResult('input.txt'); -console.log(calibrationResult);",node:14 -2024,7,2,"--- Day 7: Bridge Repair --- +console.log(calibrationResult);",javascript +392,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? @@ -57771,8 +57771,8 @@ for (const line of lines) { } } -console.log(totalCalibration);",node:14 -2024,7,2,"--- Day 7: Bridge Repair --- +console.log(totalCalibration);",javascript +393,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? @@ -57883,8 +57883,8 @@ const calculateCalibrationResult = (lines) => { }; // Output the total calibration result -console.log(calculateCalibrationResult(lines));",node:14 -2024,7,2,"--- Day 7: Bridge Repair --- +console.log(calculateCalibrationResult(lines));",javascript +394,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? @@ -58012,8 +58012,8 @@ const calculateTotalCalibration = (filePath) => { // Execute the function and output the result const result = calculateTotalCalibration('input.txt'); -console.log(result);",node:14 -2024,15,1,"--- Day 15: Warehouse Woes --- +console.log(result);",javascript +395,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? @@ -58330,8 +58330,8 @@ warehouse.forEach((line, y) => { }); }); -console.log(`result=${result}`);",node:14 -2024,15,1,"--- Day 15: Warehouse Woes --- +console.log(`result=${result}`);",javascript +396,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? @@ -58647,8 +58647,8 @@ function main() { console.log(`The sum of all boxes' GPS coordinates is ${total}`); } -main();",node:14 -2024,15,1,"--- Day 15: Warehouse Woes --- +main();",javascript +397,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? @@ -58950,8 +58950,8 @@ for (let i = 0; i < warehouseMap.length; i++) { } } -console.log(`The sum of all boxes' GPS coordinates is ${total}`);",node:14 -2024,15,1,"--- Day 15: Warehouse Woes --- +console.log(`The sum of all boxes' GPS coordinates is ${total}`);",javascript +398,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? @@ -59250,8 +59250,8 @@ function main(grid, steps) { return result; } -console.log(`Result: ${main(grid, steps)}`);",node:14 -2024,15,1,"--- Day 15: Warehouse Woes --- +console.log(`Result: ${main(grid, steps)}`);",javascript +399,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? @@ -59569,8 +59569,8 @@ function main() { console.log(`result=${result}`); } -main();",node:14 -2024,15,2,"--- Day 15: Warehouse Woes --- +main();",javascript +400,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? @@ -60339,8 +60339,8 @@ function part2() { console.log(sum); } -part2();",node:14 -2024,15,2,"--- Day 15: Warehouse Woes --- +part2();",javascript +401,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? @@ -60897,8 +60897,8 @@ for (let i = 0; i < grid.length; i++) { } } -console.log(total);",node:14 -2024,15,2,"--- Day 15: Warehouse Woes --- +console.log(total);",javascript +402,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? @@ -61486,8 +61486,8 @@ Predict the motion of the robot and boxes in this new, scaled-up warehouse. What const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8'); const solver = new WarehouseSolver(); -console.log(solver.solve(input));",node:14 -2024,15,2,"--- Day 15: Warehouse Woes --- +console.log(solver.solve(input));",javascript +403,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? @@ -62063,8 +62063,8 @@ Predict the motion of the robot and boxes in this new, scaled-up warehouse. What // Usage const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8'); -console.log(WarehouseSolver.solve(input));",node:14 -2024,15,2,"--- Day 15: Warehouse Woes --- +console.log(WarehouseSolver.solve(input));",javascript +404,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? @@ -62659,8 +62659,8 @@ class WarehouseSolver { const fs = require('fs'); const solver = new WarehouseSolver(); const input = fs.readFileSync('input.txt', 'utf8'); -console.log(solver.solve(input));",node:14 -2024,17,1,"--- Day 17: Chronospatial Computer --- +console.log(solver.solve(input));",javascript +405,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. @@ -62819,8 +62819,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { } console.log(""Program output:"", output.join("","")); -});",node:14 -2024,17,1,"--- Day 17: Chronospatial Computer --- +});",javascript +406,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. @@ -62975,8 +62975,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { // Output the result console.log(output.join("","")); -});",node:14 -2024,17,1,"--- Day 17: Chronospatial Computer --- +});",javascript +407,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. @@ -63108,8 +63108,8 @@ const part1 = (data) => { performInstruction(opcode, operand); } return output.join("",""); -}",node:14 -2024,17,1,"--- Day 17: Chronospatial Computer --- +}",javascript +408,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. @@ -63266,8 +63266,8 @@ input.forEach(line => { // Execute program and display output const result = runProgram(registers, program); -console.log(result);",node:14 -2024,17,1,"--- Day 17: Chronospatial Computer --- +console.log(result);",javascript +409,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. @@ -63417,8 +63417,8 @@ function combo(operand) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 1ms",node:14 -2024,17,2,"--- Day 17: Chronospatial Computer --- +console.timeEnd(""execution time"") // 1ms",javascript +410,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. @@ -63572,8 +63572,8 @@ const main2 = () => { console.log(""Part2"", regA); }; -main2();",node:14 -2024,17,2,"--- Day 17: Chronospatial Computer --- +main2();",javascript +411,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. @@ -63750,8 +63750,8 @@ const main2 = () => { console.log(""part2"",regA); } -main2();",node:14 -2024,17,2,"--- Day 17: Chronospatial Computer --- +main2();",javascript +412,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. @@ -63927,8 +63927,8 @@ const main2 = () => { console.log(""Part2"", regA); }; -main2();",node:14 -2024,17,2,"--- Day 17: Chronospatial Computer --- +main2();",javascript +413,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. @@ -64164,8 +64164,8 @@ const parseInput = (fileContents) => { fs.readFile('input.txt', 'utf-8', (err, data) => { if (err) throw err; console.log(run(data.split('\n'))); -});",node:14 -2024,17,2,"--- Day 17: Chronospatial Computer --- +});",javascript +414,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. @@ -64380,8 +64380,8 @@ function runProgram(register) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 7ms",node:14 -2024,18,1,"--- Day 18: RAM Run --- +console.timeEnd(""execution time"") // 7ms",javascript +415,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! @@ -64500,8 +64500,8 @@ function bfs(startX, startY, endX, endY) { console.log('No path found'); } -bfs(0, 0, 70, 70);",node:14 -2024,18,1,"--- Day 18: RAM Run --- +bfs(0, 0, 70, 70);",javascript +416,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! @@ -64616,8 +64616,8 @@ const gridSize = 71; // For the actual problem, use 71; for the example, use 7 const grid = initializeGrid(gridSize); simulateFallingBytes(grid, bytePositions, 1024); const steps = findShortestPath(grid); -console.log(`Minimum number of steps needed to reach the exit: ${steps}`);",node:14 -2024,18,1,"--- Day 18: RAM Run --- +console.log(`Minimum number of steps needed to reach the exit: ${steps}`);",javascript +417,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! @@ -64805,8 +64805,8 @@ function showMap() { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 5ms",node:14 -2024,18,1,"--- Day 18: RAM Run --- +console.timeEnd(""execution time"") // 5ms",javascript +418,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! @@ -64907,8 +64907,8 @@ while (discovered.length > 0) { } } } -}",node:14 -2024,18,1,"--- Day 18: RAM Run --- +}",javascript +419,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! @@ -65014,8 +65014,8 @@ while (q.length > 0) { q.push([cost[`${i},${j}`] + 1 + h(ii, jj), ii, jj]); } } -}",node:14 -2024,18,2,"--- Day 18: RAM Run --- +}",javascript +420,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! @@ -65224,8 +65224,8 @@ while (true) { wallsEnd++; } -console.log('part 2', bytes[wallsEnd - 1]);",node:14 -2024,18,2,"--- Day 18: RAM Run --- +console.log('part 2', bytes[wallsEnd - 1]);",javascript +421,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! @@ -65368,8 +65368,8 @@ function P2() { } } -console.log(P2());",node:14 -2024,18,2,"--- Day 18: RAM Run --- +console.log(P2());",javascript +422,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! @@ -65519,8 +65519,8 @@ for (let i = 0; i < lines.length; i++) { console.log(`${x},${y}`); break; } -}",node:14 -2024,18,2,"--- Day 18: RAM Run --- +}",javascript +423,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! @@ -65763,8 +65763,8 @@ function showMap(walkRound) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 8ms",node:14 -2024,18,2,"--- Day 18: RAM Run --- +console.timeEnd(""execution time"") // 8ms",javascript +424,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! @@ -65907,8 +65907,8 @@ while (bytes_needed_lower < bytes_needed_upper) { } } -console.log(bytes_list[bytes_needed_lower - 1].join(','));",node:14 -2024,19,1,"--- Day 19: Linen Layout --- +console.log(bytes_list[bytes_needed_lower - 1].join(','));",javascript +425,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. @@ -66085,8 +66085,8 @@ function isComposable(target) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 18ms",node:14 -2024,19,1,"--- Day 19: Linen Layout --- +console.timeEnd(""execution time"") // 18ms",javascript +426,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. @@ -66154,8 +66154,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { }, 0); console.log(validPatternCount); -});",node:14 -2024,19,1,"--- Day 19: Linen Layout --- +});",javascript +427,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. @@ -66232,8 +66232,8 @@ fs.readFile('./day_19.in', 'utf8', (err, data) => { } console.log(ans); -});",node:14 -2024,19,1,"--- Day 19: Linen Layout --- +});",javascript +428,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. @@ -66410,8 +66410,8 @@ designs.forEach(design => { } }); -console.log(""Impossible Designs:"", impossibleDesigns);",node:14 -2024,19,1,"--- Day 19: Linen Layout --- +console.log(""Impossible Designs:"", impossibleDesigns);",javascript +429,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. @@ -66489,8 +66489,8 @@ for (let design of designs) { } } -console.log(count);",node:14 -2024,19,2,"--- Day 19: Linen Layout --- +console.log(count);",javascript +430,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. @@ -66595,8 +66595,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { console.log( patterns.reduce((sum, pattern) => sum + numPossiblePatterns(pattern, towels, new Map()), 0) ); -});",node:14 -2024,19,2,"--- Day 19: Linen Layout --- +});",javascript +431,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. @@ -66728,8 +66728,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { const totalPatterns = patterns.reduce((sum, pattern) => sum + patternPossible(pattern, towelsTrie), 0); console.log(totalPatterns); -});",node:14 -2024,19,2,"--- Day 19: Linen Layout --- +});",javascript +432,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. @@ -66851,8 +66851,8 @@ fs.readFile('day19-2.txt', 'utf8', (err, data) => { } console.log(""Number of ways to achieve patterns:"", getNumAchievablePatterns(towels, patterns)); -});",node:14 -2024,19,2,"--- Day 19: Linen Layout --- +});",javascript +433,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. @@ -67036,8 +67036,8 @@ function countWays(target) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 33ms",node:14 -2024,19,2,"--- Day 19: Linen Layout --- +console.timeEnd(""execution time"") // 33ms",javascript +434,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. @@ -67147,8 +67147,8 @@ for (let design of designs) { totalCount += countWays(design, towels); } -console.log(totalCount);",node:14 -2024,20,1,"--- Day 20: Race Condition --- +console.log(totalCount);",javascript +435,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! @@ -67438,8 +67438,8 @@ for (const step of Object.keys(cheats)) { }); } -console.log(solution);",node:14 -2024,20,1,"--- Day 20: Race Condition --- +console.log(solution);",javascript +436,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! @@ -67669,8 +67669,8 @@ for (const key in cheats) { } } -console.log(count);",node:14 -2024,20,1,"--- Day 20: Race Condition --- +console.log(count);",javascript +437,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! @@ -67979,8 +67979,8 @@ function orderByDistance(list) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 16ms",node:14 -2024,20,1,"--- Day 20: Race Condition --- +console.timeEnd(""execution time"") // 16ms",javascript +438,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! @@ -68199,8 +68199,8 @@ const runRaceSimulation = (filePath) => { }; // Run the simulation with the specified input file -runRaceSimulation('input.txt');",node:14 -2024,20,1,"--- Day 20: Race Condition --- +runRaceSimulation('input.txt');",javascript +439,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! @@ -68413,8 +68413,8 @@ sortedCounts.forEach(([l, count]) => { }); const result = shortcuts.filter(s => s >= 100).length; -console.log(result);",node:14 -2024,20,2,"--- Day 20: Race Condition --- +console.log(result);",javascript +440,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! @@ -68721,8 +68721,8 @@ const solve2 = (grid, minsave) => { // Parse the input grid and solve for both parts const grid = parseInput('./inputs/day20.txt'); solve1(grid, 100); -solve2(grid, 100);",node:14 -2024,20,2,"--- Day 20: Race Condition --- +solve2(grid, 100);",javascript +441,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! @@ -69061,8 +69061,8 @@ function findShortcut(baseCell) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 99ms",node:14 -2024,20,2,"--- Day 20: Race Condition --- +console.timeEnd(""execution time"") // 99ms",javascript +442,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! @@ -69329,8 +69329,8 @@ for (let i = 0; i < track.length - 2; i++) { } } } -console.log(part2.length);",node:14 -2024,20,2,"--- Day 20: Race Condition --- +console.log(part2.length);",javascript +443,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! @@ -69576,8 +69576,8 @@ fs.readFile('input.txt', 'utf8', (err, data) => { }, 0); console.log(result); -});",node:14 -2024,20,2,"--- Day 20: Race Condition --- +});",javascript +444,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! @@ -69841,8 +69841,8 @@ fs.readFile('input20.txt', 'utf8', (err, data) => { }; console.log(getCheats(20, 100)); -});",node:14 -2024,21,1,"--- Day 21: Keypad Conundrum --- +});",javascript +445,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. @@ -70107,8 +70107,8 @@ const olddirs = { '^^': 'A', '>>': 'A', 'AA': 'A' -};",node:14 -2024,21,1,"--- Day 21: Keypad Conundrum --- +};",javascript +446,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. @@ -70283,8 +70283,8 @@ for (let line of lines) { totalComplexity += parseInt(line.slice(0, -1)) * l3.length; } -console.log(totalComplexity);",node:14 -2024,21,1,"--- Day 21: Keypad Conundrum --- +console.log(totalComplexity);",javascript +447,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. @@ -70698,8 +70698,8 @@ function generateSequencesFromToken(sourceToken, roundsToGo) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 1ms",node:14 -2024,21,1,"--- Day 21: Keypad Conundrum --- +console.timeEnd(""execution time"") // 1ms",javascript +448,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. @@ -70873,9 +70873,8 @@ inputData.forEach((line) => { totalScore += parseInt(line.slice(0, -1)) * finalPath.length; }); -console.log(totalScore); -",node:14 -2024,21,1,"--- Day 21: Keypad Conundrum --- +console.log(totalScore);",javascript +449,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. @@ -71141,8 +71140,8 @@ function permutations(arr) { }; permute(arr); return result; -}",node:14 -2024,21,2,"--- Day 21: Keypad Conundrum --- +}",javascript +450,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. @@ -71429,8 +71428,8 @@ const olddirs = { '^^': 'A', '>>': 'A', 'AA': 'A' -};",node:14 -2024,21,2,"--- Day 21: Keypad Conundrum --- +};",javascript +451,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. @@ -71838,8 +71837,8 @@ function findLengthFromExpandedToken(sourceToken, roundsToGo) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 1ms",node:14 -2024,21,2,"--- Day 21: Keypad Conundrum --- +console.timeEnd(""execution time"") // 1ms",javascript +452,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. @@ -72038,8 +72037,8 @@ function findTotalComplexity(codes, levels) { return complexities.reduce((acc, val) => acc + val, 0); } -console.log(findTotalComplexity(input, 25));",node:14 -2024,21,2,"--- Day 21: Keypad Conundrum --- +console.log(findTotalComplexity(input, 25));",javascript +453,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. @@ -72237,8 +72236,8 @@ function calculateTotalEffort(sequences, depth) { return efforts.reduce((total, effort) => total + effort, 0); } -console.log(calculateTotalEffort(rawInput, 25));",node:14 -2024,21,2,"--- Day 21: Keypad Conundrum --- +console.log(calculateTotalEffort(rawInput, 25));",javascript +454,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. @@ -72525,8 +72524,8 @@ const olddirs = { '^^': 'A', '>>': 'A', 'AA': 'A' -};",node:14 -2024,22,1,"--- Day 22: Monkey Market --- +};",javascript +455,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. @@ -72621,8 +72620,8 @@ function main() { console.log(result); } -main();",node:14 -2024,22,1,"--- Day 22: Monkey Market --- +main();",javascript +456,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. @@ -72702,8 +72701,8 @@ for (const secretArray of secrets) { } // Output the result -console.log(totalSum);",node:14 -2024,22,1,"--- Day 22: Monkey Market --- +console.log(totalSum);",javascript +457,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. @@ -72773,8 +72772,8 @@ const secrets = ns.map((num) => Array.from(hsh(num))); // Part 1 const total = secrets.reduce((sum, secret) => sum + secret[secret.length - 1], 0); -console.log(total);",node:14 -2024,22,1,"--- Day 22: Monkey Market --- +console.log(total);",javascript +458,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. @@ -72891,8 +72890,8 @@ function processSecretNumberOnce(secret) { // expecting BigInt console.time(""execution time"") main() -console.timeEnd(""execution time"") // 55ms",node:14 -2024,22,1,"--- Day 22: Monkey Market --- +console.timeEnd(""execution time"") // 55ms",javascript +459,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. @@ -72976,8 +72975,8 @@ function get2000thSecret(start) { } const result = data.reduce((sum, val) => sum + get2000thSecret(val), 0); -console.log(result);",node:14 -2024,22,2,"--- Day 22: Monkey Market --- +console.log(result);",javascript +460,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. @@ -73129,8 +73128,8 @@ function calculate() { console.log(max); } -calculate();",node:14 -2024,22,2,"--- Day 22: Monkey Market --- +calculate();",javascript +461,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. @@ -73291,8 +73290,8 @@ function findMaxBananas() { console.log(maxSum); // Output the result } -findMaxBananas();",node:14 -2024,22,2,"--- Day 22: Monkey Market --- +findMaxBananas();",javascript +462,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. @@ -73469,8 +73468,8 @@ for (let a = -9; a <= 9; a++) { } } -console.log(bestSum);// solution for https://adventofcode.com/2024/day/22 part 2",node:14 -2024,22,2,"--- Day 22: Monkey Market --- +console.log(bestSum);// solution for https://adventofcode.com/2024/day/22 part 2",javascript +463,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. @@ -73637,8 +73636,8 @@ function main() { console.log(result); } -main();",node:14 -2024,22,2,"--- Day 22: Monkey Market --- +main();",javascript +464,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. @@ -73873,8 +73872,8 @@ function processSecretNumberOnce(secret) { // expecting BigInt console.time(""execution time"") main() -console.timeEnd(""execution time"") // 340ms",node:14 -2024,23,1,"--- Day 23: LAN Party --- +console.timeEnd(""execution time"") // 340ms",javascript +465,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). @@ -73977,8 +73976,8 @@ function main() { console.log(ans); } -main();",node:14 -2024,23,1,"--- Day 23: LAN Party --- +main();",javascript +466,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). @@ -74098,8 +74097,8 @@ function main() { part1(mapping); } -main();",node:14 -2024,23,1,"--- Day 23: LAN Party --- +main();",javascript +467,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). @@ -74197,8 +74196,8 @@ const triosWithT = [...trios].filter(trio => { return trioArray.some(v => v.startsWith('t')); }); -console.log(triosWithT.length);",node:14 -2024,23,1,"--- Day 23: LAN Party --- +console.log(triosWithT.length);",javascript +468,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). @@ -74350,8 +74349,8 @@ function fillTargetsFor(computer) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 9ms",node:14 -2024,23,1,"--- Day 23: LAN Party --- +console.timeEnd(""execution time"") // 9ms",javascript +469,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). @@ -74467,8 +74466,8 @@ function solve(input) { } const input = fs.readFileSync('input.txt', 'utf8').trim(); -console.log(solve(input));",node:14 -2024,23,2,"--- Day 23: LAN Party --- +console.log(solve(input));",javascript +470,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). @@ -74635,8 +74634,8 @@ function part2() { } // Run Part 2 -part2();",node:14 -2024,23,2,"--- Day 23: LAN Party --- +part2();",javascript +471,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). @@ -74791,8 +74790,8 @@ function solve(input) { } const input = fs.readFileSync('input.txt', 'utf8').trim(); -console.log(solve(input));",node:14 -2024,23,2,"--- Day 23: LAN Party --- +console.log(solve(input));",javascript +472,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). @@ -75043,8 +75042,8 @@ function allMembersAreFriends(network) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 5ms",node:14 -2024,23,2,"--- Day 23: LAN Party --- +console.timeEnd(""execution time"") // 5ms",javascript +473,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). @@ -75184,8 +75183,8 @@ function intersection(set1, set2) { const allPersons = Object.keys(connections); bronKerbosch(new Set(), new Set(allPersons), new Set()); -console.log(Array.from(maxClique).sort().join("",""));",node:14 -2024,23,2,"--- Day 23: LAN Party --- +console.log(Array.from(maxClique).sort().join("",""));",javascript +474,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). @@ -75339,8 +75338,8 @@ Object.keys(connections).forEach(node => { const maxClique = cliques.reduce((max, clique) => (clique.size > max.size ? clique : max), new Set()); // Print the largest clique sorted -console.log(Array.from(maxClique).sort().join("",""));",node:14 -2024,24,1,"--- Day 24: Crossed Wires --- +console.log(Array.from(maxClique).sort().join("",""));",javascript +475,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. @@ -75559,8 +75558,8 @@ function main() { } // Run the main function -main();",node:14 -2024,24,1,"--- Day 24: Crossed Wires --- +main();",javascript +476,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. @@ -75743,8 +75742,8 @@ let yDec = parseInt(yDigits.join(''), 2); let zDec = parseInt(zDigits.join(''), 2); let partOne = zDec; -console.log(""Part One:"", partOne);",node:14 -2024,24,1,"--- Day 24: Crossed Wires --- +console.log(""Part One:"", partOne);",javascript +477,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. @@ -76003,8 +76002,8 @@ function calcResult() { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 2ms",node:14 -2024,24,1,"--- Day 24: Crossed Wires --- +console.timeEnd(""execution time"") // 2ms",javascript +478,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. @@ -76185,8 +76184,8 @@ const zWires = Object.keys(wires) let zBits = zWires.reverse().map(z => wires[z].wireVal).join(''); -console.log('Decimal number output on the wires starting with ""z"":', parseInt(zBits, 2));",node:14 -2024,24,1,"--- Day 24: Crossed Wires --- +console.log('Decimal number output on the wires starting with ""z"":', parseInt(zBits, 2));",javascript +479,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. @@ -76385,8 +76384,8 @@ sortedOutput.forEach(([key, val]) => { power += 1; }); -console.log(dec);",node:14 -2024,24,2,"--- Day 24: Crossed Wires --- +console.log(dec);",javascript +480,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. @@ -76667,8 +76666,8 @@ function findSwappedWires(wireValues, gates) { } const { wireValues, gates } = parseInput('input.txt'); -console.log(findSwappedWires(wireValues, gates).join(','));",node:14 -2024,24,2,"--- Day 24: Crossed Wires --- +console.log(findSwappedWires(wireValues, gates).join(','));",javascript +481,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. @@ -77062,8 +77061,8 @@ export default function day24() { console.time() console.log(day24()); -console.timeEnd()",node:14 -2024,24,2,"--- Day 24: Crossed Wires --- +console.timeEnd()",javascript +482,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. @@ -77361,8 +77360,8 @@ for (let i = 0; i < numInputBits; i++) { carries.push(carryOutput); } -console.log([...Object.keys(swaps)].sort().join(','));",node:14 -2024,24,2,"--- Day 24: Crossed Wires --- +console.log([...Object.keys(swaps)].sort().join(','));",javascript +483,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. @@ -77775,8 +77774,8 @@ function showGate(gate) { console.time(""execution time"") main() -console.timeEnd(""execution time"") // 2ms",node:14 -2024,24,2,"--- Day 24: Crossed Wires --- +console.timeEnd(""execution time"") // 2ms",javascript +484,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. @@ -78072,8 +78071,8 @@ function parseInput(fileName) { const [wireValues, gates] = parseInput('input.txt'); const swappedWires = findSwappedWires(wireValues, gates); const result = swappedWires.join(','); -console.log(result);",node:14 -2024,25,1,"--- Day 25: Code Chronicle --- +console.log(result);",javascript +485,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. @@ -78216,8 +78215,8 @@ for (const lock of locks){ if (lock.every((l,i)=>l+key[i]<=5)) count++; } } -console.log(count);",node:14 -2024,25,1,"--- Day 25: Code Chronicle --- +console.log(count);",javascript +486,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. @@ -78370,8 +78369,8 @@ const part1 = (lockKeyData) => { return pairs; } -// const part2 = (data) => {}",node:14 -2024,25,1,"--- Day 25: Code Chronicle --- +// const part2 = (data) => {}",javascript +487,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. @@ -78538,8 +78537,8 @@ locks.forEach(lock => { }); }); -console.log(ans);",node:14 -2024,25,1,"--- Day 25: Code Chronicle --- +console.log(ans);",javascript +488,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. @@ -78684,8 +78683,8 @@ locks.forEach(lockStr => { }); }); -console.log(""Part One:"", partOne);",node:14 -2024,25,1,"--- Day 25: Code Chronicle --- +console.log(""Part One:"", partOne);",javascript +489,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. @@ -78820,4 +78819,41882 @@ locks.forEach(lock => { }); }); -console.log(""Day 25 part 1, sum ="", sum);",node:14 \ No newline at end of file +console.log(""Day 25 part 1, sum ="", sum);",javascript +490,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"def find_min_diff(a, b) + sorted_a = a.sort + sorted_b = b.sort + sorted_a.zip(sorted_b).sum { |x, y| (x - y).abs } +end + +def read_input_file(file_name) + a = [] + b = [] + File.foreach(file_name) do |line| + values = line.strip.split + if values.length == 2 + a << values[0].to_i + b << values[1].to_i + end + end + [a, b] +end + +def main + a, b = read_input_file(""input.txt"") + puts find_min_diff(a, b) +end + +main",ruby +491,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"file = File.readlines(""input.txt"") + +list_a = [] +list_b = [] + +file.each do |line| + components = line.split("" "") + list_a << components[0].strip.to_i + list_b << components[1].strip.to_i +end + +list_a.sort! +list_b.sort! + +diff = list_a.zip(list_b).sum { |a, b| (a - b).abs } +puts diff",ruby +492,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"def parse_input + left = [] + right = [] + + File.readlines(""input.txt"").each do |line| + split = line.split("" "") + left << split[0].to_i + right << split[1].to_i + end + + [left, right] +end + +def sort(arr) + (0...arr.length).each do |i| + (i...arr.length).each do |j| + arr[i], arr[j] = arr[j], arr[i] if arr[j] < arr[i] + end + end + arr +end + +if __FILE__ == $0 + left, right = parse_input + left = sort(left) + right = sort(right) + + sum_dist = left.zip(right).sum { |l, r| (l - r).abs } + puts sum_dist +end",ruby +493,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"raw = File.readlines(""input.txt"") + +l = raw.map { |x| x.split[0].to_i }.sort +r = raw.map { |x| x.split[1].to_i }.sort + +puts l.each_with_index.sum { |x, i| (x - r[i]).abs }",ruby +494,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +orig_pairs = input.map { |line| line.gsub(/\s+/, ' ').split(' ').map(&:to_i) } + +left_list = orig_pairs.map(&:first).sort +right_list = orig_pairs.map(&:last).sort + +sorted_pairs = left_list.zip(right_list) + +distance = sorted_pairs.map { |left, right| (right - left).abs }.sum + +puts ""Answer: #{distance}"" +",ruby +495,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists? + +Your puzzle answer was 2378066. + +--- Part Two --- + +Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. + +Or are they? + +The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. + +This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. + +Here are the same example lists again: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +For these example lists, here is the process of finding the similarity score: + +The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. +The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. +The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). +The fourth number, 1, also does not appear in the right list. +The fifth number, 3, appears in the right list three times; the similarity score increases by 9. +The last number, 3, appears in the right list three times; the similarity score again increases by 9. +So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). + +Once again consider your left and right lists. What is their similarity score?",18934359,"require 'csv' +require 'set' + +list1 = [] +list2 = [] + +File.foreach('input.txt') do |line| + split_line = line.strip.split(/\s+/) + list1 << split_line[0].to_i + list2 << split_line[1].to_i +end + +list2_count = list2.tally + +similarity_score = 0 +list1.each do |num| + similarity_score += num * list2_count.fetch(num, 0) +end + +puts similarity_score",ruby +496,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists? + +Your puzzle answer was 2378066. + +--- Part Two --- + +Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. + +Or are they? + +The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. + +This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. + +Here are the same example lists again: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +For these example lists, here is the process of finding the similarity score: + +The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. +The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. +The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). +The fourth number, 1, also does not appear in the right list. +The fifth number, 3, appears in the right list three times; the similarity score increases by 9. +The last number, 3, appears in the right list three times; the similarity score again increases by 9. +So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). + +Once again consider your left and right lists. What is their similarity score?",18934359,"left_nums = [] +right_nums = [] + +File.foreach('input.txt') do |line| + left, right = line.strip.split + left_nums << left.to_i + right_nums << right.to_i +end + +total = 0 +left_nums.each do |num| + total += num * right_nums.count(num) +end + +puts ""total: #{total}""",ruby +497,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists? + +Your puzzle answer was 2378066. + +--- Part Two --- + +Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. + +Or are they? + +The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. + +This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. + +Here are the same example lists again: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +For these example lists, here is the process of finding the similarity score: + +The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. +The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. +The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). +The fourth number, 1, also does not appear in the right list. +The fifth number, 3, appears in the right list three times; the similarity score increases by 9. +The last number, 3, appears in the right list three times; the similarity score again increases by 9. +So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). + +Once again consider your left and right lists. What is their similarity score?",18934359,"require 'csv' + +ans = 0 +a = [] +b = [] + +File.foreach(""input.txt"") do |line| + nums = line.strip.split("" "").map(&:to_i) + a << nums[0] + b << nums[1] +end + +counts = Hash.new(0) +b.each { |x| counts[x] += 1 } + +a.each { |x| ans += x * counts[x] } + +puts ans",ruby +498,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists? + +Your puzzle answer was 2378066. + +--- Part Two --- + +Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. + +Or are they? + +The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. + +This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. + +Here are the same example lists again: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +For these example lists, here is the process of finding the similarity score: + +The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. +The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. +The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). +The fourth number, 1, also does not appear in the right list. +The fifth number, 3, appears in the right list three times; the similarity score increases by 9. +The last number, 3, appears in the right list three times; the similarity score again increases by 9. +So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). + +Once again consider your left and right lists. What is their similarity score?",18934359,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +orig_pairs = input.map { |line| line.gsub(/\s+/, ' ').split(' ').map(&:to_i) } + +left_list = orig_pairs.map(&:first).sort +right_list = orig_pairs.map(&:last).sort + +score = 0 + +left_list.each do |left_number| + count = right_list.select { |right_number| right_number == left_number }.size + score += (left_number * count) +end + +puts ""Answer: #{score}""",ruby +499,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. + +As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. + +Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! + +You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. + +Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? + +Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. + +There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? + +For example: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + +Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. + +In the example list above, the pairs and distances would be as follows: + +The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. +The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. +The third-smallest number in both lists is 3, so the distance between them is 0. +The next numbers to pair up are 3 and 4, a distance of 1. +The fifth-smallest numbers in each list are 3 and 5, a distance of 2. +Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. +To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + +Your actual left and right lists contain many location IDs. What is the total distance between your lists? + +Your puzzle answer was 2378066. + +--- Part Two --- + +Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. + +Or are they? + +The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. + +This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. + +Here are the same example lists again: + +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +For these example lists, here is the process of finding the similarity score: + +The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. +The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. +The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). +The fourth number, 1, also does not appear in the right list. +The fifth number, 3, appears in the right list three times; the similarity score increases by 9. +The last number, 3, appears in the right list three times; the similarity score again increases by 9. +So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). + +Once again consider your left and right lists. What is their similarity score?",18934359,"def calculate_similarity_score(left, right) + score = 0 + right_counts = right.tally + left.each { |left_element| score += left_element * right_counts.fetch(left_element, 0) } + score +end + +def build_lists(contents) + left = [] + right = [] + + contents.each_line do |line| + next if line.strip.empty? + + le, re = line.split + left << le.to_i + right << re.to_i + end + + [left, right] +end + +if __FILE__ == $0 + contents = File.read(""input.txt"") + left, right = build_lists(contents) + score = calculate_similarity_score(left, right) + puts score +end",ruby +500,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe?",341,"def solve(input) + lines = File.readlines(input).map(&:strip) + l_list = lines.map { |line| line.split(' ').map(&:to_i) } + counter = 0 + + l_list.each do |l| + puts ""Evaluating #{l}"" + skip = false + + # Decreasing + if l[0] > l[1] + (0...(l.length - 1)).each do |i| + if l[i] - l[i + 1] > 3 || l[i] < l[i + 1] || l[i] == l[i + 1] + skip = true + break + end + end + # Increasing + elsif l[0] < l[1] + (0...(l.length - 1)).each do |i| + if l[i + 1] - l[i] > 3 || l[i] > l[i + 1] || l[i] == l[i + 1] + skip = true + break + end + end + else + next + end + + next if skip + puts ""Safe"" + counter += 1 + end + + puts counter +end + +input_path = ARGV[0] || ""input.txt"" +solve(input_path)",ruby +501,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe?",341,"def solve(input) + lines = File.readlines(input).map(&:strip) + l_list = lines.map { |line| line.split(' ').map(&:to_i) } + counter = 0 + + l_list.each do |l| + inc_dec = (l == l.sort || l == l.sort.reverse) + size_ok = true + + (0...(l.length - 1)).each do |i| + if !(0 < (l[i] - l[i + 1]).abs && (l[i] - l[i + 1]).abs <= 3) + size_ok = false + break + end + end + + if inc_dec && size_ok + counter += 1 + end + end + + puts counter +end + +input_path = ARGV[0] || ""input.txt"" +solve(input_path)",ruby +502,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe?",341,"def parse_input + input = [] + + File.readlines('input.txt').each do |line| + tmp = line.strip.split(' ') + input << tmp.map(&:to_i) + end + + input +end + +if __FILE__ == $0 + input = parse_input + + safe = 0 + input.each do |item| + tmp_safe = true + increasing = item[1] >= item[0] + + (0...(item.length - 1)).each do |i| + diff = item[i + 1] - item[i] + + if increasing && diff <= 0 + tmp_safe = false + break + end + + if !increasing && diff >= 0 + tmp_safe = false + break + end + + if diff.abs > 3 + tmp_safe = false + break + end + end + + safe += 1 if tmp_safe + end + + puts safe +end",ruby +503,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe?",341,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +# Each line of input is a report +class Report + attr_accessor :levels + + def initialize(line) + @levels = line.strip.split(' ').map(&:to_i) + end + + def increasing? + levels.each_cons(2).all? { |a, b| a < b } + end + + def decreasing? + levels.each_cons(2).all? { |a, b| a > b } + end + + def safe? + return false unless increasing? || decreasing? + + levels.each_cons(2).all? { |a, b| (a - b).abs.between?(1, 3) } + end +end + +safe_reports = input.select { |line| Report.new(line).safe? } + +puts ""Answer: #{safe_reports.count}""",ruby +504,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe?",341,"def is_safe(report) + increasing = report[0] < report[1] + decreasing = report[1] < report[0] + unless increasing or decreasing + return false + end + for i in 0..report.count-2 do + if increasing + unless report[i] < report[i+1] and report[i + 1] - report[i] < 4 + #puts(""nahh this is broken, at index "" + i.to_s) + #puts(report[i]) + #puts(report[i+1]) + #puts(""------"") + #puts(report) + #puts(""-----"") + return false + end + else + unless report[i] > report[i+1] and report[i] - report[i+1] < 4 + return false + end + end + end + return true +end + +def test_safety_with_removal(report) + #plan: test to just remove each element ad run it again... + # + for i in 0..report.count-1 do + with_removed = report.dup + with_removed.delete_at(i) + if is_safe(with_removed) + return true + end + end + return false +end + +file = File.open(""input.txt"") +file_data = file.readlines.map(&:chomp) + +reports = [] +right_occurrences = Hash.new(0) +file_data.each do |line| + splitted = line.split.map{|r| r.to_i} + reports << splitted +end + +safe_reports = 0; +is_part_two = false +reports.each do |report| + if is_safe(report) + safe_reports += 1 + elsif is_part_two and test_safety_with_removal(report) + safe_reports += 1 + end + +end +puts(""part one:"") +puts(""safe reports: "" + safe_reports.to_s)",ruby +505,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe? + +Your puzzle answer was 341. + +--- Part Two --- + +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. + +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! + +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. + +More of the above example's reports are now safe: + +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! + +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"input = open('./input.txt').readlines + +input.map!(&:strip) + +puts input.inspect + +total_safe = 0 +input.each do | report | + safe_reports = 0 + report = report.split("" "").map(&:to_i) + (report.length).times do | zap | + sreport = report.dup.tap{|i| i.delete_at(zap)} + safe = true + increase = false + decrease = false + (sreport.length - 1).times do | index | + decrease = true if sreport[index] > sreport[index + 1] + increase = true if sreport[index] < sreport[index + 1] + if (sreport[index] - sreport[index + 1]).abs > 3 or sreport[index] == sreport[index + 1] + safe = false + end + end + safe_reports += 1 if safe and increase != decrease + end + total_safe += 1 if safe_reports > 0 +end + +puts total_safe +# 244 too high +# 271 too low for part 2",ruby +506,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe? + +Your puzzle answer was 341. + +--- Part Two --- + +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. + +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! + +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. + +More of the above example's reports are now safe: + +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! + +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +# Each line of input is a report +class Report + attr_accessor :levels + + def initialize(line) + @levels = line.strip.split(' ').map(&:to_i) + end + + def safe? + return true if all_safe?(levels) + + levels.each_index do |i| + level_set = levels.clone + level_set.delete_at(i) + return true if all_safe?(level_set) + end + + false + end + + private + + def all_increasing?(level_set) + level_set.each_cons(2).all? { |a, b| a < b } + end + + def all_decreasing?(level_set) + level_set.each_cons(2).all? { |a, b| a > b } + end + + def all_safe?(level_set) + return false unless all_increasing?(level_set) || all_decreasing?(level_set) + + level_set.each_cons(2).all? { |a, b| (a - b).abs.between?(1, 3) } + end +end + +safe_reports = input.select { |line| Report.new(line).safe? } + +puts ""Answer: #{safe_reports.count}""",ruby +507,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe? + +Your puzzle answer was 341. + +--- Part Two --- + +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. + +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! + +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. + +More of the above example's reports are now safe: + +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! + +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"module AdventOfCode2024 + module Day02 + class Puzzle + def initialize(input) + @input = input + end + + def self.parse_input(input_string) + reports = [] + input_string.each_line do |line| + report = line.split.map { |s| s.to_i } + reports.append(report) + end + reports + end + + # Check a report for safety. A report is a list of levels, and a level + # is just an integer. For example, a report could look like this: + # [1, 2, 3, 4, 5]. + # + # Safety invariants: + # - All differences between levels must be within the range of 1..3 + # - All differences between adjacent levels must be unidirectional + # (i.e., either all increasing or all decreasing). + def safe?(report) + previous_element = report[0] + previous_direction = nil + + report[1..].each do |val| + difference = (val - previous_element).abs + + # Ensure difference is within the range of 1..3 + if difference < 1 || difference > 3 + return false + end + + # Establish direction or return false if direction has changed + current_direction = (val - previous_element).positive? ? 'dec' : 'inc' + if previous_direction == nil + previous_direction = current_direction + elsif previous_direction != current_direction + return false + end + + # Set the previous_element + previous_element = val + end + + return true + end + + def safe_with_dampener?(report) + safe = false + (0..report.size).each do |index_to_delete| + dup = report.dup + dup.delete_at(index_to_delete) + safe = true if safe? dup + end + + safe + end + + def part_one + @input.count { |report| safe? report } + end + + def part_two + @input.count { |report| safe_with_dampener? report } + end + end + + def self.solve(input_file_path = File.join(__dir__, 'input.txt')) + input_string = File.read(input_file_path) + parsed_input = Puzzle.parse_input(input_string) + puzzle = Puzzle.new(parsed_input) + + puts ""Day02.1 Solution: #{puzzle.part_one}"" + puts ""Day02.2 Solution: #{puzzle.part_two}"" + end + end +end + +if __FILE__ == $PROGRAM_NAME + AdventOfCode2024::Day02.solve +end",ruby +508,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe? + +Your puzzle answer was 341. + +--- Part Two --- + +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. + +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! + +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. + +More of the above example's reports are now safe: + +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! + +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"def if_asc(x) + x.each_cons(2).all? { |y, z| y < z } +end + +def if_dsc(x) + x.each_cons(2).all? { |y, z| y > z } +end + +def if_asc_morethan3(x) + x.each_cons(2).all? { |y, z| y > z - 4 } +end + +def if_dsc_morethan3(x) + x.each_cons(2).all? { |y, z| y < z + 4 } +end + +input = File.readlines(""input.txt"", chomp: true).map { |x| x.split("" "").map(&:to_i) } +safe = 0 + +input.each do |x| + is_safe = 0 + asc = if_asc(x) + dsc = if_dsc(x) + + if asc + asc3 = if_asc_morethan3(x) + if asc3 + safe += 1 + is_safe += 1 + end + end + + if dsc + dsc3 = if_dsc_morethan3(x) + if dsc3 + safe += 1 + is_safe += 1 + end + end + + if is_safe == 0 + list_safe = 0 + (0...x.length).each do |i| + list = x[0...i] + x[i+1..-1] + list_asc = if_asc(list) + list_dsc = if_dsc(list) + + if list_asc + list_asc3 = if_asc_morethan3(list) + if list_asc3 + list_safe += 1 + end + elsif list_dsc + list_dsc3 = if_dsc_morethan3(list) + if list_dsc3 + list_safe += 1 + end + end + end + + if list_safe > 0 + safe += 1 + end + end +end + +puts safe",ruby +509,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. + +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe? + +Your puzzle answer was 341. + +--- Part Two --- + +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. + +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! + +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. + +More of the above example's reports are now safe: + +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! + +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"def is_ok(lst) + inc_dec = lst == lst.sort || lst == lst.sort.reverse + size_ok = true + (0...(lst.length - 1)).each do |i| + if !(0 < (lst[i] - lst[i + 1]).abs && (lst[i] - lst[i + 1]).abs <= 3) + size_ok = false + end + end + + return inc_dec && size_ok +end + +def solve(input_path) + lines = File.readlines(input_path, chomp: true) + l_list = lines.map { |line| line.split(' ').map(&:to_i) } + counter = 0 + + l_list.each_with_index do |l, idx| + puts ""Evaluating #{l}"" + puts ""There was an error #{idx}: #{l}"" + + if is_ok(l) + counter += 1 + else + (0...l.length).each do |i| + tmp = l.clone + tmp.delete_at(i) + if is_ok(tmp) + counter += 1 + break + end + end + end + end + + puts counter +end + +input_path = ARGV[0] || 'input.txt' +solve(input_path)",ruby +510,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +pairs = [] +input.each { |line| pairs += line.scan(/mul\(([0-9]{1,3}),([0-9]{1,3})\)/) } +answer = pairs.map { |n1, n2| n1.to_i * n2.to_i }.sum + +puts ""Answer: #{answer}""",ruby +511,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"#!/usr/bin/env ruby +input = File.read('input.txt') + +result = 0 + +muls = input.scan(/mul\((\d{1,3}),(\d{1,3})\)/) +muls.each do |m| + result += m[0].to_i * m[1].to_i +end + +puts ""Result: #{result}""",ruby +512,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"#!/usr/bin/ruby + +instructions_cor = File.read(""input.txt"") + +instructions = instructions_cor.scan(/mul\((\d+,\d+)\)/) + +mul_inp = instructions.map { |instruction| instruction[0].split("","") } +mul_results = mul_inp.map { |instruction| instruction[0].to_i * instruction[1].to_i } +mul_total = mul_results.sum + +puts ""Sum of all multiplications: #{mul_total}""",ruby +513,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"def run_ops(ops) + ew = ops[4..-2].split(',') + ew[0].to_i * ew[1].to_i +end + +def part1 + File.open('./input.txt') do |f| + pattern = /mul\(\d+,\d+\)/ + ops = f.read.scan(pattern) + sum = 0 + ops.each do |o| + sum += run_ops(o) + end + puts sum + end +end + +def part2 + File.open('./input.txt') do |f| + pattern = /do\(\)|don't\(\)|mul\(\d+,\d+\)/ + ops = f.read.scan(pattern) + do_op = true + sum = 0 + ops.each do |op| + if op == ""don't()"" + do_op = false + next + elsif op == 'do()' + do_op = true + next + end + if do_op + sum += run_ops(op) + end + end + puts sum + end +end + +part1",ruby +514,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"module AdventOfCode2024 + module Day03 + class Puzzle + def initialize(input) + @input = input + end + + def self.parse_input(input_string) + instructions = input_string.scan(/mul\(\d+,\d+\)|don't|do/) + parsed_instructions = [] + instructions.each do |instruction| + case instruction + when ""don't"", ""do"" + parsed_instructions.append(instruction) + else + operation = ""mul"" + factor_one, factor_two = instruction.scan(/\d+/) + parsed_instructions.append([operation, factor_one.to_i, factor_two.to_i]) + end + end + parsed_instructions + end + + def part_one + @input.sum do |instruction| + if instruction[0] == ""mul"" + instruction[1] * instruction[2] + else + 0 + end + end + end + + def part_two + mul_enabled = true + @input.sum do |instruction| + case instruction + when ""do"" + mul_enabled = true + 0 + when ""don't"" + mul_enabled = false + 0 + else + if mul_enabled + instruction[1] * instruction[2] + else + 0 + end + end + end + end + end + + def self.solve(input_file_path = File.join(__dir__, 'input.txt')) + input_string = File.read(input_file_path) + parsed_input = Puzzle.parse_input(input_string) + puzzle = Puzzle.new(parsed_input) + + puts ""Day03.1 Solution: #{puzzle.part_one}"" + puts ""Day03.2 Solution: #{puzzle.part_two}"" + end + end +end + +if __FILE__ == $PROGRAM_NAME + AdventOfCode2024::Day03.solve +end",ruby +515,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? + +Your puzzle answer was 170807108. + +--- Part Two --- + +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. + +There are two new instructions you'll need to handle: + +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. + +For example: + +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. + +This time, the sum of the results is 48 (2*4 + 8*5). + +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"def sum_instructions(instructions) + instructions.sum { |x, y| x.to_i * y.to_i } +end + +def get_tuples(instructions) + instructions.scan(/mul\((\d{1,3}),(\d{1,3})\)/) +end + +def main + total = 0 + File.open('input.txt') do |file| + line = file.read + split = line.split(""don't()"") + puts split.length + + # always starts enabled + total += sum_instructions(get_tuples(split.shift)) + + split.each do |block| + instructions = block.split('do()') + # ignore the don't block + instructions.shift + instructions.each do |i| + total += sum_instructions(get_tuples(i)) + end + end + end + puts ""total: #{total}"" +end + +main",ruby +516,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? + +Your puzzle answer was 170807108. + +--- Part Two --- + +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. + +There are two new instructions you'll need to handle: + +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. + +For example: + +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. + +This time, the sum of the results is 48 (2*4 + 8*5). + +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"input_text = File.read(""input.txt"") +total = 0 +do_op = true + +input_text.scan(/mul\((\d+),(\d+)\)|(don't\(\))|(do\(\))/) do |res| + if do_op && res[0] + total += res[0].to_i * res[1].to_i + elsif do_op && res[2] + do_op = false + elsif !do_op && res[3] + do_op = true + end +end + +puts total",ruby +517,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? + +Your puzzle answer was 170807108. + +--- Part Two --- + +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. + +There are two new instructions you'll need to handle: + +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. + +For example: + +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. + +This time, the sum of the results is 48 (2*4 + 8*5). + +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"file = File.open(""input.txt"") +muls = file.read.scan(/mul\(([0-9]+),([0-9]+)\)|(don't\(\))|(do\(\))/) +sum = 0 +enabled = true +muls.each do |mul| + if mul[2] == ""don't()"" + enabled = false + elsif mul[3] == ""do()"" + enabled = true + elsif enabled + sum += mul[0].to_i * mul[1].to_i + end +end +puts(sum)",ruby +518,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? + +Your puzzle answer was 170807108. + +--- Part Two --- + +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. + +There are two new instructions you'll need to handle: + +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. + +For example: + +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. + +This time, the sum of the results is 48 (2*4 + 8*5). + +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"input = open('./input.txt').readlines + +results = [] +input.each do | line | + results << line.scan(/mul\(\d{1,3},\d{1,3}\)/) +end + +results.flatten! +sum = 0 +results.each do | r | + par = r.split(""mul("")[1].split("")"")[0].split("","").map(&:to_i) + sum += par[0].to_i * par[1].to_i +end + +puts sum + +# Part Two + +results = [] +input.each do | line | + partial_res = [] + line.scan(/mul\(\d{1,3},\d{1,3}\)/) do |c| + partial_res << [c, $~.offset(0)[0]] + end + line.scan(/do\(\)/) do |c| + partial_res << [c, $~.offset(0)[0]] + end + line.scan(/don't\(\)/) do |c| + partial_res << [c, $~.offset(0)[0]] + end + partial_res.sort! { |a, b| a[1] <=> b[1]} + partial_res.each do | pr | + results << pr + end +end + +puts results.inspect + +enabled = true +sum = 0 +results.each do | res | + if enabled + if res[0][0..2] == ""mul"" + nums = res[0].split(""mul("")[1].split("")"")[0].split("","").map(&:to_i) + sum += nums.inject(:*) + elsif res[0][0..2] == ""don"" + enabled = false + end + else + if res[0][0..2] == ""do("" + enabled = true + end + end +end + +puts sum + +# Too High 94180746",ruby +519,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. + +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? + +Your puzzle answer was 170807108. + +--- Part Two --- + +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. + +There are two new instructions you'll need to handle: + +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. + +For example: + +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. + +This time, the sum of the results is 48 (2*4 + 8*5). + +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +instructions = [] +input.each do |line| + instructions += line.scan(/(don't\(\)|mul\([0-9]{1,3},[0-9]{1,3}\)|do\(\))/).flatten +end + +enabled = true +answer = 0 +instructions.each do |instruction| + if instruction == ""don't()"" + enabled = false + elsif instruction == 'do()' + enabled = true + elsif enabled + n1, n2 = instruction.scan(/mul\(([0-9]{1,3}),([0-9]{1,3})\)/).flatten + answer += n1.to_i * n2.to_i + end +end + +puts ""Answer: #{answer}""",ruby +520,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"module AdventOfCode2024 + module Day04 + class Puzzle + def initialize(input) + @input = input + end + + def self.parse_input(input_string) + parsed = [] + input_string.each_line do |line| + parsed.append(line.strip.each_char.map(&:to_s)) + end + parsed + end + + # Read n characters in d direction from @input, starting at coordinate (x,y). + def read_chars_in_direction(arr:, x:, y:, n:, d:) + chars = [] + northern_limit = 0 + eastern_limit = arr[y].size - 1 + southern_limit = arr.size - 1 + western_limit = 0 + + case d.upcase + when 'N' + y_min = y - n + 1 + if y_min >= northern_limit + y.downto(y_min) { |row_idx| chars.append(arr[row_idx][x]) } + end + when 'NE' + y_min = y - n + 1 + x_max = x + n - 1 + if y_min >= northern_limit && x_max <= eastern_limit + y.downto(y_min).to_a.zip((x..x_max)).each do |row_idx, char_idx| + chars.append(arr[row_idx][char_idx]) + end + end + when 'E' + x_max = x + n - 1 + if x_max <= eastern_limit + (x..x_max).each { |char_idx| chars.append(arr[y][char_idx])} + end + when 'SE' + y_max = y + n - 1 + x_max = x + n - 1 + if y_max <= southern_limit && x_max <= eastern_limit + (y..y_max).to_a.zip((x..x_max)).each do |row_idx, char_idx| + chars.append(arr[row_idx][char_idx]) + end + end + when 'S' + y_max = y + n - 1 + if y_max <= southern_limit + (y..y_max).each { |row_idx| chars.append(arr[row_idx][x]) } + end + when 'SW' + y_max = y + n - 1 + x_min = x - n + 1 + if y_max <= southern_limit && x_min >= western_limit + (y..y_max).to_a.zip(x.downto(x_min)).each do |row_idx, char_idx| + chars.append(arr[row_idx][char_idx]) + end + end + when 'W' + x_min = x - n + 1 + if x_min >= western_limit + x.downto(x_min) { |char_idx| chars.append(arr[y][char_idx]) } + end + when 'NW' + y_min = y - n + 1 + x_min = x - n + 1 + if y_min >= northern_limit && x_min >= western_limit + y.downto(y_min).to_a.zip(x.downto(x_min)).each do |row_idx, char_idx| + chars.append(arr[row_idx][char_idx]) + end + end + end + + chars.join + end + + def read_chars_in_all_directions(arr:, x:, y:, n:) + results = [] + directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'] + directions.each do |d| + results.append(read_chars_in_direction(arr: arr, x: x, y: y, n: n, d: d)) + end + results + end + + def read_chars_in_all_diagonals(arr:, x:, y:, n:) + results = [] + directions = ['NE', 'SE', 'SW', 'NW'] + directions.each do |d| + result = read_chars_in_direction(arr: arr, x: x, y: y, n: n, d: d) + results.append(result) + end + results + end + + def has_x_mas?(grid) + # corner coordinates (clockwise) + nw_x, nw_y = [0, 0] + ne_x, ne_y = [2, 0] + + # check if we can read 'MAS', starting from each corner + mas_count = 0 + nw_to_se = read_chars_in_direction(arr: grid, x: nw_x, y: nw_y, n: 3, d: 'SE') + ne_to_sw = read_chars_in_direction(arr: grid, x: ne_x, y: ne_y, n: 3, d: 'SW') + [nw_to_se, ne_to_sw].each do |diagonal| + mas_count += 1 if diagonal == 'MAS' || diagonal.reverse == 'MAS' + end + + if mas_count == 2 + true + else + false + end + end + + # XMAS... + def part_one + xmas_count = 0 + @input.each_with_index do |row, row_idx| + row.each_with_index do |char, char_idx| + if char == 'X' + test_cases = read_chars_in_all_directions(arr: @input, x: char_idx, y: row_idx, n: 4) + xmas_count += test_cases.count { |test_case| test_case == 'XMAS' } + end + end + end + + xmas_count + end + + # X-MAS! + def part_two + x_mas_count = 0 + @input.each_with_index do |row, row_idx| + row.each_with_index do |char, char_idx| + if row_idx + 2 < @input.size && char_idx + 2 < @input[row_idx].size + grid = [] + @input[row_idx..row_idx + 2].each do |r| + grid.append(r[char_idx..char_idx + 2]) + end + x_mas_count += 1 if has_x_mas? grid + end + end + end + + x_mas_count + end + end + + def self.solve(input_file_path = File.join(__dir__, 'input.txt')) + input_string = File.read(input_file_path) + parsed_input = Puzzle.parse_input(input_string) + puzzle = Puzzle.new(parsed_input) + + puts ""Day04.1 Solution: #{puzzle.part_one}"" + puts ""Day04.2 Solution: #{puzzle.part_two}"" + end + end +end + +if __FILE__ == $PROGRAM_NAME + AdventOfCode2024::Day04.solve +end",ruby +521,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"# Read input file +lines = File.read(""input.txt"").strip.split(""\n"") + +n = lines.length +m = lines[0].length + +# Generate all directions +dd = [] +(-1..1).each do |dx| + (-1..1).each do |dy| + dd << [dx, dy] unless dx == 0 && dy == 0 + end +end + +# Function to check if 'XMAS' is found at a given position (i, j) in a given direction (dx, dy) +def has_xmas(i, j, dx, dy, lines, n, m) + ""XMAS"".each_char.with_index do |char, k| + ii = i + k * dx + jj = j + k * dy + return false unless ii.between?(0, n - 1) && jj.between?(0, m - 1) + return false if lines[ii][jj] != char + end + true +end + +# Count up every cell and every direction +ans = 0 +(0...n).each do |i| + (0...m).each do |j| + dd.each do |dx, dy| + ans += 1 if has_xmas(i, j, dx, dy, lines, n, m) + end + end +end + +puts ans",ruby +522,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +grid = [] + +input.each do |line| + grid << line.split('') +end + +matches = 0 + +# Brute force search +grid.each_index do |row_index| + grid[row_index].each_index do |col_index| + next unless grid[row_index][col_index] == 'X' + + if row_index - 3 >= 0 + # Upper diagonal to the left + if col_index - 3 >= 0 && + grid[row_index - 1][col_index - 1] == 'M' && + grid[row_index - 2][col_index - 2] == 'A' && + grid[row_index - 3][col_index - 3] == 'S' + matches += 1 + end + + # Straight up + if grid[row_index - 1][col_index] == 'M' && + grid[row_index - 2][col_index] == 'A' && + grid[row_index - 3][col_index] == 'S' + matches += 1 + end + + # Upper diagonal to the right + if col_index + 3 < grid[row_index].size && + grid[row_index - 1][col_index + 1] == 'M' && + grid[row_index - 2][col_index + 2] == 'A' && + grid[row_index - 3][col_index + 3] == 'S' + matches += 1 + end + end + + if row_index + 3 < grid.size + # Down diagonal to the left + if col_index - 3 >= 0 && + grid[row_index + 1][col_index - 1] == 'M' && + grid[row_index + 2][col_index - 2] == 'A' && + grid[row_index + 3][col_index - 3] == 'S' + matches += 1 + end + + # Straight down + if grid[row_index + 1][col_index] == 'M' && + grid[row_index + 2][col_index] == 'A' && + grid[row_index + 3][col_index] == 'S' + matches += 1 + end + + # Down diagonal to the right + if col_index + 3 < grid[row_index].size && + grid[row_index + 1][col_index + 1] == 'M' && + grid[row_index + 2][col_index + 2] == 'A' && + grid[row_index + 3][col_index + 3] == 'S' + matches += 1 + end + end + + # Search to the left + if col_index - 3 >= 0 && + grid[row_index][col_index - 1] == 'M' && + grid[row_index][col_index - 2] == 'A' && + grid[row_index][col_index - 3] == 'S' + matches += 1 + end + + # Search to the right + if col_index + 3 < grid[row_index].size && + grid[row_index][col_index + 1] == 'M' && + grid[row_index][col_index + 2] == 'A' && + grid[row_index][col_index + 3] == 'S' + matches += 1 + end + end +end + +puts ""Matches: #{matches}""",ruby +523,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"DIRECTIONS = [ + [1, 0], + [0, 1], + [-1, 0], + [0, -1], + [1, 1], + [-1, -1], + [-1, 1], + [1, -1], +] + +def count_xmas(x, y, words, width, height) + count = 0 + DIRECTIONS.each do |dx, dy| + if (1..3).all? do |i| + nx = x + i * dx + ny = y + i * dy + nx.between?(0, width - 1) && ny.between?(0, height - 1) && words[nx][ny] == ""MAS""[i - 1] + end + count += 1 + end + end + count +end + +def main(words, width, height) + result = 0 + (0...width).each do |x| + (0...height).each do |y| + if words[x][y] == ""X"" + result += count_xmas(x, y, words, width, height) + end + end + end + puts ""result=#{result}"" +end + +words = File.readlines(""input.txt"").map(&:strip).map { |line| line.chars } + +width = words[0].length +height = words.length +main(words, width, height)",ruby +524,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"# Read the input data from the file +input_text = File.read(""input.txt"").split(""\n"") + +num_rows = input_text.length +num_cols = input_text[0].length +total = 0 + +# Helper function to count the occurrences of ""XMAS"" +def count_xmas_in_direction(str) + str.scan(/XMAS/).length +end + +# Check Rows (left to right and right to left) +input_text.each do |row| + total += count_xmas_in_direction(row) + total += count_xmas_in_direction(row.reverse) +end + +# Check Columns (top to bottom and bottom to top) +(0...num_cols).each do |col_idx| + col = input_text.map { |row| row[col_idx] }.join + total += count_xmas_in_direction(col) + total += count_xmas_in_direction(col.reverse) +end + +# Check NE/SW Diagonals +(0...(num_rows + num_cols - 1)).each do |idx_sum| + diagonal = (0...[num_rows, num_cols].min).map do |row_idx| + if (idx_sum - row_idx).between?(0, num_cols - 1) && (row_idx).between?(0, num_rows - 1) + input_text[row_idx][idx_sum - row_idx] + else + nil + end + end.join + total += count_xmas_in_direction(diagonal) + total += count_xmas_in_direction(diagonal.reverse) +end + +# Check NW/SE Diagonals +(-num_cols + 1...(num_rows)).each do |idx_diff| + diagonal = (0...[num_rows, num_cols].min).map do |row_idx| + if (row_idx).between?(0, num_rows - 1) && (row_idx - idx_diff).between?(0, num_cols - 1) + input_text[row_idx][row_idx - idx_diff] + else + nil + end + end.join + total += count_xmas_in_direction(diagonal) + total += count_xmas_in_direction(diagonal.reverse) +end + +# Print the total number of occurrences +puts total",ruby +525,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? + +Your puzzle answer was 2434. + +--- Part Two --- + +The Elf looks quizzically at you. Did you misunderstand the assignment? + +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: + +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. + +Here's the same example from before, but this time all of the X-MASes have been kept instead: + +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. + +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"input = open('./input.txt').readlines +input.map!(&:strip) + +# Read in and seach vertincally (backwards and forwards) +count = 0 +# input.each_with_index do | line, index | +# count += line.scan(/XMAS/).size +# count += line.reverse.scan(/XMAS/).size +# input[index] = line.split("""") +# end + +# # Rotate array by 90 +# rot_arr = [] +# input.transpose.each do | line | +# rot_arr << line.reverse +# end + +# rot_arr.each do | line | +# line = line.join() +# puts line +# count += line.scan(/XMAS/).size +# count += line.reverse.scan(/XMAS/).size +# end + +# # Rotate array by -45 +# ang_arr = [] +# max_x = input[0].length - 1 +# max_y = input.length - 1 +# max_loop = max_x + max_y + 1 +# bound = [max_x, max_y].min + +# xx = 0 +# yy = 0 + +# max_loop.times do | t | +# ang = [] +# x = 0 +# x = t - yy if t > yy +# y = yy +# t = max_loop - t - 1 if t > bound +# (t + 1).times do +# puts t, [x, y].inspect +# ang << rot_arr[y][x] +# y -= 1 +# x += 1 +# end +# ang_arr << ang.join('') +# puts ang_arr.inspect +# if(yy > max_x) +# xx += 1 +# end +# if (yy < max_y) +# yy += 1 +# end +# end + +# puts ang_arr + +# ang_arr.each do | line | +# count += line.scan(/XMAS/).size +# count += line.reverse.scan(/XMAS/).size +# end + +# # Rotate array by 45 +# ang_arr = [] +# max_x = input[0].length - 1 +# max_y = input.length - 1 +# max_loop = max_x + max_y + 1 +# bound = [max_x, max_y].min + +# xx = 0 +# yy = 0 + +# max_loop.times do | t | +# ang = [] +# x = 0 +# x = t - yy if t > yy +# y = yy +# t = max_loop - t - 1 if t > bound +# (t + 1).times do +# puts t, [x, y].inspect +# ang << input[y][x] +# y -= 1 +# x += 1 +# end +# ang_arr << ang.join('') +# puts ang_arr.inspect +# if(yy > max_x) +# xx += 1 +# end +# if (yy < max_y) +# yy += 1 +# end +# end + +# puts ang_arr + +# ang_arr.each do | line | +# count += line.scan(/XMAS/).size +# count += line.reverse.scan(/XMAS/).size +# end + +max_x = input[0].length +max_y = input.length +counter = 0 +(max_y - 2).times do | y | + (max_x - 2).times do | x | + scanner = """" + scanner += input[y][x..(x+2)] + scanner += input[y + 1][x..(x+2)] + scanner += input[y + 2][x..(x+2)] + puts scanner + # M.M S.M S.S M.S + # .A. .A. .A. .A. + # S.S S.M M.M M.S + count += scanner.scan(/M.M.A.S.S/).size + count += scanner.scan(/S.M.A.S.M/).size + count += scanner.scan(/S.S.A.M.M/).size + count += scanner.scan(/M.S.A.M.S/).size + counter += 1 + end +end + + +puts counter, count",ruby +526,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? + +Your puzzle answer was 2434. + +--- Part Two --- + +The Elf looks quizzically at you. Did you misunderstand the assignment? + +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: + +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. + +Here's the same example from before, but this time all of the X-MASes have been kept instead: + +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. + +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"FNAME = ""input.txt"" +WORD = ""MMASS"" + +def main + matrix = file_to_matrix(FNAME) + puts count_word(matrix, WORD) +end + +def file_to_matrix(fname) + out = [] + File.foreach(fname) do |line| + out << line.chomp.chars + end + out +end + +def count_word(matrix, word) + count = 0 + len_matrix = matrix.length + for i in 0...len_matrix + for j in 0...len_matrix + count += count_word_for_pos(matrix, [i, j], word) + end + end + count +end + +def count_word_for_pos(matrix, pos, word) + count = 0 + return 0 if pos[0] < 1 || pos[0] > matrix.length - 2 || pos[1] < 1 || pos[1] > matrix.length - 2 + + patterns = [ + [[-1, -1], [1, -1], [0, 0], [-1, 1], [1, 1]], + [[1, 1], [-1, 1], [0, 0], [1, -1], [-1, -1]], + [[-1, -1], [-1, 1], [0, 0], [1, -1], [1, 1]], + [[1, 1], [1, -1], [0, 0], [-1, 1], [-1, -1]] + ] + + patterns.each do |pattern| + s = pattern.map { |p| matrix[pos[0] + p[0]][pos[1] + p[1]] }.join + if s == word + count += 1 + end + end + + count +end + +main",ruby +527,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? + +Your puzzle answer was 2434. + +--- Part Two --- + +The Elf looks quizzically at you. Did you misunderstand the assignment? + +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: + +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. + +Here's the same example from before, but this time all of the X-MASes have been kept instead: + +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. + +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +grid = [] + +input.each do |line| + grid << line.split('') +end + +matches = 0 + +# Brute force search +grid.each_index do |row_index| + grid[row_index].each_index do |col_index| + next unless grid[row_index][col_index] == 'A' + + # Skip unless we have room for the X + next unless row_index - 1 >= 0 + next unless row_index + 1 < grid.size + next unless col_index - 1 >= 0 + next unless col_index + 1 < grid[row_index].size + + if [grid[row_index - 1][col_index - 1], grid[row_index + 1][col_index + 1]].sort == %w[M S] && + [grid[row_index - 1][col_index + 1], grid[row_index + 1][col_index - 1]].sort == %w[M S] + matches += 1 + end + end +end + +puts ""Matches: #{matches}""",ruby +528,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? + +Your puzzle answer was 2434. + +--- Part Two --- + +The Elf looks quizzically at you. Did you misunderstand the assignment? + +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: + +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. + +Here's the same example from before, but this time all of the X-MASes have been kept instead: + +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. + +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"cont = File.readlines(""day4input.txt"").map { |i| i.strip.chars } + +def get_neighbors(matrix, x, y) + rows = matrix.length + cols = matrix[0].length + neighbors = [] + + directions = [ + [-1, -1], [-1, 0], [-1, 1], + [0, -1], [0, 0], [0, 1], + [1, -1], [1, 0], [1, 1] + ] + + directions.each do |dx, dy| + nx, ny = x + dx, y + dy + if nx >= 0 && nx < rows && ny >= 0 && ny < cols + neighbors << matrix[nx][ny] + end + end + + neighbors +end + +def check(matrix) + mas = [""MAS"", ""SAM""] + d = [matrix[0][0], matrix[1][1], matrix[2][2]].join + a = [matrix[0][2], matrix[1][1], matrix[2][0]].join + mas.include?(d) && mas.include?(a) ? 1 : 0 +end + +t = 0 + +(0...cont.length).each do |x| + (0...cont[x].length).each do |y| + next if [0, 139].include?(x) || [0, 139].include?(y) + + if cont[x][y] == ""A"" + neighbors = get_neighbors(cont, x, y) + matrix = [neighbors[0..2], neighbors[3..5], neighbors[6..8]] + + t += check(matrix) + end + end +end + +puts t",ruby +529,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! + +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: + +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? + +Your puzzle answer was 2434. + +--- Part Two --- + +The Elf looks quizzically at you. Did you misunderstand the assignment? + +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: + +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. + +Here's the same example from before, but this time all of the X-MASes have been kept instead: + +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. + +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"file = File.open(""input.txt"") +file_data = file.readlines.map(&:chomp) +puzzle_matrix = [] +file_data.each_with_index do |line, i| + puzzle_matrix << [] + line.split("""").each do |c| + puzzle_matrix[i] << c + end +end + +def g(a,i) + if i < 0 + return nil + end + return a[i] +end + +## abandon this approach, fuck it. +# check instead each square if it has any xmases +# since there are no repeating letters, this should be fine +def has_xmas_horizontal(array, at, direction) + return g(array,at) == ""X"" && g(array,at + direction) == ""M"" && g(array,at + (direction*2)) == ""A"" && g(array,at + (direction*3)) == ""S"" +end + +def has_xmas_vertical(matrix, x, y, direction) + #go direction in y to check next + if g(matrix,y + direction).nil? or g(matrix,y + (direction*2)).nil? or g(matrix,y + (direction*3)).nil? + return false + end + return g(g(matrix,y), x) == ""X"" && g(g(matrix,y + direction),x) == ""M"" && g(g(matrix,y+ (direction*2)), x) == ""A"" && g(g(matrix,y+(direction*3)),x) == ""S"" +end + +def has_xmas_diag(matrix, x, y, direction_x, direction_y) + #go direction in y to check next + # we might not even have an array at a specific y, so we gotta check em + if g(matrix,y + direction_y).nil? or g(matrix,y + (direction_y*2)).nil? or g(matrix,y + (direction_y*3)).nil? + return false + end + return g(g(matrix,y),x) == ""X"" && g(g(matrix,y + direction_y),x + direction_x) == ""M"" && g(g(matrix,y + (direction_y*2)),x + (direction_x*2)) == ""A"" && g(g(matrix,y + (direction_y*3)), x + (direction_x*3)) == ""S"" +end + +def test_diag(matrix, x, y) + if matrix[y-1][x-1] == ""S"" + if matrix[y+1][x+1] == ""M"" + return true + end + end + if matrix[y-1][x-1] == ""M"" + if matrix[y+1][x+1] == ""S"" + return true + end + end + return false +end + +def test_diag_2(matrix, x, y) + if matrix[y-1][x+1] == ""S"" + if matrix[y+1][x-1] == ""M"" + return true + end + end + if matrix[y-1][x+1] == ""M"" + if matrix[y+1][x-1] == ""S"" + return true + end + end + return false +end + +def has_crossmas(matrix,x,y) + if x < 1 or y < 1 or x > matrix[0].length - 2 or y > matrix.length - 2 + return false + end + if matrix[y][x] != ""A"" + return false + end + + if test_diag(matrix, x, y) and test_diag_2(matrix, x, y) + return true + end + return false +end + +xmases = 0 +crossmases = 0 +puzzle_matrix.length.times do |y| + + puzzle_matrix[y].length.times do |x| + #check crossmas + if has_crossmas(puzzle_matrix, x,y) + crossmases +=1 + end + #check xmas in every direction + + if has_xmas_horizontal(puzzle_matrix[y], x, 1) + puts(""horisontal forward at #{x},#{y}"") + xmases+=1 + end + if has_xmas_horizontal(puzzle_matrix[y], x, -1) + puts(""horisontal backward at #{x},#{y}"") + xmases+=1 + end + if has_xmas_vertical(puzzle_matrix, x, y, 1) + puts(""vertical down at #{x},#{y}"") + xmases +=1 + end + if has_xmas_vertical(puzzle_matrix, x, y, -1) + puts(""vertical up at #{x},#{y}"") + xmases +=1 + end + + if has_xmas_diag(puzzle_matrix, x, y, 1,1) + puts(""diag 1,1 at #{x},#{y}"") + xmases +=1 + end + if has_xmas_diag(puzzle_matrix, x, y, 1,-1) + puts(""diag 1,-1 at #{x},#{y}"") + xmases +=1 + end + if has_xmas_diag(puzzle_matrix, x, y, -1,1) + puts(""diag -1,1 at #{x},#{y}"") + xmases +=1 + end + #this one freaks out for some reason... + if has_xmas_diag(puzzle_matrix, x, y, -1, -1) + puts(""diag -1,-1 at #{x},#{y}"") + xmases +=1 + end + #check vertical + end +end +puts(xmases) +puts(crossmases)",ruby +530,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates?",4766,"input_file = ""input.txt"" +# input_file = ""./input_1.txt"" + +rules = [] +updates = [] + +# Read input from the file +File.open(input_file, ""r"") do |data| + lines = data.readlines + + lines.each do |line| + # Look for rules then updates + if line.include?(""|"") + rules << line.strip.split(""|"") + elsif line.include?("","") + updates << line.strip.split("","") + end + end +end + +# Loop through updates +correct_updates = [] +updates.each do |update| + correct = true + + # Check if there are repeated pages in the update + update.each do |page| + count = update.count(page) + if count != 1 + puts ""WARNING: update #{update} has repeated page #{page}"" + end + end + + # Check if the update has an even number of pages + if update.length.even? + puts ""WARNING: update #{update} has an even number (#{update.length}) of pages"" + end + + # Identify relevant rules + relevant_rules = [] + rules.each do |rule| + if (rule.to_set <= update.to_set) + relevant_rules << rule + end + end + + # Check that each rule is obeyed + relevant_rules.each do |rule| + if update.index(rule[0]) > update.index(rule[1]) + correct = false + break + end + end + + # If all rules are obeyed, add the update to the list of correct updates + if correct + correct_updates << update + puts ""Correct update: #{update}"" + puts "" Relevant rules: #{relevant_rules}"" + puts '' + end +end + +# Now go through correct_updates[] and find the middle element +tally = [] +correct_updates.each do |update| + # All updates should have odd numbers of pages + mid_index = (update.length - 1) / 2 + tally << update[mid_index].to_i +end + +puts ""Tally: #{tally}"" +total = tally.sum +puts ""Result: #{total}""",ruby +531,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates?",4766,"@page_pairs = {} +@page_updates = [] + +def main + read_puzzle_input + check_page_updates +end + +def read_puzzle_input + File.readlines('input.txt').each do |line| + if line.include?(""|"") + page_pair = line.strip.split(""|"") + @page_pairs[page_pair[0]] ||= [] + @page_pairs[page_pair[0]] << page_pair[1] + elsif line.include?("","") + @page_updates << line.strip.split("","") + end + end +end + +def check_page_updates + total_sum = 0 + @page_updates.each do |page_update| + middle_number = correct_order(page_update) + total_sum += middle_number.to_i if middle_number + end + puts total_sum +end + +def correct_order(page_update) + puts + puts page_update + (page_update.length-1).downto(1) do |page_index| + puts page_update[page_index], @page_pairs[page_update[page_index]] + @page_pairs[page_update[page_index]].each do |page| + if page_update[0..page_index-1].include?(page) + puts ""Error:"", page + return false + end + end + end + page_update[(page_update.length - 1) / 2] +end + +main",ruby +532,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates?",4766,"def parse_input(filename) + # Parse input file into rules and updates + content = File.read(filename).strip.split(""\n\n"") + + # Parse rules into a set of tuples (before, after) + rules = Set.new + content[0].split(""\n"").each do |line| + before, after = line.split('|').map(&:to_i) + rules.add([before, after]) + end + + # Parse updates into lists of integers + updates = content[1].split(""\n"").map { |line| line.split(',').map(&:to_i) } + + return rules, updates +end + +def is_valid_order(update, rules) + # Check if an update follows all applicable rules + update.each_with_index do |x, i| + update[(i + 1)..].each do |y| + # If there's a rule saying y should come before x, the order is invalid + return false if rules.include?([y, x]) + end + end + true +end + +def get_middle_number(update) + # Get the middle number of an update + update[update.length / 2] +end + +def main + rules, updates = parse_input('input.txt') + + # Find valid updates and their middle numbers + middle_sum = 0 + updates.each do |update| + if is_valid_order(update, rules) + middle_num = get_middle_number(update) + middle_sum += middle_num + puts ""Valid update: #{update}, middle number: #{middle_num}"" + end + end + + puts ""\nSum of middle numbers: #{middle_sum}"" +end + +main if __FILE__ == $0",ruby +533,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates?",4766,"def check_valid(before_dict, update) + # For each number in the update + update.each_with_index do |num, i| + # For each number after the current number + (i+1...update.length).each do |j| + # If the number is not in before_dict + return false unless before_dict.key?(num) + + val = update[j] + # If the value is not in before_dict[num], return false + return false unless before_dict[num].include?(val) + end + end + true +end + +before_dict = {} +updates = [] + +# Read the input file +File.open(""input.txt"", ""r"") do |file| + lines = file.readlines.map(&:strip) + + one = true + lines.each do |line| + if line.empty? + one = false + next + end + + if one + k, val = line.split(""|"") + key = k.to_i + value = val.to_i + + # Store rules in before_dict + before_dict[key] ||= [] + before_dict[key] << value + else + # Store updates + updates << line.split("","").map(&:to_i) + end + end +end + +# Sort the values in before_dict +before_dict.each { |key, values| values.sort! } + +# Verify the updates +total = 0 +updates.each do |update| + if check_valid(before_dict, update) + total += update[update.length / 2] + end +end + +puts total",ruby +534,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates?",4766,"# Read the input file +rules = [] +lists = [] +File.readlines('input.txt').each_with_index do |line, i| + break if line.strip.empty? + + rules << line.strip.split('|') +end + +# Skip the empty line between rules and updates +rules.shift + +# Populate the update list +File.readlines('input.txt')[rules.length + 1..-1].each do |line| + lists << line.strip.split(',') +end + +# Store all rules per key in a dictionary +r_dict = Hash.new { |hash, key| hash[key] = [] } + +rules.each do |key, val| + r_dict[key] << val +end + +result = [] +lists.each do |x| + overlap = [] + + # Create a copy of ""x"" + j = x.dup + + # Create a list of the length of ""x"" which stores the amount of overlap between the rules applied to each key and the values in the list + x.each do |i| + overlap << (r_dict[i] & x).size + end + + out_list = [] + + # Find the index of the value with the most overlap + # Add that corresponding value to the output list, then remove it from both overlap and the input list (the ""update"") + x.length.times do + index = overlap.index(overlap.max) + out_list << x[index] + overlap.delete_at(index) + x.delete_at(index) + end + + # If the ordered list is the same as the initial list, the initial list was ordered + result << out_list if j == out_list +end + +# Make a list of the middle numbers +mid_nums = result.map { |x| x[x.length / 2].to_i } + +# Output the sum of the middle numbers +puts mid_nums.sum",ruby +535,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates? + +Your puzzle answer was 4766. + +--- Part Two --- + +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. + +For each of the incorrectly-ordered updates, use the page ordering rules to put the page numbers in the right order. For the above example, here are the three incorrectly-ordered updates and their correct orderings: + +75,97,47,61,53 becomes 97,75,47,61,53. +61,13,29 becomes 61,29,13. +97,13,75,29,47 becomes 97,75,47,29,13. +After taking only the incorrectly-ordered updates and ordering them correctly, their middle page numbers are 47, 29, and 47. Adding these together produces 123. + +Find the updates which are not in the correct order. What do you get if you add up the middle page numbers after correctly ordering just those updates?",6257,"def is_valid(update, rules) + all_pages = update.to_set + seen_pages = Set.new + + update.each do |cur| + if rules.key?(cur) + rules[cur].each do |n| + if all_pages.include?(n) && !seen_pages.include?(n) + return false + end + end + end + + seen_pages.add(cur) + end + + true +end + +def compare(x, y, rules) + if rules.key?(y) && rules[y].include?(x) + return -1 + end + + if rules.key?(x) && rules[x].include?(y) + return 1 + end + + 0 +end + +def fix(update, rules) + update.sort { |x, y| compare(x, y, rules) } +end + +rules = {} +updates = [] + +File.open('input.txt') do |f| + f.each_line do |line| + if line.include?(""|"") + x, y = line.strip.split(""|"").map(&:to_i) + rules[y] ||= [] + rules[y] << x + elsif !line.strip.empty? + updates << line.strip.split("","").map(&:to_i) + end + end +end + +total = 0 +updates.each do |update| + unless is_valid(update, rules) + fixed = fix(update, rules) + total += fixed[fixed.length / 2] + end +end + +puts total",ruby +536,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates? + +Your puzzle answer was 4766. + +--- Part Two --- + +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. + +For each of the incorrectly-ordered updates, use the page ordering rules to put the page numbers in the right order. For the above example, here are the three incorrectly-ordered updates and their correct orderings: + +75,97,47,61,53 becomes 97,75,47,61,53. +61,13,29 becomes 61,29,13. +97,13,75,29,47 becomes 97,75,47,29,13. +After taking only the incorrectly-ordered updates and ordering them correctly, their middle page numbers are 47, 29, and 47. Adding these together produces 123. + +Find the updates which are not in the correct order. What do you get if you add up the middle page numbers after correctly ordering just those updates?",6257,"module AdventOfCode2024 + module Day05 + class Puzzle + def initialize(input) + @input = input + end + + def self.parse_input(input_string) + lines = input_string.each_line.map(&:to_s).map(&:strip) + rules, updates = [], [] + lines[..1175].each { |l| rules.append(l.split('|').map(&:to_i)) } + lines[1177..].each { |l| updates.append(l.split(',').map(&:to_i)) } + parsed_input = {} # update -> relevant rules + updates.each do |u| + fit_rules = [] + rules.each do |r| + fit_rules.append(r) if u.include?(r[0]) && u.include?(r[1]) + end + parsed_input[u] = fit_rules + end + + parsed_input + end + + def good_update?(update, rules) + rules.each do |rule| + left, right = rule + left_index, right_index = update.index(left), update.index(right) + if left_index > right_index + return false + end + end + + true + end + + def part_one + @input.sum do |update, rules| + middle_index = (update.size / 2).ceil + if good_update?(update, rules) + update[middle_index] + else + 0 + end + end + end + + def part_two + sum = 0 + bad_updates = @input.filter { |update, rules| !good_update?(update, rules) } + bad_updates.each do |update, rules| + good_update = update.sort do |a, b| + case + when rules.include?([a, b]) + 1 + when rules.include?([b, a]) + -1 + else + 0 + end + end + + sum += good_update[(good_update.size / 2).ceil] + end + + sum + end + end + + def self.solve(input_file_path = File.join(__dir__, 'input.txt')) + input_string = File.read(input_file_path) + parsed_input = Puzzle.parse_input(input_string) + puzzle = Puzzle.new(parsed_input) + + puts ""Day05.1 Solution: #{puzzle.part_one}"" + puts ""Day05.2 Solution: #{puzzle.part_two}"" + end + end +end + +if __FILE__ == $PROGRAM_NAME + AdventOfCode2024::Day05.solve +end",ruby +537,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates? + +Your puzzle answer was 4766. + +--- Part Two --- + +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. + +For each of the incorrectly-ordered updates, use the page ordering rules to put the page numbers in the right order. For the above example, here are the three incorrectly-ordered updates and their correct orderings: + +75,97,47,61,53 becomes 97,75,47,61,53. +61,13,29 becomes 61,29,13. +97,13,75,29,47 becomes 97,75,47,29,13. +After taking only the incorrectly-ordered updates and ordering them correctly, their middle page numbers are 47, 29, and 47. Adding these together produces 123. + +Find the updates which are not in the correct order. What do you get if you add up the middle page numbers after correctly ordering just those updates?",6257,"# Read and parse the input file +raw_rules, updates = File.read(""input.txt"").strip.split(""\n\n"") +rules = raw_rules.split(""\n"").map { |line| line.split(""|"").map(&:to_i) } +updates = updates.split(""\n"").map { |line| line.split("","").map(&:to_i) } + +# Function to check if an update follows the rules +def follows_rules(update, rules) + idx = {} + update.each_with_index { |num, i| idx[num] = i } + + rules.each do |a, b| + if idx.key?(a) && idx.key?(b) && idx[a] >= idx[b] + return [false, 0] + end + end + return [true, update[update.length / 2]] +end + +# Function to sort the update based on the rules +def sort_correctly(update, rules) + my_rules = rules.select { |a, b| update.include?(a) && update.include?(b) } + + # Use a Hash with a default value of 0 for in-degree calculation + indeg = Hash.new(0) + + my_rules.each { |a, b| indeg[b] += 1 } + + ans = [] + while ans.length < update.length + update.each do |x| + next if ans.include?(x) + if indeg[x] <= 0 + ans << x + my_rules.each { |a, b| indeg[b] -= 1 if a == x } + end + end + end + + ans +end + +# Variable to store the final result +ans = 0 + +# Process each update +updates.each do |update| + valid, middle = follows_rules(update, rules) + if valid + next + end + + seq = sort_correctly(update, rules) + ans += seq[seq.length / 2] +end + +# Output the result +puts ans",ruby +538,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates? + +Your puzzle answer was 4766. + +--- Part Two --- + +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. + +For each of the incorrectly-ordered updates, use the page ordering rules to put the page numbers in the right order. For the above example, here are the three incorrectly-ordered updates and their correct orderings: + +75,97,47,61,53 becomes 97,75,47,61,53. +61,13,29 becomes 61,29,13. +97,13,75,29,47 becomes 97,75,47,29,13. +After taking only the incorrectly-ordered updates and ordering them correctly, their middle page numbers are 47, 29, and 47. Adding these together produces 123. + +Find the updates which are not in the correct order. What do you get if you add up the middle page numbers after correctly ordering just those updates?",6257,"file = File.open(""input.txt"") +file_data = file.readlines.map(&:chomp) +rules = {} +updates = [] +getting_rules = true +file_data.each_with_index do |line, i| + if line.include?("","") + getting_rules = false + end + if getting_rules + line_rule = line.split(""|"").map{|v| v.to_i} + if rules[line_rule[0]].nil? + rules[line_rule[0]] = [] + end + rules[line_rule[0]] << line_rule[1] + elsif + updates << line.split("","").map{|v| v.to_i} + end +end + +def page_should_be_ahead(rules, page, rest) + rest.each do |other| + rule = rules[other] + if rule != nil && rule.include?(page) + return false + end + end + return true +end + +def sort_according_to_rules(update, rules) + if update.length < 2 + return update + end + correct_index = -1 + update.length.times do |i| + page = update[i] + rest = update.dup.tap{|a| a.delete_at(i)} + if page_should_be_ahead(rules, page, rest) + correct_index = i + break + end + end + tail = update.dup.tap{|a| a.delete_at(correct_index)} + return [update[correct_index], *sort_according_to_rules(tail, rules)] +end + +correct_updates = 0 +incorrect_sorted_updates = 0 +updates.each do |update| + updates_ok = true + update.length.times do |i| + page = update[i] + + unless page_should_be_ahead(rules, page, update.drop(i+1)) + updates_ok = false + break + end + end + if updates_ok + correct_updates += update[update.length/2] + elsif + #sort the update numbers and then get middle + sorted = sort_according_to_rules(update, rules) + incorrect_sorted_updates += sorted[sorted.length/2] + end +end +puts(""correct_updates:"") +puts(correct_updates) + +puts(""incorrect_updates (sorted):"") +puts(incorrect_sorted_updates)",ruby +539,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. + +The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. + +The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. + +Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. + +The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. + +For example: + +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 +The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) + +The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. + +To get the printers going as soon as possible, start by identifying which updates are already in the right order. + +In the above example, the first update (75,47,61,53,29) is in the right order: + +75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. +47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. +61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). +53 is correctly fourth because it is before page number 29 (53|29). +29 is the only page left and so is correctly last. +Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. + +The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. + +The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. + +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. + +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. + +For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. + +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. + +Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates? + +Your puzzle answer was 4766. + +--- Part Two --- + +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. + +For each of the incorrectly-ordered updates, use the page ordering rules to put the page numbers in the right order. For the above example, here are the three incorrectly-ordered updates and their correct orderings: + +75,97,47,61,53 becomes 97,75,47,61,53. +61,13,29 becomes 61,29,13. +97,13,75,29,47 becomes 97,75,47,29,13. +After taking only the incorrectly-ordered updates and ordering them correctly, their middle page numbers are 47, 29, and 47. Adding these together produces 123. + +Find the updates which are not in the correct order. What do you get if you add up the middle page numbers after correctly ordering just those updates?",6257,"def fix_update(order, update) + valid = true + restricted = [] + + update.each_with_index do |item, i| + restricted.each do |record| + if record[1].include?(item) + valid = false + update[i], update[record[0]] = update[record[0]], update[i] + break + end + end + + if order.has_key?(item) + restricted << [i, order[item]] + end + end + + if !valid + return fix_update(order, update) + end + + update +end + +order = {} +updates = [] + +File.open(""input.txt"", ""r"") do |f| + read_mode = 0 + f.each_line do |line| + if line == ""\n"" + read_mode = 1 + next + end + + if read_mode == 0 + parts = line.split(""|"") + key = parts[1].to_i + value = parts[0].to_i + order[key] ||= [] + order[key] << value + elsif read_mode == 1 + parts = line.split("","") + updates << parts.map(&:to_i) + end + end +end + +total = 0 +updates.each do |update| + valid = true + restricted = [] + + update.each_with_index do |item, i| + restricted.each do |record| + if record[1].include?(item) + valid = false + break + end + end + + if order.has_key?(item) + restricted << [i, order[item]] + end + end + + if !valid + update = fix_update(order, update) + total += update[update.length / 2] + end +end + +puts total",ruby +540,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"DIRECTIONS = [[-1, 0], [0, 1], [1, 0], [0, -1]] + +def turn_right(x) + (x + 1) % 4 +end + +def main + fopen = File.open(""data.txt"", ""r"") + obstacles = Set.new + visited = Set.new + direction = 0 + pos = [0, 0] + + i = -1 + fopen.each_line do |line| + i += 1 + line.strip! + j = -1 + line.each_char do |c| + j += 1 + if c == ""#"" + obstacles.add([i, j]) + elsif c == ""^"" + pos = [i, j] + visited.add(pos) + end + end + end + + max_pos = i + + loop do + if obstacles.include?([pos[0] + DIRECTIONS[direction][0], pos[1] + DIRECTIONS[direction][1]]) + direction = turn_right(direction) + end + pos = [pos[0] + DIRECTIONS[direction][0], pos[1] + DIRECTIONS[direction][1]] + if pos[0] < 0 || pos[0] > max_pos || pos[1] < 0 || pos[1] > max_pos + break + end + visited.add(pos) + end + + puts visited.size +end + +main",ruby +541,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"def get_next_pos(pos, direction) + case direction + when 'v' + return [pos[0] + 1, pos[1]] + when '^' + return [pos[0] - 1, pos[1]] + when '<' + return [pos[0], pos[1] - 1] + else + return [pos[0], pos[1] + 1] + end +end + +def get_next_direction(direction) + case direction + when 'v' + return '<' + when '<' + return '^' + when '^' + return '>' + else + return 'v' + end +end + +# Read grid from input file +grid = File.readlines('input.txt').map { |line| line.strip.chars } + +visited = Set.new +n_rows = grid.length +n_cols = grid[0].length + +# Find the starting position and direction +pos = nil +direction = nil +n_rows.times do |i| + n_cols.times do |j| + if ['v', '^', '<', '>'].include?(grid[i][j]) + pos = [i, j] + direction = grid[i][j] + break + end + end + break if pos +end + +# Traverse the grid and record visited positions +while pos[0].between?(0, n_rows - 1) && pos[1].between?(0, n_cols - 1) + visited.add(pos) + next_pos = get_next_pos(pos, direction) + + if next_pos[0].between?(0, n_rows - 1) && next_pos[1].between?(0, n_cols - 1) + if grid[next_pos[0]][next_pos[1]] == '#' + direction = get_next_direction(direction) + next_pos = pos + end + end + + pos = next_pos +end + +# Output the number of visited positions +puts visited.size",ruby +542,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"def get_unique_positions(grid) + n = grid.length + m = grid[0].length + guard = [0, 0] + dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]] + dir_index = 0 + + # Find the initial guard position and direction + for i in 0...n + for j in 0...m + case grid[i][j] + when ""^"" + guard = [i, j] + dir_index = 0 + when "">"" + guard = [i, j] + dir_index = 1 + when ""v"" + guard = [i, j] + dir_index = 2 + when ""<"" + guard = [i, j] + dir_index = 3 + end + end + end + + next_pos = guard + unique_positions = 0 + + while next_pos[0] >= 0 && next_pos[0] < n && next_pos[1] >= 0 && next_pos[1] < m + next_pos = [guard[0] + dirs[dir_index][0], guard[1] + dirs[dir_index][1]] + + if next_pos[0] < 0 || next_pos[0] >= n || next_pos[1] < 0 || next_pos[1] >= m + break + end + + if grid[guard[0]][guard[1]] != ""X"" + unique_positions += 1 + grid[guard[0]] = grid[guard[0]][0...guard[1]] + ""X"" + grid[guard[0]][guard[1] + 1..-1] + end + + if grid[next_pos[0]][next_pos[1]] == ""#"" + dir_index = (dir_index + 1) % 4 + next_pos = [guard[0] + dirs[dir_index][0], guard[1] + dirs[dir_index][1]] + end + + guard = next_pos + end + + unique_positions += 1 + grid[guard[0]] = grid[guard[0]][0...guard[1]] + ""X"" + grid[guard[0]][guard[1] + 1..-1] + + return unique_positions +end + +# Main program +if __FILE__ == $0 + # Open file 'day6-1.txt' in read mode + File.open('input.txt', 'r') do |f| + grid = f.readlines.map(&:strip) + puts ""Number of unique positions: #{get_unique_positions(grid)}"" + end +end",ruby +543,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +class Grid + attr_reader :initial_grid, :initial_position, :initial_direction, + :current_grid, :current_position, :current_direction + + def initialize(input) + @initial_grid = input.map { |line| line.split('') } + + input.each_index do |row| + col = input[row].index('^') + next unless col + + @initial_position = [row, col] + @initial_direction = :up + break + end + + reset_current + end + + def reset_current + @current_direction = initial_direction.dup + @current_grid = initial_grid.map(&:dup) + visit(*initial_position) + end + + def create_map + loop do + break if off_grid?(*next_position) + + if obstacle?(*next_position) + turn + else + visit(*next_position) + end + end + end + + def obstacle?(row, col) + current_grid[row][col] == '#' + end + + def off_grid?(row, col) + row.negative? || row >= current_grid.size || + col.negative? || col >= current_grid[0].size + end + + def next_position + row, col = current_position + + case current_direction + when :up then row -= 1 + when :down then row += 1 + when :left then col -= 1 + when :right then col += 1 + end + + [row, col] + end + + def visit(row, col) + current_grid[row][col] = 'X' + @current_position = [row, col] + end + + TURNS = { + up: :right, + right: :down, + down: :left, + left: :up + }.freeze + + def turn + @current_direction = TURNS[current_direction] + end + + def print + current_grid.each { |line| puts line.join('') } + end + + def visit_count + current_grid.flatten.count('X') + end +end + +grid = Grid.new(input) +grid.create_map + +puts ""Answer: #{grid.visit_count}""",ruby +544,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"class Direction + UP = [""^"", [-1, 0]] + DOWN = [""v"", [1, 0]] + LEFT = [""<"", [0, -1]] + RIGHT = ["">"", [0, 1]] + + def self.all_directions + [UP, DOWN, LEFT, RIGHT] + end + + def self.next(direction) + case direction + when UP then RIGHT + when RIGHT then DOWN + when DOWN then LEFT + when LEFT then UP + end + end + + def self.next_pos(direction, pos) + [pos[0] + direction[1][0], pos[1] + direction[1][1]] + end +end + +def pretty_print(matrix, visited, pos, direction) + matrix.each_with_index do |row, i| + row.each_with_index do |cell, j| + if [i, j] == pos + print direction[0] + elsif visited.include?([i, j]) + print ""X"" + elsif cell + print ""#"" + else + print ""."" + end + end + print ""\n"" + end +end + +def in_bounds(pos, matrix) + pos[0] >= 0 && pos[0] < matrix.length && pos[1] >= 0 && pos[1] < matrix[0].length +end + +# Read input and process the grid +matrix = [] +visited = Set.new +pos = [0, 0] +direction = Direction::UP + +File.open(""input.txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + line.strip.chars.each_with_index do |char, j| + if char == ""#"" + matrix[i] ||= [] + matrix[i][j] = true + else + matrix[i] ||= [] + matrix[i][j] = false + end + + if char == ""^"" + pos = [i, j] + end + end + end + + pretty_print(matrix, visited, pos, direction) + + # Start moving and visiting + while in_bounds(pos, matrix) + visited.add(pos) + + next_pos = Direction.next_pos(direction, pos) + if !in_bounds(next_pos, matrix) + break + end + + if matrix[next_pos[0]][next_pos[1]] # wall + direction = Direction.next(direction) + next_pos = Direction.next_pos(direction, pos) + end + pos = next_pos + end +end + +puts visited.size",ruby +545,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + +Your puzzle answer was 4890. + +--- Part Two --- + +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. + +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. + +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. + +Option one, put a printing press next to the guard's starting position: + +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. + +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"def get_next_pos(pos, direction) + case direction + when 'v' then [pos[0] + 1, pos[1]] + when '^' then [pos[0] - 1, pos[1]] + when '<' then [pos[0], pos[1] - 1] + else [pos[0], pos[1] + 1] + end +end + +def get_next_direction(direction) + case direction + when 'v' then '<' + when '<' then '^' + when '^' then '>' + else 'v' + end +end + +def is_loop(grid, pos, direction) + n_rows = grid.size + n_cols = grid[0].size + visited_with_dir = Set.new + + while pos[0].between?(0, n_rows - 1) && pos[1].between?(0, n_cols - 1) + return true if visited_with_dir.include?([pos, direction]) + + visited_with_dir.add([pos, direction]) + next_pos = get_next_pos(pos, direction) + + if next_pos[0].between?(0, n_rows - 1) && next_pos[1].between?(0, n_cols - 1) + if grid[next_pos[0]][next_pos[1]] == '#' + direction = get_next_direction(direction) + next_pos = pos + end + end + + pos = next_pos + end + + false +end + +grid = File.readlines('input.txt', chomp: true).map(&:chars) + +n_rows = grid.size +n_cols = grid[0].size + +pos = nil +direction = nil + +n_rows.times do |i| + n_cols.times do |j| + if %w[v ^ < >].include?(grid[i][j]) + pos = [i, j] + direction = grid[i][j] + break + end + end + break if pos +end + +loop_ct = 0 + +n_rows.times do |i| + n_cols.times do |j| + if grid[i][j] == '.' + grid[i][j] = '#' + loop_ct += 1 if is_loop(grid, pos, direction) + grid[i][j] = '.' + end + end +end + +puts loop_ct",ruby +546,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + +Your puzzle answer was 4890. + +--- Part Two --- + +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. + +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. + +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. + +Option one, put a printing press next to the guard's starting position: + +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. + +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"#!/usr/bin/env ruby + +@map = File.open('input.txt') + .readlines + .map(&:chomp) + .map { |l| l.chars} + +@height = @map.length +@width = @map.first.length + +@starting_row = @map.find_index { |l| l.index('^') } +@starting_col = @map[@starting_row].index('^') + +# Sanity check +puts ""Starting at #{@starting_row}, #{@starting_col}"" + +@directions = { + ""^"" => [-1, 0], + ""V"" => [1, 0], + "">"" => [0, 1], + ""<"" => [0, -1] +}.freeze + +@rotations = { + ""^"" => "">"", + ""V"" => ""<"", + "">"" => ""V"", + ""<"" => ""^"" +}.freeze + +def cycle_detect(map) + row = @starting_row + col = @starting_col + + movements = Array.new(@height) { Array.new(@width) { Set.new } } + is_cycle = false + + loop do + guard = map[row][col] + + if movements[row][col].include? guard + is_cycle = true + break + end + + movements[row][col].add guard + + # puts ""#{row}, #{col}, #{guard}"" + d_row, d_col = @directions[guard] + # puts d_row, d_col + + break if row+d_row < 0 || col+d_col < 0 || row+d_row >= @height || col+d_col >= @width + + dest = map[row+d_row][col+d_col] + + if dest != '#' + map[row][col] = 'X' + row += d_row + col += d_col + map[row][col] = guard + else + map[row][col] = @rotations[guard] + end + + end + + return is_cycle +end + +test_map = @map.map(&:dup) +test_map[14][16] = '#' +cycle_detect(test_map) + +# puts cycle_detect(@map.map(&:dup)) +cycles = 0 +@height.times do |row| + puts ""checking row #{row}"" + @width.times do |col| + next if row == @starting_row && col == @starting_col + # puts "" checking col #{col}"" + map = @map.map(&:dup) + map[row][col] = '#' + cycles += 1 if cycle_detect(map) + end +end + +puts ""#{cycles} cycles"" + +# puts ""\n\nEnding position: #{row}, #{col}"" +# puts @map.flat_map { |l| l.select { |c| c == 'X' }}.length",ruby +547,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + +Your puzzle answer was 4890. + +--- Part Two --- + +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. + +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. + +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. + +Option one, put a printing press next to the guard's starting position: + +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. + +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"require 'set' + +module AdventOfCode2024 + module Day06 + class Puzzle + attr_accessor :input + + def initialize(input) + @input = input + end + + def self.parse_input(input_string) + lines = input_string.split(""\n"") + width = lines.size + @input = {} + + width.times do |y| + width.times do |x| + @input[Complex(x,y)] = lines[y][x] + end + end + + @input + end + + def turn(dir) + case dir + when '^' then '>' + when '>' then 'v' + when 'v' then '<' + when '<' then '^' + end + end + + # Walk from position pos in direction dir. + def walk(pos, dir) + case dir + when '^' then Complex(pos.real, pos.imag - 1) + when '>' then Complex(pos.real + 1, pos.imag) + when 'v' then Complex(pos.real, pos.imag + 1) + when '<' then Complex(pos.real - 1, pos.imag) + end + end + + def patrol + pos, dir = @input.find { |k,v| ['^'].include? v } + start = pos + last = nil + hit = [].to_set + count = 0 + + loop do + if @input[pos].nil? + count = @input.count { |k,v| v == 'X' } + break + elsif ['#', 'O'].include? @input[pos] + if hit.include? [pos, dir] + count = -1 + break + end + hit.add([pos, dir]) + dir = turn(dir) + pos = walk(last, dir) + else + @input[pos] = 'X' + last = pos + pos = walk(pos, dir) + end + end + + # reset guard + @input[start] = '^' + + return count + end + + def part_one + patrol + end + + def part_two + # use x's from part one as possible spots to place o's + o_pos = (@input.filter { |k,v| v == 'X' }).keys + + # reset map + @input.each { |k,v| @input[k] = '.' if ['X', 'O'].include? v } + + # brute force + loops = 0 + o_pos.each_with_index do |pos, i| + @input[pos] = 'O' + loops += 1 if patrol.negative? + + # reset map + @input.each { |k,v| @input[k] = '.' if ['X', 'O'].include? v } + end + + loops + end + end + + def self.solve(input_file_path = File.join(__dir__, 'input.txt')) + input_string = File.read(input_file_path) + parsed_input = Puzzle.parse_input(input_string) + puzzle = Puzzle.new(parsed_input) + + puts ""Day06.1 Solution: #{puzzle.part_one}"" + puts ""Day06.2 Solution: #{puzzle.part_two}"" + end + end +end + +if __FILE__ == $PROGRAM_NAME + AdventOfCode2024::Day06.solve +end",ruby +548,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + +Your puzzle answer was 4890. + +--- Part Two --- + +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. + +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. + +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. + +Option one, put a printing press next to the guard's starting position: + +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. + +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"require 'set' + +# Read input file +input_data = File.read(""input.txt"").strip +raw_map = input_data.split(""\n"") +matrixed = raw_map.map { |row| row.strip.chars } + +class Direction + UP = :up + RIGHT = :right + DOWN = :down + LEFT = :left + + def self.turn_right(dir) + case dir + when UP then RIGHT + when RIGHT then DOWN + when DOWN then LEFT + when LEFT then UP + end + end +end + +class Position + attr_accessor :x, :y + + def initialize(x, y) + @x = x + @y = y + end + + def next_pos(direction) + case direction + when Direction::UP then Position.new(@x - 1, @y) + when Direction::RIGHT then Position.new(@x, @y + 1) + when Direction::DOWN then Position.new(@x + 1, @y) + when Direction::LEFT then Position.new(@x, @y - 1) + end + end +end + +class Guardian + attr_accessor :pos, :dir, :walks, :current_walk, :repeated_walks, :last_steps + + def initialize(pos, dir) + @pos = pos + @dir = dir + @walks = Set.new + @current_walk = [] + @repeated_walks = 0 + @last_steps = [] + end + + def turn_right + @dir = Direction.turn_right(@dir) + walk = @current_walk.dup + @current_walk.clear + if @walks.include?(walk) + @repeated_walks += 1 + end + @walks.add(walk) unless walk.empty? + end + + def take_step + @pos = @pos.next_pos(@dir) + @current_walk << [@pos.x, @pos.y] + end +end + +class Action + TURN = :turn + STEP = :step + OUT = :out +end + +class Map + attr_accessor :map, :guardian + + def initialize(matrix) + @map = matrix + @guardian = find_guardian + end + + def find_guardian + @map.each_with_index do |row, i| + row.each_with_index do |col, j| + if col == ""^"" + @map[i][j] = ""X"" + return Guardian.new(Position.new(i, j), Direction::UP) + end + end + end + nil + end + + def is_open?(pos) + return [false, Action::OUT] unless on_map?(pos) + return [true, Action::STEP] if [""X"", "".""].include?(@map[pos.x][pos.y]) + + [false, Action::TURN] + end + + def on_map?(pos) + pos.x >= 0 && pos.x < @map.length && pos.y >= 0 && pos.y < @map[0].length + end + + def mark_visited(pos) + @map[pos.x][pos.y] = ""X"" + end + + def count_visited + @map.flatten.count { |col| col == ""X"" } + end +end + +def check_loop(map, iter, total) + go_on = true + last_action = [] + loop_detected = false + reason = """" + + while go_on + curr_pos = map.guardian.pos + next_pos = map.guardian.pos.next_pos(map.guardian.dir) + is_open, action = map.is_open?(next_pos) + + if is_open + map.guardian.take_step + map.mark_visited(curr_pos) + elsif action == Action::TURN + map.guardian.turn_right + elsif action == Action::OUT + go_on = false + end + + last_action.shift if last_action.count(action) > 2 + last_action << action + + if map.guardian.repeated_walks >= 2 + go_on = false + loop_detected = true + reason = ""2 repeated walks"" + elsif last_action == [Action::TURN, Action::TURN, Action::TURN] + go_on = false + loop_detected = true + reason = ""3 turns in a row"" + end + end + + puts ""Iteration #{iter}/#{total}"" + loop_detected +end + +possible_obstacles = [] +matrixed.each_with_index do |row, i| + row.each_with_index do |col, j| + possible_obstacles << [i, j] if col == ""."" + end +end + +cont = 0 +possible_obstacles.each_with_index do |obs, i| + matrix_copy = raw_map.map { |row| row.strip.chars } + matrix_copy[obs[0]][obs[1]] = ""#"" + m = Map.new(matrix_copy) + + next if m.guardian.nil? + + cont += 1 if check_loop(m, i + 1, possible_obstacles.size) +end + +puts cont",ruby +549,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. + +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + +You start by making a map (your puzzle input) of the situation. For example: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. + +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + +Your puzzle answer was 4890. + +--- Part Two --- + +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. + +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. + +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. + +Option one, put a printing press next to the guard's starting position: + +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: + +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. + +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"def get_positions(data) + # Define movement directions: [row_offset, col_offset] + directions = [[-1, 0], [0, 1], [1, 0], [0, -1]] + direction_idx = 0 + positions = Set.new + curr_pos = nil + + # Find the initial position of the guard ('^') + data.each_with_index do |row, row_idx| + col_idx = row.index(""^"") + if col_idx + curr_pos = [row_idx, col_idx] + break + end + end + + total_steps = 0 + while true + next_row = curr_pos[0] + directions[direction_idx][0] + next_col = curr_pos[1] + directions[direction_idx][1] + + # If out of bounds, break the loop + break if next_row.negative? || next_row >= data.size || next_col.negative? || next_col >= data[0].size + + # If hitting an obstacle ('#'), turn right + if data[next_row][next_col] == ""#"" + direction_idx = (direction_idx + 1) % 4 + next + end + + # Detect possible infinite loop + return Set.new if total_steps >= 15_000 + + curr_pos = [next_row, next_col] + positions.add(curr_pos) + total_steps += 1 + end + positions +end + +def get_obstructions(data) + obstructions = 0 + + data.each_with_index do |row, row_idx| + row.each_with_index do |cell, col_idx| + next if [""^"", ""#""].include?(cell) + + data[row_idx][col_idx] = ""#"" + obstructions += 1 if get_positions(data).empty? + data[row_idx][col_idx] = ""."" + end + end + + obstructions +end + +def main + puzzle = [] + File.foreach(""input.txt"", chomp: true) do |line| + break if line.empty? + + puzzle << line.chars + end + + puts ""Amount of distinct positions: #{get_positions(puzzle).size}"" + puts ""Amount of possible places for obstructions to put guard in a loop: #{get_obstructions(puzzle)}"" +end + +main",ruby +550,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"lines = [] + +lines = File.readlines('input.txt').map(&:strip) + +def is_possible(line) + split_line = line.split(': ') + total = split_line[0] + values = split_line[1].strip.split + + perm_arr = ['+', 'x'] + + perms = perm_arr.repeated_permutation(values.length - 1) + + perms.each do |perm| + temp_tot = values[0].to_i + (values.length - 1).times do |i| + if perm[i] == '+' + temp_tot = (temp_tot + values[i + 1].to_i) + else + temp_tot = (temp_tot * values[i + 1].to_i) + end + end + return true if temp_tot == total.to_i + end + false +end + +total_result = 0 +lines.each do |line| + total_result += line.split(':')[0].to_i if is_possible(line) +end + +puts ""The total calibration result is #{total_result}""",ruby +551,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) +input = File.read(file_path) + +equations = input.split(""\n"").map { |line| [line.split("": "")[0].to_i, line.split("": "")[1].split("" "").map(&:to_i)] } + +sum = 0 + +equations.each do |equation| + result = equation[0] + possible_results = [] + equation[1].each do |num| + if possible_results.empty? + possible_results << num + else + new_possible_results = [] + possible_results.each do |result| + new_possible_results << result + num + new_possible_results << result * num + end + possible_results = new_possible_results + end + end + + sum += result if possible_results.include?(result) +end + +puts sum",ruby +552,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +class Node + include Enumerable + + attr_accessor :value, :left, :right + + def initialize(value) + @value = value + end + + def each(&block) + left.each(&block) if left + block.call(self) + right.each(&block) if right + end + + def <=>(other_node) + value <=> other_node.value + end + + def leaf? + left.nil? && right.nil? + end + + def to_s + value + end +end + +class Equation + attr_reader :test_value, :root + + def initialize(input) + parts = input.split(':') + @test_value = parts.first.strip.to_i + + operands = parts.last.strip.split(' ').map(&:to_i) + build_tree(operands) + end + + def build_tree(operands) + @root = Node.new(operands.first) + + operands[1..].each do |operand| + leaves = root.select(&:leaf?) + + leaves.each do |node| + sum = node.value + operand + node.left = Node.new(sum) if sum <= test_value + + product = node.value * operand + node.right = Node.new(product) if product <= test_value + end + end + end + + def valid? + root.any? { |node| node.value == test_value } + end + + def to_s + ""#{test_value}: #{root.map(&:to_s).join(' ')}"" + end +end + +equations = input.map { |line| Equation.new(line) } +answer = equations.select(&:valid?).map(&:test_value).sum + +puts ""Answer: #{answer}""",ruby +553,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"def solve + def traverse(sum, remainders, result) + return true if sum == result + return false if sum > result || remainders.empty? + + first, *rest = remainders + traverse(sum + first, rest, result) || traverse(sum * first, rest, result) + end + + File.readlines('inputs/7').sum do |line| + result_str, numbers_str = line.split(':') + result = result_str.strip.to_i + sum, *remainder = numbers_str.strip.split.map(&:to_i) + + traverse(sum, remainder, result) ? result : 0 + end +end + +puts solve",ruby +554,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"def is_valid(nums, target) + if nums.size == 1 + return nums.first == target + end + x = nums.pop + + return is_valid(nums.dup, target - x) || (target % x == 0 && is_valid(nums.dup, target / x)) +end + +sum = 0 + +File.open('input.txt').each do |line| + res = line.split("":"") + target = res[0].to_i + nums = res[1].split("" "").map(&:to_i) + + sum += target if is_valid(nums, target) +end + +puts sum",ruby +555,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result? + +Your puzzle answer was 1298103531759. + +--- Part Two --- + +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. + +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. + +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: + +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. + +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"data = File.read(""data/day_7.txt"").lines.map(&:strip) + +equations = data.map do |line| + line.split +end + +def part_1(equations) + total = 0 + equations.each do |equation| + target = equation[0].chomp("":"").to_i + operands = equation[1..-1].map(&:to_i) + sums_so_far = [] + operands.each do |operand| + if sums_so_far.empty? + sums_so_far << operand + next + end + + new_sums = [] + sums_so_far.each do |sum| + next if sum > target + new_sums << sum + operand + new_sums << sum * operand + end + sums_so_far = new_sums + end + total += target if sums_so_far.include?(target) + end + total +end + +def part_2(equations) + total = 0 + equations.each do |equation| + target = equation[0].chomp("":"").to_i + operands = equation[1..-1].map(&:to_i) + sums_so_far = [] + operands.each do |operand| + if sums_so_far.empty? + sums_so_far << operand + next + end + + new_sums = [] + sums_so_far.each do |sum| + next if sum > target + new_sums << sum + operand + new_sums << sum * operand + new_sums << (sum.to_s + operand.to_s).to_i + end + sums_so_far = new_sums + end + total += target if sums_so_far.include?(target) + end + total +end + +p ""Part 1 : #{part_1(equations)}"" +p ""Part 2 : #{part_2(equations)}""",ruby +556,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result? + +Your puzzle answer was 1298103531759. + +--- Part Two --- + +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. + +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. + +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: + +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. + +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"#! /usr/bin/env ruby + +CONCAT_OPERATOR = :| +OPERATORS = [CONCAT_OPERATOR, :+, :*].freeze + +def generate_operators(operators_count) + OPERATORS.repeated_permutation(operators_count) +end + +def valid_equation?(eq_parts, result) + puts ""eq_parts: #{eq_parts.inspect}"" + operators_count = eq_parts.size - 1 + + generate_operators(operators_count).each do |operators| + # Evaluate the equation with the operators + parts = eq_parts.dup + eq_result = parts.shift + parts.each do |part| + operator = operators.shift + eq_result = if operator == CONCAT_OPERATOR + (eq_result.to_s + part.to_s).to_i + else + eq_result.send(operator, part) + end + + # Since the operators can only increase the result, + # we can stop early if we've already exceeded the expected result value part way through + break if eq_result > result + end + + # Stop if we found a valid combination of operators + return true if eq_result == result + end + + false +end + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file) + +sum = 0 +lines.each do |line| + result, eq_parts = line.split(':').map(&:strip) + eq_parts = eq_parts.split(' ').map(&:strip).map(&:to_i) + result = result.to_i + + sum += result if valid_equation?(eq_parts, result) +end + +puts ""sum: #{sum}""",ruby +557,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result? + +Your puzzle answer was 1298103531759. + +--- Part Two --- + +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. + +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. + +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: + +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. + +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"file = File.open(""input.txt"") +file_data = file.readlines.map(&:chomp) +equations = [] + +file_data.each do |line| + answer, inputs = line.split("":"") + equations << {:a => answer.to_i, :e => inputs.split("" "").map{|l| l.to_i}} +end + +def test_eq(e,o) + q = e[0] + o.split("""").each_with_index do |op,i| + if op == ""+"" + q += e[i+1] + elsif op == ""*"" + q *= e[i+1] + else + #concat op + q = ""#{q}#{e[i+1]}"".to_i + end + end + return q +end + +def op_comb(len) + if len <= 1 + return [""+"", ""*"", ""|""] + end + last_len = op_comb(len-1) + new_ones = [] + last_len.each do |last| + new_ones << ""*#{last}"" + new_ones << ""+#{last}"" + new_ones << ""|#{last}"" + end + return new_ones +end + +len_to_op_combs = {} + +def valid_eq(eq, combs) + combs.each do |comb| + if test_eq(eq[:e], comb) == eq[:a] + return comb + end + end + return nil +end + + +total_sum = 0 +equations.each do |eq| + test_values_len = eq[:e].length - 1 + if len_to_op_combs[test_values_len].nil? + len_to_op_combs[test_values_len] = op_comb(test_values_len) + end + + is_valid_eq = valid_eq(eq, len_to_op_combs[test_values_len]) + + if !is_valid_eq.nil? + total_sum += eq[:a] + puts(""valid combo: #{is_valid_eq} for eq"") + puts(eq.inspect) + end + +end +puts(total_sum)",ruby +558,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result? + +Your puzzle answer was 1298103531759. + +--- Part Two --- + +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. + +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. + +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: + +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. + +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"require 'benchmark' + +def is_valid(nums, target) + if nums.size == 1 + return nums.first == target + end + + a = nums.shift + b = nums.shift + + is_valid(nums.dup.unshift((a.to_s + b.to_s).to_i), target) || is_valid(nums.dup.unshift(a + b), target) || is_valid(nums.dup.unshift(a * b), target) +end + +puts Benchmark.measure { + +sum = 0 + +File.open(ARGV[0]).each do |line| + res = line.split("":"") + target = res[0].to_i + nums = res[1].split("" "").map(&:to_i) + + sum += target if is_valid(nums, target) +end + +puts sum + +}",ruby +559,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? + +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. + +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). + +For example: + +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result? + +Your puzzle answer was 1298103531759. + +--- Part Two --- + +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. + +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. + +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: + +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. + +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"require 'set' + +module AdventOfCode2024 + module Day07 + class Puzzle + attr_accessor :input + + def initialize(input) + @input = input + end + + def self.parse_input(input_string) + eqs = {} # test_val -> remaining numbers + lines = input_string.split(""\n"") + lines.each do |line| + test_val, remaining = line.split(':') + eqs[test_val.to_i] = remaining.strip.split(' ').map(&:to_i) + end + + eqs + end + + def part_one + sum = 0 + ops = ['*', '+'] + @input.each do |k,v| + ops.repeated_permutation(v.size - 1) do |o| + try = v[0] + + v[1..].each_with_index do |num, i| + case o[i] + when '*' + try = try * num + when '+' + try = try + num + end + end + + if k == try + sum += try + break + end + end + end + + sum + end + + def part_two + sum = 0 + pos_ops = ['*', '+', '|'] # possible operators + @input.each do |k,v| + pos_ops.repeated_permutation(v.size - 1) do |ops| + try = v[0] + + v[1..].each_with_index do |num, i| + case ops[i] + when '|' + try = [try, num].join('').to_i + when '*' + try.nil? ? try = num : try *= num + when '+' + try.nil? ? try = num : try += num + end + end + + if try == k + sum += try + break + end + end + end + + sum + end + end + + def self.solve(input_file_path = File.join(__dir__, 'input.txt')) + input_string = File.read(input_file_path) + parsed_input = Puzzle.parse_input(input_string) + puzzle = Puzzle.new(parsed_input) + + puts ""Day07.1 Solution: #{puzzle.part_one}"" + puts ""Day07.2 Solution: #{puzzle.part_two}"" + end + end +end + +if __FILE__ == $PROGRAM_NAME + AdventOfCode2024::Day07.solve +end",ruby +560,2024,8,1,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"#! /usr/bin/env ruby +# frozen_string_literal: true + +require 'set' + +#------------------------------------------------------------------------------ +Point = Data.define(:x, :y) do + def to_s + ""[#{x}, #{y}]"" + end + + def +(other) + Point.new(x + other.x, y + other.y) + end + + def -(other) + Point.new(x - other.x, y - other.y) + end + + def distance(other) + (x - other.x).abs + (y - other.y).abs + end + + def vector(other) + Point.new(other.x - x, other.y - y) + end +end + +#------------------------------------------------------------------------------ +class Map + def initialize(lines) + @lines = lines + end + + def width + @lines.first.size + end + + def height + @lines.size + end + + def cell(point) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] + end + + def set(point, value) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] = value + end + + def each_point + 0.upto(height - 1) do |y| + 0.upto(width - 1) do |x| + yield Point.new(x, y) + end + end + end + + def to_s + @lines.join(""\n"") + end + + def inspect + result = <<~MAP + Map #{width}x#{height}: + #{to_s} + MAP + result + end +end + +#------------------------------------------------------------------------------ +input_file = ""input.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +map = Map.new(lines) + +# Collect antennas by type +antennas_by_type = Hash.new { |h, k| h[k] = [] } +map.each_point do |point| + antenna_type = map.cell(point) + antennas_by_type[antenna_type] << point if antenna_type != '.' +end + +anti_points = Set.new + +antennas_by_type.each do |antenna_type, antennas| + antennas.combination(2).each do |antenna1, antenna2| + vector = antenna1.vector(antenna2) + + anti_point1 = antenna2 + vector + anti_point2 = antenna1 - vector + + anti_points.add(anti_point1) if map.cell(anti_point1) + anti_points.add(anti_point2) if map.cell(anti_point2) + end +end + +puts ""Anti-point count: #{anti_points.size}"" + +# 381 - correct",ruby +561,2024,8,1,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) +input = File.read(file_path) + +antenas = {} +max_x = 0 +max_y = 0 + +input.split(""\n"").map(&:chars).each_with_index do |line, i| + line.each_with_index do |char, j| + max_x = j if j > max_x + next if char == '.' + + antenas[char] = [[i, j]] if antenas[char].nil? + antenas[char] << [i, j] if !antenas[char].nil? + end + max_y = i if i > max_y +end + +antinodes = {} +antenas.each do |key, value| + value.combination(2) do |f, s| + next if f == s + x1 = f[0] + y1 = f[1] + x2 = s[0] + y2 = s[1] + + dx = x2 - x1 + dy = y2 - y1 + + sx1 = x1-dx + sy1 = y1-dy + + sx2 = x2+dx + sy2 = y2+dy + + antinodes[[sx1, sy1]] = true if sx1 >= 0 && sx1 <= max_x && sy1 >= 0 && sy1 <= max_y + antinodes[[sx2, sy2]] = true if sx2 >= 0 && sx2 <= max_x && sy2 >= 0 && sy2 <= max_y + + end +end + +puts antinodes.size",ruby +562,2024,8,1,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +class Map + attr_reader :grid, :antennas + + def initialize(lines) + @grid = lines.map(&:chars) + @antennas = {} + + grid.each_index do |row| + grid[row].each_index do |col| + signal = grid[row][col] + next if signal == '.' + + antennas[signal] ||= [] + antennas[signal] << [row, col] + end + end + end + + def compute_antinodes + antennas.each_value do |positions| + positions.each_index do |i| + positions.each_index do |j| + next if i == j + + diff_row = positions[i].first - positions[j].first + diff_col = positions[i].last - positions[j].last + + mark_antinode(positions[i].first + diff_row, positions[i].last + diff_col) + mark_antinode(positions[j].first - diff_row, positions[j].last - diff_col) + end + end + end + end + + def antinode_count + grid.map { |row| row.select { |signal| signal == '#' } }.flatten.size + end + + def print_map + grid.each do |row| + puts row.join('') + end + end + + private + + def mark_antinode(row, col) + return if row.negative? || row >= grid.size + return if col.negative? || col >= grid[0].size + + grid[row][col] = '#' + end +end + +map = Map.new(input) +map.compute_antinodes + +puts ""Answer: #{map.antinode_count}""",ruby +563,2024,8,1,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"lines = IO.readlines(ARGV[0]) +MAX_X = lines.first.chomp.size - 1 +MAX_Y = lines.size - 1 +antennas = {} +nodes = {} + +lines.each_with_index do |line, y| + line.chars.each_with_index do |char, x| + if /\w/.match?(char) + antennas[char] ||= [] + antennas[char] << [x, y] + end + end +end + +def in_bounds(x, y) + x >= 0 && x <= MAX_X && y >= 0 && y <= MAX_Y +end + +antennas.each do |char, coordinates| + coordinates.combination(2).each do |a, b| + dx = b[0] - a[0] + dy = b[1] - a[1] + x1 = a[0] - dx + y1 = a[1] - dy + x2 = b[0] + dx + y2 = b[1] + dy + nodes[[x1, y1]] = true if in_bounds(x1, y1) + nodes[[x2, y2]] = true if in_bounds(x2, y2) + end +end + +puts nodes.count",ruby +564,2024,8,1,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"input = open('./input.txt').readlines.map(&:strip) + +def draw_map(locations, mx, my) + map = [] + my.times do + map << Array.new(mx) {'.'} + end + locations.each do | loc | + map[loc[1]][loc[0]] = ""#"" + end + map.each do | line | + puts line.join + end +end + +# Setup dict and maxes +my = input.length +mx = input[0].length +location_dict = {} +[(""a""..""z""), (""A""..""Z""), (""0""..""9"")].each do | signals | + signals.each do | signal | + location_dict[signal] = [] + end +end + +# Read in locations and populate dict +input.each_with_index do | line, y | + line.split('').each_with_index do | loc, x | + unless loc == '.' + location_dict[loc] << [x, y] + end + end +end + +puts location_dict + +antinodes = [] + +location_dict.each_key do | key | + antennae = location_dict[key] + if antennae.count > 0 + antennae.each do | main | + antennae.each do | other | + unless main == other + dx, dy = (other[0] - main[0]), (other[1] - main[1]) + + an1x, an1y = main[0] - dx, main[1] - dy + an2x, an2y = other[0] + dx, other[1] + dy + + antinodes << [an1x, an1y] if an1x < mx and an1x >= 0 and an1y < my and an1y >= 0 + antinodes << [an2x, an2y] if an2x < mx and an2x >= 0 and an2y < my and an2y >= 0 + end + end + end + end +end + +puts antinodes.uniq.count + +draw_map(antinodes.uniq, mx, my)",ruby +565,2024,8,2,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? + +Your puzzle answer was 332. + +--- Part Two --- + +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. + +Whoops! + +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). + +So, these three T-frequency antennas now create many antinodes: + +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. + +The original example now has 34 antinodes, including the antinodes that appear on every antenna: + +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +class Map + attr_reader :grid, :antennas + + def initialize(lines) + @grid = lines.map(&:chars) + @antennas = {} + + grid.each_index do |row| + grid[row].each_index do |col| + signal = grid[row][col] + next if signal == '.' + + antennas[signal] ||= [] + antennas[signal] << [row, col] + end + end + end + + def compute_antinodes + antennas.each_value do |positions| + positions.each_index do |i| + positions.each_index do |j| + next if i == j + + diff_row = positions[i].first - positions[j].first + diff_col = positions[i].last - positions[j].last + + mark_antinode(*positions[i]) + mark_antinode(*positions[j]) + + anti_row, anti_col = positions[i].clone + + loop do + break unless mark_antinode(anti_row, anti_col) + + anti_row += diff_row + anti_col += diff_col + end + + anti_row, anti_col = positions[j].clone + + loop do + break unless mark_antinode(anti_row, anti_col) + + anti_row -= diff_row + anti_col -= diff_col + end + end + end + end + end + + def antinode_count + grid.map { |row| row.select { |signal| signal == '#' } }.flatten.size + end + + def print_map + grid.each do |row| + puts row.join('') + end + end + + private + + def mark_antinode(row, col) + return if row.negative? || row >= grid.size + return if col.negative? || col >= grid[0].size + + grid[row][col] = '#' + end +end + +map = Map.new(input) +map.compute_antinodes + +puts ""Answer: #{map.antinode_count}""",ruby +566,2024,8,2,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? + +Your puzzle answer was 332. + +--- Part Two --- + +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. + +Whoops! + +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). + +So, these three T-frequency antennas now create many antinodes: + +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. + +The original example now has 34 antinodes, including the antinodes that appear on every antenna: + +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"require 'set' + +def parse_input + frequency = Hash.new { |h, key| h[key] = [] } + + input = File.readlines('inputs/8', chomp: true) + rows = input.size + cols = input[0].size + + input.each_with_index do |line, row| + line.each_char.with_index do |char, col| + if char != '.' + frequency[char] << [row, col] + end + end + end + + [frequency, rows, cols] +end + +def solve + frequency, rows, cols = parse_input + antinodes = Set.new + + frequency.each_value do |pairs| + pairs.combination(2) do |(x1, y1), (x2, y2) | + (0...rows).each do |x3| + (0...cols).each do |y3| + # Determinant check for collinearity + antinodes << [x3, y3] if x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2) == 0 + end + end + end + end + + antinodes.size +end + +puts solve",ruby +567,2024,8,2,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? + +Your puzzle answer was 332. + +--- Part Two --- + +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. + +Whoops! + +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). + +So, these three T-frequency antennas now create many antinodes: + +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. + +The original example now has 34 antinodes, including the antinodes that appear on every antenna: + +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"module AdventOfCode2024 + module Day08 + class Puzzle + attr_accessor :input + + def initialize(input) + @input = input + end + + def self.parse_input(input_string) + lines = input_string.split(""\n"") + width = lines.size + input = {} + + width.times do |y| + width.times do |x| + input[Complex(x,y)] = lines[y][x] + end + end + + input + end + + def display + width = @input.keys.max_by { |c| c.real }.real + height = @input.keys.max_by { |c| c.imag }.imag + (0..height).each do |y| + (0..width).each do |x| + print input[Complex(x,y)] + end + puts + end + end + + def part_one + freqs = @input.values.filter { |v| v != '.' }.uniq + antennas = {} + freqs.each { |f| antennas[f] = @input.filter { |k,v| v == f }.keys } + antennas.each do |freq, coords| + coords.permutation(2) do |p| + a, b = p + a_b = a - b + b_a = b - a + anti_one = Complex(a.real + a_b.real, a.imag + a_b.imag) + anti_two = Complex(b.real + b_a.real, b.imag + b_a.imag) + [anti_one, anti_two].each do |anti| + @input[anti] = '#' if @input.keys.include? anti + end + end + end + + @input.count { |k,v| v.include? '#' } + end + + def part_two + @input = Puzzle.parse_input(File.read(File.join(__dir__, 'input.txt'))) + hashes = @input.filter { |k,v| v == '#' }.keys + hashes.each { |k| @input[k] = '.' } + freqs = @input.values.filter { |v| !['.', '#'].include? v }.uniq + antennas = {} + freqs.each { |f| antennas[f] = @input.filter { |k,v| v == f }.keys } + antennas.each do |freq, coords| + coords.permutation(2) do |p| + a, b = p + a_b = a - b + b_a = b - a + + [a, b].each do |pt| + if @input[pt].match?(/^[a-zA-Z\d]$/) + @input[pt] = '#' + end + end + + anti = Complex(a.real + a_b.real, a.imag + a_b.imag) + while @input.include? anti + if @input[anti].match?(/[a-zA-Z\d]/) + @input[anti] = '#' + else + @input[anti] = '#' + end + anti = Complex(anti.real + a_b.real, anti.imag + a_b.imag) + end + + anti = Complex(b.real + b_a.real, b.imag + b_a.imag) + while @input.include? anti + if @input[anti].match?(/[a-zA-Z\d]/) + @input[anti] = '#' + else + @input[anti] = '#' + end + anti = Complex(anti.real + b_a.real, anti.imag + b_a.imag) + end + end + end + + @input.count { |k,v| v.include?('#') } + end + end + + def self.solve(input_file_path = File.join(__dir__, 'input.txt')) + input_string = File.read(input_file_path) + parsed_input = Puzzle.parse_input(input_string) + puzzle = Puzzle.new(parsed_input) + + puts ""Day08.1 Solution: #{puzzle.part_one}"" + puts ""Day08.2 Solution: #{puzzle.part_two}"" + end + end +end + +if __FILE__ == $PROGRAM_NAME + AdventOfCode2024::Day08.solve +end",ruby +568,2024,8,2,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? + +Your puzzle answer was 332. + +--- Part Two --- + +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. + +Whoops! + +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). + +So, these three T-frequency antennas now create many antinodes: + +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. + +The original example now has 34 antinodes, including the antinodes that appear on every antenna: + +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"#! /usr/bin/env ruby +# frozen_string_literal: true + +require 'set' + +#------------------------------------------------------------------------------ +Point = Data.define(:x, :y) do + def to_s + ""[#{x}, #{y}]"" + end + + def +(other) + Point.new(x + other.x, y + other.y) + end + + def -(other) + Point.new(x - other.x, y - other.y) + end + + def *(scalar) + Point.new(x * scalar, y * scalar) + end + + def distance(other) + (x - other.x).abs + (y - other.y).abs + end + + def vector(other) + Point.new(other.x - x, other.y - y) + end + + def prime_vector + gcd = x.gcd(y) + Point.new(x / gcd, y / gcd) + end +end + +#------------------------------------------------------------------------------ +class Map + def initialize(lines) + @lines = lines + end + + def width + @lines.first.size + end + + def height + @lines.size + end + + def cell(point) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] + end + + def set(point, value) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] = value + end + + def each_point + 0.upto(height - 1) do |y| + 0.upto(width - 1) do |x| + yield Point.new(x, y) + end + end + end + + def to_s + @lines.join(""\n"") + end + + def inspect + result = <<~MAP + Map #{width}x#{height}: + #{to_s} + MAP + result + end +end + +#------------------------------------------------------------------------------ +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +map = Map.new(lines) + +# Collect antennas by type +antennas_by_type = Hash.new { |h, k| h[k] = [] } +map.each_point do |point| + antenna_type = map.cell(point) + antennas_by_type[antenna_type] << point if antenna_type != '.' +end + +anti_points = Set.new + +antennas_by_type.each do |antenna_type, antennas| + antennas.combination(2).each do |antenna1, antenna2| + vector = antenna1.vector(antenna2) + prime_vector = vector.prime_vector + + max_vector_repeats = [map.width / prime_vector.x, map.height / prime_vector.y].max + 0.upto(max_vector_repeats) do |i| + candidates = [ + antenna1 + prime_vector * i, + antenna2 + prime_vector * i, + antenna1 - prime_vector * i, + antenna2 - prime_vector * i + ] + + candidates.each do |candidate| + anti_points.add(candidate) if map.cell(candidate) + end + end + end +end + +puts ""Anti-point count: #{anti_points.size}"" + +# 381 - correct",ruby +569,2024,8,2,"--- Day 8: Resonant Collinearity --- + +You find yourselves on the roof of a top-secret Easter Bunny installation. + +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: + +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? + +Your puzzle answer was 332. + +--- Part Two --- + +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. + +Whoops! + +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). + +So, these three T-frequency antennas now create many antinodes: + +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. + +The original example now has 34 antinodes, including the antinodes that appear on every antenna: + +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) +input = File.read(file_path) + +antenas = {} +max_x = 0 +max_y = 0 + +input.split(""\n"").map(&:chars).each_with_index do |line, i| + line.each_with_index do |char, j| + max_x = j if j > max_x + next if char == '.' + + if antenas[char].nil? + antenas[char] = [[i, j]] + else + antenas[char] << [i, j] + end + + end + max_y = i if i > max_y +end + +antinodes = {} +antenas.each do |key, value| + value.combination(2) do |f, s| + next if f == s + x1 = f[0] + y1 = f[1] + + x2 = s[0] + y2 = s[1] + + antinodes[[x1, y1]] = true + antinodes[[x2, y2]] = true + + dx = x2 - x1 + dy = y2 - y1 + + loop do + ant1 = false + ant2 = false + + sx1 = x1-dx + sy1 = y1-dy + + sx2 = x2+dx + sy2 = y2+dy + + ant1 = true if sx1 >= 0 && sx1 <= max_x && sy1 >= 0 && sy1 <= max_y + ant2 = true if sx2 >= 0 && sx2 <= max_x && sy2 >= 0 && sy2 <= max_y + + + antinodes[[sx1, sy1]] = true if ant1 + antinodes[[sx2, sy2]] = true if ant2 + + break if !ant1 && !ant2 + + x1 = sx1 + y1 = sy1 + + x2 = sx2 + y2 = sy2 + + + end + end + +end + +p antinodes.size",ruby +570,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"#! /usr/bin/env ruby + +AocFile = Struct.new(:block_id, :length, :position, :is_moved) +EmptySpace = Struct.new(:length, :position, :is_moved) + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +disk_map = File.readlines(input_file).first.chomp + +# Render the compressed disk map into a list of file blocks +file_blocks = [] +file_id = 0 +position = 0 +empty_block = false + +disk_map.each_char do |char| + length = char.to_i + file_blocks << (empty_block ? EmptySpace.new(length, position, false) : AocFile.new(file_id, length, position, false)) + file_id += 1 unless empty_block + + empty_block = !empty_block + position += length +end + +# Defragment the disk map by moving the file blocks to the empty space +resulting_blocks = [] +last_non_moved_block_idx = file_blocks.size - 1 + +file_blocks.each do |block| + # We have reached the first moved block, which means the rest will have been moved as well + break if block.is_moved + + # Move data blocks as-is + if block.is_a?(AocFile) + resulting_blocks << block + block.is_moved = true + next + end + + # Collect enough blocks from the end of the list to fill the empty space + last_non_moved_block_idx.downto(0) do |i| + tail_block = file_blocks[i] + + if tail_block.is_moved || tail_block.is_a?(EmptySpace) || tail_block.length == 0 + last_non_moved_block_idx = i - 1 + next + end + + # The tail block fits completely in the empty space + if tail_block.length < block.length + resulting_blocks << AocFile.new(tail_block.block_id, tail_block.length, block.position, true) + tail_block.is_moved = true + block.length -= tail_block.length + block.position += tail_block.length + + last_non_moved_block_idx = i - 1 + next + end + + # The tail block fits partially in the empty space + # Create a new file block to fill the empty space + resulting_blocks << AocFile.new(tail_block.block_id, block.length, block.position, true) + + # Shorten the tail block by the same amount + tail_block.length -= block.length + tail_block.is_moved = true if tail_block.length == 0 + + # The empty space is now filled, so we can stop + block.length = 0 + block.is_moved = true + break + end +end + +# Calculate the checksum of the resulting disk map +checksum = 0 +resulting_blocks.each do |block| + 0.upto(block.length - 1) do |i| + pos = block.position + i + checksum += pos * block.block_id + end +end + +puts checksum + +# 6395800119709 - correct",ruby +571,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"input = IO.readlines(ARGV[0]).first.chomp +input.chop if input.size % 2 == 1 # get rid of any free space on the end + +arr = input.split("""").map(&:to_i) +i = 0 +j = arr.size - 1 +result = [] + +j_fileid = j / 2 +j_size = arr[j] + +while i <= j do + # fill next file + i_size = i == j ? j_size : arr[i] + i_fileid = i / 2 + while i_size > 0 + result << i_fileid + i_size -= 1 + end + + # fill free space with files from the end + i += 1 + i_size = arr[i] + while i_size > 0 do + if j_size == 0 + j -= 2 + break if j < i + j_fileid = j / 2 + j_size = arr[j] + end + result << j_fileid + i_size -= 1 + j_size -= 1 + end + i += 1 +end + +# calculate checksum +puts result.each_with_index.reduce(0) { |sum, (x, i)| sum += x*i}",ruby +572,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"#!/usr/bin/env ruby +# frozen_string_literal: true + +input = File.readlines('./input.txt').map(&:chomp) + +class DiskMap + attr_reader :original_map, :expanded_map + + def initialize(input) + @original_map = input.split('').map(&:to_i) + @expanded_map = [] + expand_map + end + + def expand_map + file_id = 0 + original_map.each_index do |i| + if i.even? + original_map[i].times { expanded_map << file_id } + file_id += 1 + else + original_map[i].times { expanded_map << nil } + end + end + end + + def compact + compacted = expanded_map.compact + expanded_map.slice!(compacted.size..) + + expanded_map.each_index do |i| + next unless expanded_map[i].nil? + + expanded_map[i] = compacted.pop + end + end + + def checksum + sum = 0 + + expanded_map.each_index do |i| + sum += (i * expanded_map[i]) + end + + sum + end + + def to_s + expanded_map.map { |e| e || '.' }.join('') + end +end + +map = DiskMap.new(input.first) +map.compact +puts ""Checksum: #{map.checksum}""",ruby +573,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"DiskFragment = Struct.new(:id, :size, :tail) + +fragments = File.read('inputs/9', chomp: true) + .chars + .each_slice(2) + .with_index + .map { |(size, tail), id| DiskFragment.new(id, size.to_i, tail.to_i) } + +disk = [] +while fragment = fragments.shift + disk.push(*Array.new(fragment.size, fragment.id)) + + while fragment.tail > 0 && !fragments.empty? + last = fragments.last + + if last.size > 0 + disk << last.id + fragment.tail -= 1 + last.size -= 1 + else + fragments.pop + end + end +end + +puts disk.each_with_index.sum { |id, index| id * index }",ruby +574,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) +input = File.read(file_path) + +#input = ""2333133121414131402"" + +files = {} +empty = [] +disk = {} + + +file = true +i = 0 +f_id = 0 +loc = 0 + +input = input.chars.map(&:to_i).each do |size| + if file + files[f_id] = {size: size, loc: [loc, loc + size -1]} + Array(loc..(loc + size - 1)).each do |l| + disk[l] = f_id + end + + file = false + f_id += 1 + else + Array(loc..(loc + size - 1)).each do |l| + empty.push(l) + disk[l] = -1 + end + + file = true + end + + loc += size + i += 1 +end + + +#print disk +defragmented = false + +files.to_a.reverse.to_h.each do |key, value| + value[:loc][1].downto(value[:loc][0]) do |l| + e = empty.shift + if e < l + disk[e] = key + disk[l] = -1 + else + defragmented = true + break + end + end + break if defragmented + + empty = (empty + value[:loc]).sort +end + +puts disk.reduce(0) {|acc, (k, v)| acc + ((v==-1?0:v) * k)}",ruby +575,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"#! /usr/bin/env ruby + +AocFile = Struct.new(:block_id, :length, :position) +EmptySpace = Struct.new(:length, :position) + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +disk_map = File.readlines(input_file).first.chomp + +# Render the compressed disk map into a list of file blocks +file_blocks = [] +file_id = 0 +position = 0 +empty_block = false + +disk_map.each_char do |char| + length = char.to_i + file_blocks << (empty_block ? EmptySpace.new(length, position) : AocFile.new(file_id, length, position)) + file_id += 1 unless empty_block + + empty_block = !empty_block + position += length +end + +# Separate the empty blocks from the filled blocks to make it easier to iterate over them +empty_blocks = file_blocks.select { |block| block.is_a?(EmptySpace) } +filled_blocks = file_blocks.select { |block| block.is_a?(AocFile) } + +# Walk filled blocks from the last one and try to move each of them into the first empty block where they'd fit +filled_blocks.reverse_each do |block| + # Look for the first empty block that fits it + empty_blocks.each do |empty_block| + next if empty_block.length < block.length + break if empty_block.position > block.position + + # Move the block to the empty block + block.position = empty_block.position + + # Truncate the empty block and move it to the right + empty_block.length -= block.length + empty_block.position += block.length + break + end +end + +# It does not matter in which order we calculate the checksum, +# but let's order the blocks by their position for easier debugging +resulting_blocks = filled_blocks.sort_by { |block| block.position } + +# Calculate the checksum of the resulting disk map +checksum = 0 +resulting_blocks.each do |block| + 0.upto(block.length - 1) do |i| + pos = block.position + i + checksum += pos * block.block_id + end +end + +puts checksum + +# 8560706397829 - too high +# 6418529470362 - correct",ruby +576,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) +input = File.read(file_path) + +#input = ""2333133121414131402"" + +files = {} +empty = {} + +reverse_empty = {} +disk = {} + + +file = true +i = 0 +f_id = 0 +loc = 0 + +input = input.chars.map(&:to_i).each do |size| + if file + files[f_id] = {size: size, loc: [loc, loc + size -1]} + Array(loc..(loc + size - 1)).each do |l| + disk[l] = f_id + end + + file = false + f_id += 1 + else + empty[loc] = {size: size, loc: [loc, loc + size -1]} + reverse_empty[loc + size - 1] = {size: size, loc: [loc, loc + size -1]} + Array(loc..(loc + size - 1)).each do |l| + disk[l] = -1 + end + + file = true + end + + loc += size + i += 1 +end + + +defragmented = false + +files.to_a.reverse.to_h.each do |key, value| + empty = empty.sort.to_h + e = empty.select {|k, v| v[:size] >= value[:size] && k < value[:loc][0]}.sort.first + next if e.nil? + + # write the file + i = e[0] + value[:size].times do + disk[i] = key + i += 1 + end + + # remove the empty space + empty.delete(e[0]) + reverse_empty.delete(e[0] + value[:size] - 1) + + # empty disk space + value[:loc][1].downto(value[:loc][0]) do |l| + disk[l] = -1 + end + + if e[1][:size] > value[:size] + empty[e[0] + value[:size]] = {size: e[1][:size] - value[:size], loc: [e[0] + value[:size], e[1][:loc][1]]} + reverse_empty[e[1][:loc][1]] = {size: e[1][:size] - value[:size], loc: [e[1][:loc][1],e[0] + value[:size]]} + end + + new_key = value[:loc][0] + new_size = value[:size] + l1 = value[:loc][0] + l2 = value[:loc][1] + + if !empty[l2+1].nil? + ek = l2+1 + el1 = empty[l2+1][:loc][0] + el2 = empty[l2+1][:loc][1] + es = empty[l2+1][:size] + + l2 = el2 + new_size += es + empty.delete(ek) + reverse_empty.delete(el2) + end + + if !reverse_empty[l1-1].nil? + ek = l1-1 + el1 = reverse_empty[l1-1][:loc][0] + el2 = reverse_empty[l1-1][:loc][1] + es = reverse_empty[l1-1][:size] + + l1 = el1 + new_size += es + new_key = l1 + empty.delete(el1) + reverse_empty.delete(ek) + end + + empty[new_key] = {size: new_size, loc: [l1, l2]} + reverse_empty[l2] = {size: new_size, loc: [l1, l2]} + +end + +puts disk.reduce(0) {|acc, (k, v)| acc + ((v==-1?0:v) * k)}",ruby +577,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"require 'benchmark' + +MyFile = Data.define(:id, :index, :size) + +class MyDisk + attr_accessor :blocks, :files + + def self.create(str) + disk = MyDisk.new + fi = 0 + str.chars.map(&:to_i).each_with_index do |size, i| + f_id = i % 2 == 0 ? i/2 : nil + disk.blocks += [f_id] * size + disk.files << MyFile.new(f_id, fi, size) if !f_id.nil? + fi += size + end + disk + end + + def initialize + @blocks = [] + @files = [] + end + + def defrag + files.reverse.each do |file| + index = find_space(file) + move_file_to_index(file, index) if !index.nil? + end + end + + def move_file_to_index(file, index) + (0..file.size-1).each do |i| + blocks[index + i] = file.id # write file to new location + blocks[file.index + i] = nil # null out previous location + end + end + + def find_space_size(index) + size = 0 + while blocks[index].nil? && index < blocks.size do + size += 1 + index += 1 + end + size + end + + def find_next_space(index, end_index) + i = blocks[index..end_index].index(&:nil?) + + if i.nil? + [nil, 0] + else + [index + i, find_space_size(index + i)] + end + end + + def find_space(file) + i = 0 + loop do + next_space, space_size = find_next_space(i, file.index) + break if next_space.nil? + + return next_space if space_size >= file.size + i = next_space + space_size + end + nil + end + + def checksum + blocks.each_with_index.reduce(0) { |sum, (f_id, i)| sum + (f_id ? f_id * i : 0) } + end +end + +input = IO.readlines(ARGV[0]).first.chomp + +disk = MyDisk.create(input) + +puts Benchmark.measure { + +disk.defrag +puts disk.checksum + +}",ruby +578,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"file = File.open(""input.txt"") +file_data = file.readlines.map(&:chomp) +file_blocks = [] +hole_indices = {} +file_data[0].split("""").each_with_index do |char,i| + if i % 2 == 0 + file_id = i/2 + char.to_i.times do + file_blocks << file_id.to_i + end + else + if char.to_i > 0 + if hole_indices[char.to_i].nil? + hole_indices[char.to_i] = [] + end + hole_indices[char.to_i] << file_blocks.length + end + char.to_i.times do + file_blocks << ""."" + end + + end +end + +def get_file_id_to_size(blockz) + file_id_to_size = Hash.new(0) + blockz.each do |b| + file_id_to_size[b] += 1 + end +end + + +starting_blocks = get_file_id_to_size(file_blocks) + +#puts(""file blocks is"") +puts(file_blocks.map{|b| b.to_s}.inspect) +#puts(""holes is"") +#puts(hole_indices.inspect) +#puts(hole_indices.inspect) + +def chksum(blocks) + checksum = 0 + blocks.each_with_index do |bl, i| + if bl != '.' + checksum += (bl*i) + end + end + return checksum +end + +back_i = file_blocks.length - 1 +front_i = 0 + +moved_file_ids= {} +while back_i >= 0 + if file_blocks[back_i] == '.' || moved_file_ids[file_blocks[back_i]] + back_i-=1 + else + size = 0 + file_id = file_blocks[back_i] + moved_file_ids[file_id] = true + while file_blocks[back_i - size] == file_id + size += 1 + end + index = -1 + file_blocks.length.times do |i| + size_at_point = 0 + fits = false + while i + size_at_point < back_i && file_blocks[i + size_at_point] == '.' + size_at_point += 1 + if size_at_point >= size + fits = true + break + end + end + if fits + index = i + break + end + end + if index > 0 + #put the file at index + # then clear the space where the file was before + size.times do |s| + file_blocks[back_i - s] = '.' + file_blocks[index + s] = file_id + end + end + #puts(file_blocks.map{|b| b.to_s}.inspect) + back_i -= size + end +end + +#puts(file_blocks.inspect) +puts(""part two:"") +puts(chksum(file_blocks))",ruby +579,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. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"data = File.read(""input.txt"").lines.map(&:strip) + +$data = data.first.chars.map(&:to_i) + +$open_representation = [] +$nil_locations_and_sizes = [] +$file_locations_and_sizes = [] + +file = true +current_id = 0 +$data.each do |num| + if file + $file_locations_and_sizes << [$open_representation.size, num, current_id] + num.times do + $open_representation << current_id + end + current_id += 1 + file = false + else + $nil_locations_and_sizes << [$open_representation.size, num] + num.times do + $open_representation << nil + end + file = true + end +end + +$nil_locations_and_sizes.reject! { |a| a[1] <= 0 } +$file_locations_and_sizes.reject! { |a| a[1] <= 0 } +original_open_representation = $open_representation.dup + +def part_1 + nil_indexes = [] + $open_representation.each_with_index do |num, index| + if num.nil? + nil_indexes << index + end + end + + nil_indexes.each do |index| + last_el = nil + loop do + last_el = $open_representation.pop + break if !last_el.nil? + end + $open_representation[index] = last_el + end + $open_representation.compact! + + checksum = 0 + $open_representation.each_with_index do |num, index| + checksum += num*index + end + checksum +end + +def part_2 + final_file_locations_and_sizes = [] + $file_locations_and_sizes.reverse.each do |file| + file_size = file[1] + location = nil + nil_index = nil + nil_locations_and_sizes_local = $nil_locations_and_sizes.dup + nil_locations_and_sizes_local.each_with_index do |nil_location, index| + if nil_location[1] >= file_size && nil_location[0] < file[0] + location = nil_location[0] + nil_index = index + break + end + end + if location + final_file_locations_and_sizes << [location, file_size, file[2]] + $nil_locations_and_sizes[nil_index] = [nil_locations_and_sizes_local[nil_index][0] + file_size, nil_locations_and_sizes_local[nil_index][1] - file_size] + else + final_file_locations_and_sizes << [file[0], file[1], file[2]] + end + $nil_locations_and_sizes.reject! { |a| a[0] > file[0] } + $nil_locations_and_sizes.reject! { |a| a[1] <= 0 } + end + + + different_checksum = 0 + final_file_locations_and_sizes.each do |file| + file_location_start = file[0] + file_size = file[1] + file_id = file[2] + + for i in file_location_start..file_location_start+file_size-1 + different_checksum += file_id*i + end + end + different_checksum +end + +p ""Part 1: #{part_1}"" +p ""Part 2: #{part_2}""",ruby +580,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"require 'set' + +def parse_input + map = {} + peaks = Set.new + trailheads = Set.new + + input = File.readlines('inputs/10', chomp: true) + rows = input.length + cols = input[0].length + + input.each_with_index do |line, row| + line.strip.chars.each_with_index do |char, col| + height = char.to_i + map[[row,col]] = height + + peaks << [row,col] if height == 9 + trailheads << [row,col] if height == 0 + end + end + + [map, rows, cols, peaks, trailheads] +end + +def out_of_bounds?(row, col, rows, cols) + row < 0 || row >= rows || col < 0 || col >= cols +end + +def solve + map, rows, cols, peaks, trailheads = parse_input + solution = Hash.new { |hash, key| hash[key] = Set.new } + + traverse = ->(row, col, prev_value, peak) do + return if out_of_bounds?(row, col, rows, cols) + + if map[[row,col]] == prev_value - 1 + solution[[row,col]] << peak + + traverse.call(row - 1, col, prev_value - 1, peak) + traverse.call(row + 1, col, prev_value - 1, peak) + traverse.call(row, col + 1, prev_value - 1, peak) + traverse.call(row, col - 1, prev_value - 1, peak) + end + end + + # Call traverse for each peak + peaks.each { |pos| traverse.call(*pos, 9 + 1, pos) } + + # Sum the solution for each trailhead + trailheads.each.sum { |pos| solution[pos].size } +end + +puts solve",ruby +581,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"@m = File.read(""input.txt"").split(""\n"").map{_1.chars.map(&:to_i)} +trailheads = [] + +def reachablenines(x,y) + v=@m[y][x] + width = @m[0].size + height = @m.size + if v==9 + return [x,y] + else + res = [] + neighbours = [[1,0],[0,-1],[-1,0],[0,1]].map{|c| c.zip([x,y]).map(&:sum)} + neighbours.select{|x,y|x>=0 && y>=0 && x= topographic_map[0].length || y >= topographic_map.length + return + end + + if !prev_x.nil? && !prev_y.nil? && (topographic_map[y][x] - topographic_map[prev_y][prev_x]) != 1 + return + end + + if topographic_map[y][x] == 9 && trailends[""#{x},#{y}""].nil? + trailends[""#{x},#{y}""] = path + return + end + + + walk_trails(x+1, y, x, y, topographic_map, path.dup, trailends, debug) + walk_trails(x-1, y, x, y, topographic_map, path.dup, trailends, debug) + walk_trails(x, y+1, x, y, topographic_map, path.dup, trailends, debug) + walk_trails(x, y-1, x, y, topographic_map, path.dup, trailends, debug) +end + +def find_trailhead_scores(topographic_map, trailhead_starts, debug=false) + scores = 0 + + trailhead_starts.each do |trailhead_start| + trailends = {} + walk_trails(trailhead_start[:x], trailhead_start[:y], nil, nil, topographic_map, [], trailends, debug) + puts ""#{trailhead_start} => #{trailends.keys}"" if debug + scores += trailends.keys.length + end + + scores +end + +def process(file_name, debug=false) + + topographic_map = [] + trailhead_starts = [] + + File.foreach(ARGV[0]).with_index do |line, index| + row = line.strip.chars.map(&:to_i) + row.each_index.select { |i| row[i] == 0 }.each do |i| + trailhead_starts.push({ x: i, y: index }) + end + topographic_map.push(row) + end + + if debug + puts ""topographic_map:"" + topographic_map.each do |row| + puts row.join + end + puts ""trailhead_starts: #{trailhead_starts.join("", "")}"" + end + + puts ""Sum of the scores of all trailheads: #{find_trailhead_scores(topographic_map, trailhead_starts, debug)}"" + +end + + +process(input_array[0], !input_array.at(1).nil?)",ruby +583,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"#! /usr/bin/env ruby + +class Map + def initialize(lines) + @lines = lines.map(&:chars).map { |line| line.map(&:to_i) } + end + + def width + @lines.first.size + end + + def height + @lines.size + end + + def cell(point) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] + end + + def set(point, value) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] = value + end + + def each_point + 0.upto(height - 1) do |y| + 0.upto(width - 1) do |x| + yield Point.new(x, y) + end + end + end + + def to_s + @lines.map(&:join).join(""\n"") + end + + def inspect + result = <<~MAP + Map #{width}x#{height}: + #{to_s} + MAP + result + end +end + +#------------------------------------------------------------------------------ +Point = Data.define(:x, :y) do + def to_s + ""[#{x}, #{y}]"" + end + + def +(other) + Point.new(x + other.x, y + other.y) + end + + def -(other) + Point.new(x - other.x, y - other.y) + end + + def distance(other) + (x - other.x).abs + (y - other.y).abs + end + + def vector(other) + Point.new(other.x - x, other.y - y) + end +end + +module Direction + UP = Point.new(0, -1) + DOWN = Point.new(0, +1) + LEFT = Point.new(-1, 0) + RIGHT = Point.new(+1, 0) + + ALL = [UP, DOWN, LEFT, RIGHT] +end + +#------------------------------------------------------------------------------ +# Returns a set of peaks reachable from the given starting point +def peaks_reachable_from(map, start) + elevation = map.cell(start) + return Set.new unless elevation + return Set.new([start]) if elevation == 9 + + result = Set.new + Direction::ALL.each do |dir| + if map.cell(start + dir) == elevation + 1 + result += peaks_reachable_from(map, start + dir) + end + end + + result +end + +#------------------------------------------------------------------------------ +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +map = Map.new(lines) +puts map.inspect + +# Find all trailheads (points with a value of 0) +trailheads = [] +map.each_point do |point| + trailheads << point if map.cell(point) == 0 +end +puts ""Found #{trailheads.size} trailheads"" +puts trailheads.inspect + +# For each trailhead, find the number of 9s that could be reached from it +total_score = 0 +trailheads.each do |trailhead| + puts ""Trailhead at #{trailhead}"" + peaks = peaks_reachable_from(map, trailhead) + score = peaks.size + puts ""- Score: #{score}"" + total_score += score +end + +puts ""Total score: #{total_score}"" + +# 744 - correct",ruby +584,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + + +def can_go_up(i, j, value, grid) + return false if i == 0 + return false if grid[i - 1][j] != value + 1 + return true +end + +def can_go_down(i, j, value, grid) + return false if i == grid.length - 1 + return false if grid[i + 1][j] != value + 1 + return true +end + +def can_go_left(i, j, value, grid) + return false if j == 0 + return false if grid[i][j - 1] != value + 1 + return true +end + +def can_go_right(i, j, value, grid) + return false if j == grid[0].length - 1 + return false if grid[i][j + 1] != value + 1 + return true +end + +input = File.read(file_path) +input = input.split(""\n"").map{|x| x.chars.map(&:to_i)} + +trailheads = {} + +input.each_with_index do |row, i| + row.each_with_index do |cell, j| + if cell == 0 + trailheads[[i, j]] = [{position: [i, j], value: 0}] + end + end +end + +trailheads.each do |key, val| + i, j = key + while true + new_vals = [] + val.each do |possible_path| + i, j = possible_path[:position] + value = possible_path[:value] + if value == 9 + new_vals.push({position: [i, j], value: 9}) + next + end + + if can_go_up(i, j, value, input) + new_vals.push({position: [i - 1, j], value: value + 1}) + end + if can_go_down(i, j, value, input) + new_vals.push({position: [i + 1, j], value: value + 1}) + end + if can_go_left(i, j, value, input) + new_vals.push({position: [i, j - 1], value: value + 1}) + end + if can_go_right(i, j, value, input) + new_vals.push({position: [i, j + 1], value: value + 1}) + end + end + + val = new_vals.uniq + + if val.empty? || val.all?{|x| x[:value] == 9} + trailheads[key] = val + break + end + end +end + + +puts trailheads.select{|k, v| !v.empty? }.map{|k, v| v.size}.sum",ruby +585,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"data = File.read(""data/day_10.txt"").lines.map(&:strip) + +$data = data.map(&:chars) +$data = $data.map { |row| row.map(&:to_i)} + +$trailheads = [] + +$data.each_with_index do |row, x| + row.each_with_index do |cell, y| + if cell == 0 + $trailheads << [x, y] + end + end +end + +def part_1 + total = 0 + $trailheads.each do |trailhead| + trailhead_score = 0 + possible = [trailhead] + for i in 1..9 + new_possible = [] + possible.each do |point| + next_from_point = (find_next_possible(point,i)) + new_possible += next_from_point + end + possible = new_possible.uniq + end + trailhead_score = possible.length + total += trailhead_score + end + total +end + +def find_next_possible(point, i) + x, y = point + possible = [] + if x + 1 < $data.length + possible << [x + 1, y] if $data[x + 1][y] == i + end + if x - 1 >= 0 + possible << [x - 1, y] if $data[x - 1][y] == i + end + if y + 1 < $data[0].length + possible << [x, y + 1] if $data[x][y + 1] == i + end + if y - 1 >= 0 + possible << [x, y - 1] if $data[x][y - 1] == i + end + possible +end + +class Path + attr_accessor :ending_point, :starting_point, :points + + def initialize(starting_point) + @starting_point = starting_point + @ending_point = starting_point + @points = [starting_point] + end + + def new_from_points(points) + starting_point = points[0] + path = Path.new(starting_point) + for i in 1..points.length - 1 + path.add_point(points[i]) + end + path + end + + def add_point(point) + @points << point + @ending_point = point + end + + def to_s + ""Path from #{@starting_point} to #{@ending_point}: #{@points}"" + end +end + +def part_2 + total = 0 + $trailheads.each do |trailhead| + paths_from_trailhead = [Path.new(trailhead)] + trailhead_rating = 0 + possible = [trailhead] + for i in 1..9 + new_possible = [] + possible.each do |point| + next_from_point = (find_next_possible(point,i)) + new_possible += next_from_point + + new_paths = [] + for path in paths_from_trailhead + if path.ending_point == point + for next_point in next_from_point + new_path = path.new_from_points(path.points) + new_path.add_point(next_point) + new_paths << new_path + end + end + end + paths_from_trailhead += new_paths + end + paths_from_trailhead.reject! { |path| path.points.length < i+1 } + possible = new_possible.uniq + end + paths_from_trailhead.reject! { |path| path.points.length < 10 } + path_set = Set.new + paths_from_trailhead.each do |path| + path_set << path.points + end + trailhead_rating = path_set.length + total += trailhead_rating + end + total +end + +p ""Part 1: #{part_1}"" +start_time = Time.now +p ""Part 2: #{part_2}"" +end_time = Time.now +p ""Time: #{end_time - start_time}""",ruby +586,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"#! /usr/bin/env ruby + +class Map + def initialize(lines) + @lines = lines.map(&:chars).map { |line| line.map(&:to_i) } + end + + def width + @lines.first.size + end + + def height + @lines.size + end + + def cell(point) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] + end + + def set(point, value) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] = value + end + + def each_point + 0.upto(height - 1) do |y| + 0.upto(width - 1) do |x| + yield Point.new(x, y) + end + end + end + + def to_s + @lines.map(&:join).join(""\n"") + end + + def inspect + result = <<~MAP + Map #{width}x#{height}: + #{to_s} + MAP + result + end +end + +#------------------------------------------------------------------------------ +Point = Data.define(:x, :y) do + def to_s + ""[#{x}, #{y}]"" + end + + def +(other) + Point.new(x + other.x, y + other.y) + end + + def -(other) + Point.new(x - other.x, y - other.y) + end + + def distance(other) + (x - other.x).abs + (y - other.y).abs + end + + def vector(other) + Point.new(other.x - x, other.y - y) + end +end + +module Direction + UP = Point.new(0, -1) + DOWN = Point.new(0, +1) + LEFT = Point.new(-1, 0) + RIGHT = Point.new(+1, 0) + + ALL = [UP, DOWN, LEFT, RIGHT] +end + +#------------------------------------------------------------------------------ +def trailhead_score(map, start) + elevation = map.cell(start) + return 0 unless elevation + return 1 if elevation == 9 + + result = 0 + Direction::ALL.each do |dir| + result += trailhead_score(map, start + dir) if map.cell(start + dir) == elevation + 1 + end + + result +end + +#------------------------------------------------------------------------------ +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +map = Map.new(lines) +puts map.inspect + +# Find all trailheads (points with a value of 0) +trailheads = [] +map.each_point do |point| + trailheads << point if map.cell(point) == 0 +end +puts ""Found #{trailheads.size} trailheads"" +puts trailheads.inspect + +# For each trailhead, find the number of 9s that could be reached from it +total_score = 0 +trailheads.each do |trailhead| + puts ""Trailhead at #{trailhead}"" + score = trailhead_score(map, trailhead) + puts ""- Score: #{score}"" + total_score += score +end + +puts ""Total score: #{total_score}"" + +# 1651 - correct",ruby +587,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + + +def can_go_up(i, j, value, grid) + return false if i == 0 + return false if grid[i - 1][j] != value + 1 + return true +end + +def can_go_down(i, j, value, grid) + return false if i == grid.length - 1 + return false if grid[i + 1][j] != value + 1 + return true +end + +def can_go_left(i, j, value, grid) + return false if j == 0 + return false if grid[i][j - 1] != value + 1 + return true +end + +def can_go_right(i, j, value, grid) + return false if j == grid[0].length - 1 + return false if grid[i][j + 1] != value + 1 + return true +end + +input = File.read(file_path) +input = input.split(""\n"").map{|x| x.chars.map(&:to_i)} + +trailheads = {} + +input.each_with_index do |row, i| + row.each_with_index do |cell, j| + if cell == 0 + trailheads[[i, j]] = [{position: [i, j], value: 0}] + end + end +end + +trailheads.each do |key, val| + i, j = key + while true + new_vals = [] + val.each do |possible_path| + i, j = possible_path[:position] + value = possible_path[:value] + if value == 9 + new_vals.push({position: [i, j], value: 9}) + next + end + + if can_go_up(i, j, value, input) + new_vals.push({position: [i - 1, j], value: value + 1}) + end + if can_go_down(i, j, value, input) + new_vals.push({position: [i + 1, j], value: value + 1}) + end + if can_go_left(i, j, value, input) + new_vals.push({position: [i, j - 1], value: value + 1}) + end + if can_go_right(i, j, value, input) + new_vals.push({position: [i, j + 1], value: value + 1}) + end + end + + val = new_vals + + if val.empty? || val.all?{|x| x[:value] == 9} + trailheads[key] = val + break + end + end +end + + +puts trailheads.select{|k, v| !v.empty? }.map{|k, v| v.size}.sum",ruby +588,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"require 'set' + +def parse_input + map = {} + peaks = Set.new + trailheads = Set.new + + input = File.readlines('inputs/10', chomp: true) + rows = input.length + cols = input[0].length + + input.each_with_index do |line, row| + line.strip.chars.each_with_index do |char, col| + height = char.to_i + map[[row,col]] = height + + peaks << [row,col] if height == 9 + trailheads << [row,col] if height == 0 + end + end + + [map, rows, cols, peaks, trailheads] +end + +def out_of_bounds?(row, col, rows, cols) + row < 0 || row >= rows || col < 0 || col >= cols +end + +def solve + map, rows, cols, peaks, trailheads = parse_input + solution = Hash.new { |hash, key| hash[key] = 0 } + + traverse = ->(row, col, prev_value) do + return if out_of_bounds?(row, col, rows, cols) + + if map[[row,col]] == prev_value - 1 + solution[[row,col]] += 1 + + traverse.call(row - 1, col, prev_value - 1) + traverse.call(row + 1, col, prev_value - 1) + traverse.call(row, col + 1, prev_value - 1) + traverse.call(row, col - 1, prev_value - 1) + end + end + + # Call traverse for each peak + peaks.each { |pos| traverse.call(*pos, 9 + 1) } + + # Sum the amount of ways to get to the peak + trailheads.sum { |trailhead| solution[trailhead] } +end + +puts solve",ruby +589,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. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"input_array = ARGV + +def walk_trails(x, y, prev_x, prev_y, topographic_map, path, trailends = {}, debug=false) + path.push ""#{x},#{y}"" + + if x < 0 || y < 0 || x >= topographic_map[0].length || y >= topographic_map.length + return + end + + if !prev_x.nil? && !prev_y.nil? && (topographic_map[y][x] - topographic_map[prev_y][prev_x]) != 1 + return + end + + if topographic_map[y][x] == 9 + trailends[""#{x},#{y}""] = [] if trailends[""#{x},#{y}""].nil? + trailends[""#{x},#{y}""] << path + return + end + + + walk_trails(x+1, y, x, y, topographic_map, path.dup, trailends, debug) + walk_trails(x-1, y, x, y, topographic_map, path.dup, trailends, debug) + walk_trails(x, y+1, x, y, topographic_map, path.dup, trailends, debug) + walk_trails(x, y-1, x, y, topographic_map, path.dup, trailends, debug) +end + +def find_trailhead_scores_and_ratings(topographic_map, trailhead_starts, debug=false) + scores = 0 + ratings = 0 + trailhead_starts.each do |trailhead_start| + trailends = {} + walk_trails(trailhead_start[:x], trailhead_start[:y], nil, nil, topographic_map, [], trailends, debug) + puts ""#{trailhead_start} => #{trailends.keys}"" if debug + ratings += trailends.values.sum(&:length) + scores += trailends.keys.length + end + + { + scores: scores, + ratings: ratings, + } +end + +def process(file_name, debug=false) + + topographic_map = [] + trailhead_starts = [] + + File.foreach(ARGV[0]).with_index do |line, index| + row = line.strip.chars.map(&:to_i) + row.each_index.select { |i| row[i] == 0 }.each do |i| + trailhead_starts.push({ x: i, y: index }) + end + topographic_map.push(row) + end + + if debug + puts ""topographic_map:"" + topographic_map.each do |row| + puts row.join + end + puts ""trailhead_starts: #{trailhead_starts.join("", "")}"" + end + + scores_and_ratings = find_trailhead_scores_and_ratings(topographic_map, trailhead_starts, debug) + puts ""Sum of the scores of all trailheads: #{scores_and_ratings[:scores]}"" + puts ""Sum of the ratings of all trailheads: #{scores_and_ratings[:ratings]}"" + +end + + +process(input_array[0], !input_array.at(1).nil?)",ruby +590,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path) + +stones = input.split("" "") + +25.times do + new_stones = [] + stones.each do |stone| + if stone == '0' + new_stones.push('1') + next + end + + + if stone.size % 2 == 0 + stone1 = stone[0..stone.size/2-1] + stone2 = stone[stone.size/2..stone.size].sub(/^0+/,'') + stone2 = '0' if stone2.nil? || stone2.empty? + + new_stones.push(stone1) + new_stones.push(stone2) + next + end + + new_stones.push((stone.to_i * 2024).to_s) + end + + stones = new_stones +end + + +puts stones.size",ruby +591,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +stones = File.read(path).split.map(&:to_i) + +def blink(stones) + new_stones = [] + stones.each do |stone| + if stone.zero? + new_stones << 1 + elsif stone.to_s.length.even? + chars = stone.to_s + new_stones << chars[0...(chars.length / 2)].to_i + new_stones << chars[(chars.length / 2)...chars.length].to_i + else + new_stones << stone * 2024 + end + end + new_stones +end + +25.times do |i| + stones = blink(stones) +end + +p stones.count",ruby +592,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 solve + # Read the stones and their counts from the input file + stones = File + .read('inputs/11', chomp: true) + .split + .map(&:to_i) + .tally + + memoize = {} + + # Define a method to transform a single stone + transform = lambda do |stone| + return [1] if stone.zero? + return [memoize[stone]] if memoize.key?(stone) + + str = stone.to_s + if str.length.even? + mid = str.length / 2 + result = [str[...mid].to_i, str[mid..].to_i] + memoize[stone] = result + result + else + result = stone * 2024 + memoize[stone] = result + [result] + end + end + + # Define a method to apply the transformation to all stones + blink = lambda do |stones| + stones.each_with_object(Hash.new(0)) do |(stone, count), result| + transform.call(stone).flatten.each { |t| result[t] += count } + end + end + + # Perform 75 transformations + 25.times { stones = blink.call(stones) } + + # Return the sum of all the stone counts + stones.values.sum +end + +puts solve",ruby +593,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,"#! /usr/bin/env ruby + +def blink(stones) + output = [] + + stones.each do |stone| + if stone == 0 + output << 1 + elsif (string_stone = stone.to_s).size.even? + s1 = string_stone[0..string_stone.size/2-1] + s2 = string_stone[string_stone.size/2..string_stone.size] + output << s1.to_i + output << s2.to_i + else + output << stone * 2024 + end + end + + output +end + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +stones = File.readlines(input_file).first.split.map(&:to_i) + +25.times do |i| + stones = blink(stones) + puts ""After #{i + 1} blinks:"" + puts ""Number of stones: #{stones.size}"" + puts +end + +# 213625 - correct",ruby +594,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,"class Day11 + def initialize() + @times = 25 + @stones = [] + end + + def read_file + i = 0 + File.open(""Day11\\input11.txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + @stones = line.split("" "").map(&:to_i) + end + end + end + + def process_stones + curr_blink = 0 + + while curr_blink < @times do + j = 0 + stones_count = @stones.length + while j <= stones_count-1 + if @stones[j] == 0 + @stones[j] = 1 + elsif @stones[j].to_s.chars.length % 2 == 0 + midpoint = @stones[j].to_s.length / 2 + splitted_number_1 = @stones[j].to_s[0...midpoint] + splitted_number_2 = @stones[j].to_s[midpoint..-1] + @stones[j] = splitted_number_1.to_i + @stones.insert(j+1, splitted_number_2.to_i) + j += 1 + stones_count += 1 + else + @stones[j] = @stones[j] * 2024 + end + j += 1 + end + curr_blink += 1 + end + end + + def get_stones_number + return @stones.length + end +end + +day11 = Day11.new() +day11.read_file +day11.process_stones +puts day11.get_stones_number",ruby +595,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,"stones={} +stones_nextstate = {} +File.read(""Day11.txt"").split.map(&:to_i).each{|i| stones[i]||=0;stones[i]+=1} +REPEATS=75 #Set to 25 for part 1 + +REPEATS.times{ + stones.each{|nr,amt| + if nr == 0 + stones_nextstate[1]||=0 + stones_nextstate[1] += amt + elsif nr.digits.size % 2 == 0 + a,b = nr.to_s[...nr.to_s.size/2].to_i,nr.to_s[nr.to_s.size/2..].to_i + stones_nextstate[a]||=0 + stones_nextstate[b]||=0 + stones_nextstate[a]+=amt + stones_nextstate[b]+=amt + else + stones_nextstate[nr*2024]||=0 + stones_nextstate[nr*2024]+=amt + end + } + + stones=stones_nextstate + stones_nextstate = {} +} +p stones.values.sum",ruby +596,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +stones = File.read(path).split.map(&:to_i) + +@memo = Hash.new +@hits = 0 + +def blink(stone) + if stone.zero? + [1] + elsif stone.to_s.length.even? + chars = stone.to_s + [chars[0...(chars.length / 2)].to_i, chars[(chars.length / 2)...chars.length].to_i] + else + [stone * 2024] + end +end + +def process(stones, remaining_steps) + return stones.count if remaining_steps.zero? + if stones.count == 1 + cached = @memo[stones.first] || Hash.new + if cached.key?(remaining_steps) + @hits += 1 + return cached[remaining_steps] + end + new_stones = blink(stones.first) + cached[remaining_steps] = process(new_stones, remaining_steps - 1) + @memo[stones.first] = cached + return cached[remaining_steps] + end + process(stones[0...1], remaining_steps) + process(stones[1...stones.count], remaining_steps) +end + +res = process(stones, 75) + +p ""values cached: #{@memo.values.sum { _1.values.count }}"" +p ""cache hits: #{@hits}"" + +p res",ruby +597,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,"def solve + # Read the stones and their counts from the input file + stones = File + .read('inputs/11', chomp: true) + .split + .map(&:to_i) + .tally + + memoize = {} + + # Define a method to transform a single stone + transform = lambda do |stone| + return [1] if stone.zero? + return [memoize[stone]] if memoize.key?(stone) + + str = stone.to_s + if str.length.even? + mid = str.length / 2 + result = [str[...mid].to_i, str[mid..].to_i] + memoize[stone] = result + result + else + result = stone * 2024 + memoize[stone] = result + [result] + end + end + + # Define a method to apply the transformation to all stones + blink = lambda do |stones| + stones.each_with_object(Hash.new(0)) do |(stone, count), result| + transform.call(stone).flatten.each { |t| result[t] += count } + end + end + + # Perform 75 transformations + 75.times { stones = blink.call(stones) } + + # Return the sum of all the stone counts + stones.values.sum +end + +puts solve",ruby +598,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,"#! /usr/bin/env ruby + +def blink(stones) + output = Hash.new(0) + + stones.each do |stone, count| + if stone == 0 + output[1] += count + elsif (string_stone = stone.to_s).size.even? + s1 = string_stone[0..string_stone.size/2-1] + s2 = string_stone[string_stone.size/2..string_stone.size] + output[s1.to_i] += count + output[s2.to_i] += count + else + output[stone * 2024] += count + end + end + + output +end + +input_file = ""input.txt"" +stones = File.readlines(input_file).first.split.map(&:to_i) + +stones = stones.inject({}) { |acc, stone| acc[stone] = 1; acc } + +75.times do |i| + stones = blink(stones) + puts ""After #{i + 1} blinks:"" + puts ""Number of stones: #{stones.values.sum}"" + puts +end + +puts stones.values.sum",ruby +599,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path) + +stones = {} +input.split("" "").each do |stone| + stones[stone] = 1 +end + +prev_stones = {'0' => ['1']} + +75.times do |i| + + new_stones = {} + stones.each do |stone, cnt| + + if prev_stones[stone] + prev_stones[stone].each do |prev_stone| + if new_stones[prev_stone] + new_stones[prev_stone] += cnt + else + new_stones[prev_stone] = cnt + end + end + next + end + + if stone.size % 2 == 0 + stone1 = stone[0..stone.size/2-1] + stone2 = stone[stone.size/2..stone.size].sub(/^0+/,'') + stone2 = '0' if stone2.nil? || stone2.empty? + + + new_stones[stone1] += cnt if new_stones[stone1] + new_stones[stone1] = cnt if new_stones[stone1].nil? + new_stones[stone2] += cnt if new_stones[stone2] + new_stones[stone2] = cnt if new_stones[stone2].nil? + + + prev_stones[stone] = [stone1, stone2] + next + end + + stone_value = (stone.to_i * 2024).to_s + new_stones[stone_value] += cnt if new_stones[stone_value] + new_stones[stone_value] = cnt if new_stones[stone_value].nil? + prev_stones[stone] = [stone_value] + end + + stones = new_stones +end + +puts stones.values.sum",ruby +600,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,"#! /usr/bin/env ruby + +#------------------------------------------------------------------------------ +Point = Data.define(:x, :y) do + def to_s + ""[#{x}, #{y}]"" + end + + def +(other) + Point.new(x + other.x, y + other.y) + end + + def -(other) + Point.new(x - other.x, y - other.y) + end + + def distance(other) + (x - other.x).abs + (y - other.y).abs + end + + def vector(other) + Point.new(other.x - x, other.y - y) + end +end + +#------------------------------------------------------------------------------ +module Direction + UP = Point.new(0, -1) + DOWN = Point.new(0, +1) + LEFT = Point.new(-1, 0) + RIGHT = Point.new(+1, 0) + + ALL = [UP, DOWN, LEFT, RIGHT] +end + +#------------------------------------------------------------------------------ +class Map + def initialize(lines) + @lines = lines + end + + def width + @lines.first.size + end + + def height + @lines.size + end + + def cell(point) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] + end + + def set(point, value) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] = value + end + + def each_point + 0.upto(height - 1) do |y| + 0.upto(width - 1) do |x| + yield Point.new(x, y) + end + end + end + + def to_s + @lines.join(""\n"") + end + + def inspect + result = <<~MAP + Map #{width}x#{height}: + #{to_s} + MAP + result + end +end + +#------------------------------------------------------------------------------ +def measure_region(region, map, point, visited) + return 0, 0 if visited.include?(point) + point_plant = map.cell(point) + return 0, 0 if point_plant != region + visited.add(point) + + area = 1 + perimeter = 0 + + Direction::ALL.each do |dir| + neighbor = point + dir + neighbor_plant = map.cell(neighbor) + + if neighbor_plant != region + perimeter += 1 + else + neighbor_area, neighbor_perimeter = measure_region(region, map, neighbor, visited) + area += neighbor_area + perimeter += neighbor_perimeter + end + end + + [area, perimeter] +end + +#------------------------------------------------------------------------------ +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +map = Map.new(lines) + +visited = Set.new +total_cost = 0 +map.each_point do |point| + next if visited.include?(point) + + region = map.cell(point) + area, perimeter = measure_region(region, map, point, visited) + total_cost += perimeter * area +end + +puts ""Total cost: #{total_cost}""",ruby +601,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 parse_input + input = File.readlines('inputs/12', chomp: true) + rows = input.size + cols = input[0].size + + [input, rows, cols] +end + +def bfs(graph, rows, cols, start, plant) + queue = [start] + visited = Set.new([start]) + + until queue.empty? + row, col = queue.shift + + neighbors = [[row - 1, col], [row + 1, col], [row, col - 1], [row, col + 1]] + neighbors.each do |r, c| + next if r < 0 || r >= rows || c < 0 || c >= cols + next if visited.include?([r,c]) || graph[r][c] != plant + + visited.add([r,c]) + queue.push([r,c]) + end + end + + visited +end + +def borders(region) + region.sum do |row, col| + neighbors = [[row - 1, col], [row + 1, col], [row, col - 1], [row, col + 1]] + neighbors.count { |neighbor| !region.include?(neighbor) } + end +end + + +def solve + garden, rows, cols = parse_input + visited = Set.new + groups = [] + + garden.each_with_index do |line, r| + line.chars.each_with_index do |char, c| + next if visited.include?([r,c]) + + group = bfs(garden, rows, cols, [r,c], char) + groups << group unless group.empty? + visited.merge(group) + end + end + + groups.sum { |group| borders(group) * group.size } +end + +puts solve",ruby +602,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +$mapped = {} + +def can_go_up(i, j, value, grid) + return false if i == 0 + return false if $mapped[[i-1,j]] + return false if grid[i - 1][j] != value + return true +end + +def can_go_down(i, j, value, grid) + return false if i == grid.length - 1 + return false if $mapped[[i+1,j]] + return false if grid[i + 1][j] != value + return true +end + +def can_go_left(i, j, value, grid) + return false if j == 0 + return false if $mapped[[i,j-1]] + return false if grid[i][j - 1] != value + return true +end + +def can_go_right(i, j, value, grid) + return false if j == grid[0].length - 1 + return false if $mapped[[i,j+1]] + return false if grid[i][j + 1] != value + return true +end + +def get_border_cnt(i,j,cell, grid) + sum = 0 + + sum += 1 if i == 0 || grid[i-1][j] != cell + sum += 1 if i == grid.length - 1 || grid[i+1][j] != cell + sum += 1 if j == 0 || grid[i][j-1] != cell + sum += 1 if j == grid[0].length - 1 || grid[i][j+1] != cell + + return sum + +end + + + +def map_area(grid, i, j, cell, new_areas = []) + $mapped[[i,j]] = true + + cu = can_go_up(i, j, cell, grid) + cd = can_go_down(i, j, cell, grid) + cl = can_go_left(i, j, cell, grid) + cr = can_go_right(i, j, cell, grid) + + border = get_border_cnt(i,j,cell,grid) + + area_data = {i: i, j: j, border: border} + new_areas.push(area_data) + + new_areas.concat(map_area(grid, i-1, j, cell)) if cu + new_areas.concat(map_area(grid, i+1, j, cell)) if cd + new_areas.concat(map_area(grid, i, j+1, cell)) if cr + new_areas.concat(map_area(grid, i, j-1, cell)) if cl + + + return new_areas +end + +input = File.read(file_path).split(""\n"").map(&:chars) + + +areas = [] +total_price = 0 + +input.each_with_index do |row, a| + row.each_with_index do |cell, b| + next if $mapped[[a,b]] + + new_area = map_area(input, a, b, cell).uniq + areas.push(new_area) + + total_price += new_area.size * new_area.map{|x| x[:border]}.sum + + end +end + +puts total_price",ruby +603,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,"class Day12 + def initialize() + @matrix = [] + @width = 0 + @height = 0 + @visited = Hash.new + @areas_register = Hash.new + @groups_matrix = [] + @sums = [] + end + + def read_file + i = 0 + File.open(""Day12\\input12.txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + chars = line.strip.chars + @matrix[i] = chars + @width = chars.length + i += 1 + @height += 1 + end + end + end + + def find_groups + for i in 0..@height-1 + for j in 0..@width-1 + if @visited.key?([i,j]) + next + else + collect_group([i,j]) + end + end + end + return @areas_register + end + + def collect_group(first_coords) + queue = [first_coords] + common_char = @matrix[first_coords[0]][first_coords[1]] + group_area = 0 + adjacent_sides_count = 0 + group_peremeter = 0 + group_coords = [] + + while !queue.empty? + coords = queue.shift + i = coords[0] + j = coords[1] + + if @visited.key?([i,j]) + next + else + if @matrix[i][j] == common_char + group_coords.push([i,j]) + adjacent_sides_count += 1 + group_area += 1 + @visited[[i,j]] = true + if i-1 >= 0 + queue.push([i-1,j]) + end + if i+1 < @height + queue.push([i+1,j]) + end + if j-1 >= 0 + queue.push([i,j-1]) + end + if j+1 < @width + queue.push([i,j+1]) + end + end + end + end + group_peremeter = (group_area * 4) - ((group_area-2)*4) + per = find_perimeter(group_coords.uniq) + @sums.push(group_area * ((group_area * 4) - (per))) + end + + def calculate_price + sum = 0 + + for s in @sums + sum += s + end + + return sum + end + + def get_coords_around(i,j) + coords = [] + + coords.push([i,j]) + + if i-1 >= 0 + coords.push([i-1,j]) + end + if i+1 < @height + coords.push([i+1,j]) + end + if j-1 >= 0 + coords.push([i,j-1]) + end + if j+1 < @width + coords.push([i,j+1]) + end + return coords + end + + def find_perimeter(vertices) + perimeter = 0 + adjacent_sides_count = 0 + + for i in 0..vertices.length-1 + for j in 0..vertices.length-1 + if i != j + if (vertices[i][0] == vertices[j][0] && vertices[i][1] == vertices[j][1]-1) || + (vertices[i][0] == vertices[j][0] && vertices[i][1] == vertices[j][1]+1) || + (vertices[i][0] == vertices[j][0]-1 && vertices[i][1] == vertices[j][1]) || + (vertices[i][0] == vertices[j][0]+1 && vertices[i][1] == vertices[j][1]) + adjacent_sides_count += 1 + end + end + end + + end + return adjacent_sides_count + end +end + + +day12 = Day12.new() +day12.read_file +puts day12.find_groups +puts day12.calculate_price",ruby +604,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +@field = File.read(path).split.map{ _1.chars } +regions = [] +@affected = Set.new + +@height = @field.count +@width = @field.first.count + +def find_region(from:) + plot = @field[from[0]][from[1]] + region = [] + stack = Set.new([from]) + visited = Set.new + while !stack.empty? + e = stack.first + stack.delete(e) + visited << e + if @field[e[0]][e[1]] == plot + region << e + @affected << e + [[e[0] + 1, e[1]], [e[0] - 1, e[1]], [e[0], e[1] + 1], [e[0], e[1] - 1]].each do |(i, j)| + if !visited.include?([i, j]) && (0...@height).include?(i) && (0...@width).include?(j) + stack << [i, j] + end + end + end + end + region +end + +(0...@height).each do |i| + (0...@width).each do |j| + next if @affected.include?([i, j]) + regions << find_region(from: [i, j]) + end +end + +def price(region) + perimeter = region.reduce(0) do |sum, (i, j)| + sum + 4 - [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]].filter { region.include?(_1) }.count + end + perimeter * region.count +end + +# regions.each { p ""A region of #{@field[_1[0][0]][_1[0][1]]} plants with price #{price(_1)}"" } + +p regions.sum { price(_1) }",ruby +605,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,"#! /usr/bin/env ruby + +#------------------------------------------------------------------------------ +Point = Data.define(:x, :y) do + def to_s + ""[#{x}, #{y}]"" + end + + def +(other) + Point.new(x + other.x, y + other.y) + end +end + +#------------------------------------------------------------------------------ +module Direction + UP = Point.new(0, -1) + DOWN = Point.new(0, +1) + LEFT = Point.new(-1, 0) + RIGHT = Point.new(+1, 0) + + ALL = [UP, DOWN, LEFT, RIGHT] +end + +#------------------------------------------------------------------------------ +class Map + def initialize(lines) + @lines = lines + end + + def width + @lines.first.size + end + + def height + @lines.size + end + + def cell(point) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] + end + + def set(point, value) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] = value + end + + def each_point + 0.upto(height - 1) do |y| + 0.upto(width - 1) do |x| + yield Point.new(x, y) + end + end + end + + def to_s + @lines.join(""\n"") + end + + def inspect + result = <<~MAP + Map #{width}x#{height}: + #{to_s} + MAP + result + end +end + +#------------------------------------------------------------------------------ +# Returns the number of different corners for the given 1x1 square on the map +def number_of_corners(region, map, point) + corners = 0 + corners += 1 if external_top_right?(region, map, point) + corners += 1 if external_bottom_right?(region, map, point) + corners += 1 if external_bottom_left?(region, map, point) + corners += 1 if external_top_left?(region, map, point) + + corners += 1 if internal_top_right?(region, map, point) + corners += 1 if internal_bottom_right?(region, map, point) + corners += 1 if internal_bottom_left?(region, map, point) + corners += 1 if internal_top_left?(region, map, point) + + corners +end + +def external_top_right?(region, map, point) + map.cell(point + Direction::UP) != region && + map.cell(point + Direction::RIGHT) != region +end + +def external_bottom_right?(region, map, point) + map.cell(point + Direction::DOWN) != region && + map.cell(point + Direction::RIGHT) != region +end + +def external_bottom_left?(region, map, point) + map.cell(point + Direction::DOWN) != region && + map.cell(point + Direction::LEFT) != region +end + +def external_top_left?(region, map, point) + map.cell(point + Direction::UP) != region && + map.cell(point + Direction::LEFT) != region +end + +# AAx +# BBA +# BBA +def internal_top_right?(region, map, point) + map.cell(point + Direction::DOWN) == region && + map.cell(point + Direction::LEFT) == region && + map.cell(point + Direction::DOWN + Direction::LEFT) != region +end + +# ABB +# ABB +# xAA +def internal_bottom_left?(region, map, point) + map.cell(point + Direction::UP) == region && + map.cell(point + Direction::RIGHT) == region && + map.cell(point + Direction::UP + Direction::RIGHT) != region +end + +# BBA +# BBA +# AAx +def internal_bottom_right?(region, map, point) + map.cell(point + Direction::UP) == region && + map.cell(point + Direction::LEFT) == region && + map.cell(point + Direction::UP + Direction::LEFT) != region +end + +# xAA +# ABB +# ABB +def internal_top_left?(region, map, point) + map.cell(point + Direction::DOWN) == region && + map.cell(point + Direction::RIGHT) == region && + map.cell(point + Direction::DOWN + Direction::RIGHT) != region +end + +#------------------------------------------------------------------------------ +def measure_region(region, map, point, visited) + return 0, 0 if visited.include?(point) + point_plant = map.cell(point) + return 0, 0 if point_plant != region + visited.add(point) + + area = 1 + corners = number_of_corners(region, map, point) + + Direction::ALL.each do |dir| + neighbor = point + dir + neighbor_plant = map.cell(neighbor) + + if neighbor_plant == region + neighbor_area, neighbor_corners = measure_region(region, map, neighbor, visited) + area += neighbor_area + corners += neighbor_corners + end + end + + [area, corners] +end + +#------------------------------------------------------------------------------ +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +map = Map.new(lines) + +visited = Set.new +total_cost = 0 +map.each_point do |point| + next if visited.include?(point) + + region = map.cell(point) + area, corners = measure_region(region, map, point, visited) + puts ""Region #{region} at #{point} has area #{area} and #{corners} corners"" + total_cost += area * corners +end + +puts ""Total cost: #{total_cost}""",ruby +606,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,"data = File.read(""data/day_12.txt"").lines.map(&:strip) + +$grid = data.map { |line| line.chars } + + +$seen = {} +$neighbors = {} +def part_1 + char_neighbor_counts = {} + $regions = [] + $grid.each_with_index do |row, i| + row.each_with_index do |cell, j| + next if $seen[""#{i},#{j}""] + + search_queue = [[i,j]] + region = [[i,j]] + while search_queue.any? + next_up = search_queue.shift + next if $seen[""#{next_up[0]},#{next_up[1]}""] + $seen[""#{next_up[0]},#{next_up[1]}""] = true + + neighbors = find_neighbors(next_up[0], next_up[1]) + search_queue += neighbors + region += neighbors + end + $regions << region + end + end + + + total_price = 0 + $regions.each do |region| + area = region.uniq.length + perim = 0 + region.uniq.each do |cell| + perim += 4 - $neighbors[""#{cell[0]},#{cell[1]}""] + end + price = area * perim + total_price += price + end + total_price +end + + +def part_2 + total_price = 0 + $regions.each do |region| + area = region.uniq.length + corners = 0 + region.uniq.each do |cell| + corners += corners(cell) + end + price = area * corners + total_price += price + end + total_price +end + +def find_neighbors(i,j) + i = i.to_i + j = j.to_i + char = $grid[i][j] + neighbors = [] + if i > 0 + neighbors << [i-1,j] if $grid[i-1][j] == char + end + if i < $grid.length - 1 + neighbors << [i+1,j] if $grid[i+1][j] == char + end + if j > 0 + neighbors << [i,j-1] if $grid[i][j-1] == char + end + if j < $grid[i].length - 1 + neighbors << [i,j+1] if $grid[i][j+1] == char + end + $neighbors[""#{i},#{j}""] = neighbors.count + neighbors +end + +def corners(cell) + i = cell[0] + j = cell[1] + char = $grid[i][j] + up = i > 0 ? $grid[i-1][j] : nil + down = i < $grid.length - 1 ? $grid[i+1][j] : nil + left = j > 0 ? $grid[i][j-1] : nil + right = j < $grid[i].length - 1 ? $grid[i][j+1] : nil + + corners = 0 + if up != char + if left != char + corners += 1 + end + if right != char + corners += 1 + end + end + if down != char + if left != char + corners += 1 + end + if right != char + corners += 1 + end + end + + # Now check for inside corners + if up == char + if left == char + corners += 1 unless $grid[i-1][j-1] == char + end + if right == char + corners += 1 unless $grid[i-1][j+1] == char + end + end + if down == char + if left == char + corners += 1 unless $grid[i+1][j-1] == char + end + if right == char + corners += 1 unless $grid[i+1][j+1] == char + end + end + corners +end + +p ""Part 1: #{part_1}"" +p ""Part 2: #{part_2}""",ruby +607,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,"class Day12 + def initialize() + @matrix = [] + @width = 0 + @height = 0 + @visited = Hash.new + @areas_register = Hash.new + @groups_matrix = [] + @sums = [] + end + + def read_file + i = 0 + File.open(""Day12\\input12.txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + chars = line.strip.chars + @matrix[i] = chars + @width = chars.length + i += 1 + @height += 1 + end + end + end + + def find_groups + for i in 0..@height-1 + for j in 0..@width-1 + if @visited.key?([i,j]) + next + else + collect_group([i,j]) + end + end + end + return @areas_register + end + + def collect_group(first_coords) + queue = [first_coords] + common_char = @matrix[first_coords[0]][first_coords[1]] + group_area = 0 + adjacent_sides_count = 0 + group_peremeter = 0 + group_coords = [] + + while !queue.empty? + coords = queue.shift + i = coords[0] + j = coords[1] + + if @visited.key?([i,j]) + next + else + if @matrix[i][j] == common_char + group_coords.push([i,j]) + adjacent_sides_count += 1 + group_area += 1 + @visited[[i,j]] = true + if i-1 >= 0 + queue.push([i-1,j]) + end + if i+1 < @height + queue.push([i+1,j]) + end + if j-1 >= 0 + queue.push([i,j-1]) + end + if j+1 < @width + queue.push([i,j+1]) + end + end + end + end + group_peremeter = (group_area * 4) - ((group_area-2)*4) + per = find_perimeter(group_coords.uniq) + full_perimeter = ((group_area * 4) - (per)) + final_perimeter = full_perimeter - (find_shared_lines_for_perimeter(group_coords.uniq)/2) + @sums.push(group_area * final_perimeter) + end + + def calculate_price + sum = 0 + + for s in @sums + sum += s + end + + return sum + end + + def get_coords_around(i,j) + coords = [] + + coords.push([i,j]) + + if i-1 >= 0 + coords.push([i-1,j]) + end + if i+1 < @height + coords.push([i+1,j]) + end + if j-1 >= 0 + coords.push([i,j-1]) + end + if j+1 < @width + coords.push([i,j+1]) + end + + return coords + end + + def has_element_above?(coords) + i = coords[0] + j = coords[1] + my_char = @matrix[i][j] + if i-1 >= 0 + return @matrix[i-1][j] == my_char + else + return false + end + end + + def has_element_below?(coords) + i = coords[0] + j = coords[1] + my_char = @matrix[i][j] + if i+1 < @height + return @matrix[i+1][j] == my_char + else + return false + end + end + + def has_element_left?(coords) + i = coords[0] + j = coords[1] + my_char = @matrix[i][j] + if j-1 >= 0 + return @matrix[i][j-1] == my_char + else + return false + end + end + + def has_element_right?(coords) + i = coords[0] + j = coords[1] + my_char = @matrix[i][j] + if j+1 < @width + return @matrix[i][j+1] == my_char + else + return false + end + end + + def find_perimeter(vertices) + perimeter = 0 + adjacent_sides_count = 0 + + for i in 0..vertices.length-1 + for j in 0..vertices.length-1 + if i != j + if (vertices[i][0] == vertices[j][0] && vertices[i][1] == vertices[j][1]-1) || + (vertices[i][0] == vertices[j][0] && vertices[i][1] == vertices[j][1]+1) || + (vertices[i][0] == vertices[j][0]-1 && vertices[i][1] == vertices[j][1]) || + (vertices[i][0] == vertices[j][0]+1 && vertices[i][1] == vertices[j][1]) + adjacent_sides_count += 1 + end + end + end + end + return adjacent_sides_count + end + + def find_shared_lines_for_perimeter(vertices) + shared_lines = 0 + + for i in 0..vertices.length-1 + for j in 0..vertices.length-1 + if i != j + line_above_i = [vertices[i][0] - 1, vertices[i][1]] + line_above_j = [vertices[j][0] - 1, vertices[j][1]] + + line_below_i = [vertices[i][0] + 1, vertices[i][1]] + line_below_j = [vertices[j][0] + 1, vertices[j][1]] + + line_left_i = [vertices[i][0], vertices[i][1] - 1] + line_left_j = [vertices[j][0], vertices[j][1] - 1] + + line_right_i = [vertices[i][0], vertices[i][1] + 1] + line_right_j = [vertices[j][0], vertices[j][1] + 1] + + if line_above_i[0] == line_above_j[0] && (vertices[i][1] - vertices[j][1]).abs == 1 && !has_element_above?(vertices[i]) && !has_element_above?(vertices[j]) + shared_lines += 1 + end + + if line_below_i[0] == line_below_j[0] && (vertices[i][1] - vertices[j][1]).abs == 1 && !has_element_below?(vertices[i]) && !has_element_below?(vertices[j]) + shared_lines += 1 + end + + if line_left_i[1] == line_left_j[1] && (vertices[i][0] - vertices[j][0]).abs == 1 && !has_element_left?(vertices[i]) && !has_element_left?(vertices[j]) + shared_lines += 1 + end + + if line_right_i[1] == line_right_j[1] && (vertices[i][0] - vertices[j][0]).abs == 1 && !has_element_right?(vertices[i]) && !has_element_right?(vertices[j]) + shared_lines += 1 + end + end + end + end + return shared_lines + end +end + + +day12 = Day12.new() +day12.read_file +puts day12.find_groups +puts day12.calculate_price",ruby +608,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +@field = File.read(path).split.map{ _1.chars } +regions = [] +@affected = Set.new + +@height = @field.count +@width = @field.first.count + +def find_region(from:) + plot = @field[from[0]][from[1]] + region = [] + stack = Set.new([from]) + visited = Set.new + while !stack.empty? + e = stack.first + stack.delete(e) + visited << e + if @field[e[0]][e[1]] == plot + region << e + @affected << e + [[e[0] + 1, e[1]], [e[0] - 1, e[1]], [e[0], e[1] + 1], [e[0], e[1] - 1]].each do |(i, j)| + if !visited.include?([i, j]) && (0...@height).include?(i) && (0...@width).include?(j) + stack << [i, j] + end + end + end + end + region +end + +(0...@height).each do |i| + (0...@width).each do |j| + next if @affected.include?([i, j]) + regions << find_region(from: [i, j]) + end +end + +def price(region) + rows = region.sort do |e1, e2| + main_sort = e1[0] <=> e2[0] + main_sort.zero? ? e1[1] <=> e2[1] : main_sort + end.group_by{ _1[0]}.values + + columns = region.sort do |e1, e2| + main_sort = e1[1] <=> e2[1] + main_sort.zero? ? e1[0] <=> e2[0] : main_sort + end.group_by{ _1[1]}.values + + sides = 0 + + sides += rows.reduce(0) do |sum, row| + linked_top = false + linked_bottom = false + previous_j = nil + new_sides = row.reduce(0) do |sub_sum, (i, j)| + if previous_j != j - 1 + linked_top = false + linked_bottom = false + end + previous_j = j + t = 0 + if region.include?([i - 1, j]) + linked_top = false + else + t +=1 unless linked_top + linked_top = true + end + if region.include?([i + 1, j]) + linked_bottom = false + else + t +=1 unless linked_bottom + linked_bottom = true + end + sub_sum + t + end + sum + new_sides + end + + sides += columns.reduce(0) do |sum, column| + linked_left = false + linked_right = false + previous_i = nil + new_sides = column.reduce(0) do |sub_sum, (i, j)| + if previous_i != i - 1 + linked_left = false + linked_right = false + end + previous_i = i + t = 0 + if region.include?([i, j - 1]) + linked_left = false + else + t +=1 unless linked_left + linked_left = true + end + if region.include?([i, j + 1]) + linked_right = false + else + t +=1 unless linked_right + linked_right = true + end + sub_sum + t + end + sum + new_sides + end + sides * region.count +end + + +p regions.sum { price(_1) }",ruby +609,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,"#!/usr/bin/ruby + +require 'set' + +DATA = File.read('data.txt').lines.map(&:strip).map(&:chars) +HEIGHT = DATA.size +WIDTH = DATA[0].size + +def get_xy_around(y, x) + [ + [y-1, x, :up], + [y+1, x, :down], + [y, x-1, :left], + [y, x+1, :right] + ] +end + +def get_neighbors(y, x) + get_xy_around(y, x).select do |ny, nx, _| + ny >= 0 && ny < HEIGHT && nx >= 0 && nx < WIDTH + end +end + +def flood_fill(start_y, start_x, visited) + plant_type = DATA[start_y][start_x] + region = Set.new + queue = [[start_y, start_x]] + + while !queue.empty? + y, x = queue.shift + next if visited.include?([y, x]) + next if DATA[y][x] != plant_type + + visited.add([y, x]) + region.add([y, x]) + + get_neighbors(y, x).each do |ny, nx| + queue << [ny, nx] if !visited.include?([ny, nx]) && DATA[ny][nx] == plant_type + end + end + + region +end + +def calculate_perimeter(region) + perimeter = 0 + region.each do |y, x| + get_xy_around(y, x).each do |ny, nx, _| + perimeter += 1 if !region.include?([ny, nx]) + end + end + perimeter +end + +def count_sides(region) + edges = Set.new + + region.each do |y, x| + get_xy_around(y, x).each do |ny, nx, direction| + edges.add([ny, nx, direction]) if !region.include?([ny, nx]) + end + end + + sides = 0 + processed = Set.new + + edges.each do |y, x, direction| + next if processed.include?([y, x, direction]) + current = [y, x, direction] + todo = [current] + while !todo.empty? + current = todo.shift + y, x, dir = current + next if processed.include?(current) + next if region.include?([y, x]) + + origin = case dir + when :right + [y, x-1] + when :left + [y, x+1] + when :up + [y+1, x] + when :down + [y-1, x] + end + next if !region.include?(origin) + + processed.add(current) + + if dir == :right or dir == :left + todo << [y+1, x, dir] + todo << [y-1, x, dir] + elsif dir == :up or dir == :down + todo << [y, x+1, dir] + todo << [y, x-1, dir] + end + end + sides += 1 + end + + sides +end + +def solve + visited = Set.new + part1 = 0 + part2 = 0 + + HEIGHT.times do |y| + WIDTH.times do |x| + next if visited.include?([y, x]) + + region = flood_fill(y, x, visited) + area = region.size + perimeter = calculate_perimeter(region) + sides = count_sides(region) + letter = DATA[y][x] + part1 += area * perimeter + part2 += sides * area + end + end + + [part1, part2] +end + +PART_ONE, PART_TWO = solve +puts 'Part 1: %s' % PART_ONE +puts 'Part 2: %s' % PART_TWO",ruby +610,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,"#!/usr/bin/env ruby +# frozen_string_literal: true +require 'matrix' + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n\n"").map{ |l| l.split(""\n"").map{ |c| c.scan(/X(?:=|\+)(\d*), Y(?:=|\+)(\d*)/).map { |a, b| { X: a.to_i, Y: b.to_i} } }.flatten } + +sum = 0 +input.each do |l| + f, s, loc = l[0], l[1], l[2] + + a1, b1, c1 = f[:X], s[:X], loc[:X] + a2, b2, c2 = f[:Y], s[:Y], loc[:Y] + + coef = Matrix[[a1, b1], [a2, b2]] + const = Matrix[[c1], [c2]] + + if coef.square? && coef.determinant != 0 + solution = coef.inverse * const + x, y = solution[0, 0], solution[1, 0] + + sum += x * 3 + y if x.to_i == x && y.to_i == y + end +end + +puts sum.to_i",ruby +611,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,"require 'set' + +def parse_input + input = File.read('inputs/13', chomp: true) + + input.strip.split(""\n\n"").map do |game| + lines = game.lines.map(&:strip) + + button_a = lines[0].match(/Button A: X\+(\d+), Y\+(\d+)/).captures.map(&:to_i) + button_b = lines[1].match(/Button B: X\+(\d+), Y\+(\d+)/).captures.map(&:to_i) + prize = lines[2].match(/Prize: X=(\d+), Y=(\d+)/).captures.map(&:to_i) + + [ + button_a[0], + button_a[1], + button_b[0], + button_b[1], + prize[0], + prize[1], + ] + end +end + +def solve + games = parse_input + visited = Set.new + tokens = Set.new + sum = 0 + + walk = ->(x, y, ax, ay, bx, by, goal_x, goal_y, count_a, count_b, sum) do + return if x > goal_x || y > goal_y + return if count_a > 100 || count_b > 100 + return if visited.include?([count_a, count_b]) + + visited << [count_a, count_b] + + return if + if x == goal_x && y == goal_y + tokens << sum + return + end + + walk.call(x + ax, y + ay, ax, ay, bx, by, goal_x, goal_y, count_a + 1, count_b, sum + 3) + walk.call(x + bx, y + by, ax, ay, bx, by, goal_x, goal_y, count_a, count_b + 1, sum + 1) + end + + games.each do |game| + walk.call(0, 0, *game, 0, 0, 0) + sum += tokens.min unless tokens.empty? + tokens = Set.new + visited = Set.new + end + + sum +end + +puts solve",ruby +612,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,"#! /usr/bin/env ruby + +require 'matrix' + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +total_tokens = 0 +while lines.any? + button_a = lines.shift + button_b = lines.shift + prize = lines.shift + + # Button A: X+12, Y+57 + button_a_x, button_a_y = button_a.split("":"").last.strip.split("","").map { |s| s.split('+').last.to_i } + button_b_x, button_b_y = button_b.split("":"").last.strip.split("","").map { |s| s.split('+').last.to_i } + + # Prize: X=14212, Y=3815 + prize_x, prize_y = prize.split("":"").last.strip.split("","").map { |s| s.split('=').last.to_i } + + # Create a system of equations: + # button_a_x * x + button_b_x * y = prize_x + # button_a_y * x + button_b_y * y = prize_y + coefficients = Matrix[ + [button_a_x, button_b_x], + [button_a_y, button_b_y] + ] + constants = Vector[prize_x, prize_y] + + # The solution is the number of presses for each button to reach the prize + solution = coefficients.inverse * constants + + # Check if the solution is an integer (we can only press buttons an integer number of times) + next unless solution.all? { |s| s.denominator == 1 } + + # Calculate the number of tokens (it costs 3 tokens to press button A, 1 to press button B) + total_tokens += solution[0].to_i * 3 + solution[1].to_i +end + +puts ""Total tokens: #{total_tokens}""",ruby +613,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +machines = File.read(path).split(""\n\n"").map do |machine| + button_a, button_b, prize = machine.split(""\n"") + button_a = button_a[12...button_a.length].split(', Y+').map(&:to_i) + button_b = button_b[12...button_b.length].split(', Y+').map(&:to_i) + prize = prize[9...prize.length].split(', Y=').map(&:to_i) + [button_a, button_b, prize] +end + +res = machines.reduce(0) do |sum, machine| + target_x = machine.last[0] + target_y = machine.last[1] + button_a = machine[0] + button_b = machine[1] + possible_values = (0..100).filter_map do |a| + a_x = a * button_a[0] + next nil if a_x > target_x + b, b_rest = (target_x - a_x).divmod(button_b[0]) + next nil unless b_rest.zero? + next nil unless a * button_a[1] + b * button_b[1] == target_y + [a, b] + end + possible_values.empty? ? sum : sum + possible_values.map { |a, b| 3 * a + b }.min +end + +p res",ruby +614,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,"class Day13 + def initialize() + + end + + def read_file + i = 0 + button_A_X = 0 + button_A_Y = 0 + button_B_X = 0 + button_B_Y = 0 + prize_X = 0 + prize_Y = 0 + tokens_sum = 0 + + File.open(""Day13\\input13.txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + if line.include?(""Button A:"") + line.gsub!(""Button A: "", """") + puts line + splitted_coords = line.strip!.split("","") + button_A_X = splitted_coords[0].strip.gsub!(""X+"", """").to_i + button_A_Y = splitted_coords[1].strip.gsub!(""Y+"", """").to_i + end + if line.include?(""Button B:"") + line.gsub!(""Button B: "", """") + puts line + splitted_coords = line.strip!.split("","") + button_B_X = splitted_coords[0].strip.gsub!(""X+"", """").to_i + button_B_Y = splitted_coords[1].strip.gsub!(""Y+"", """").to_i + end + if line.include?(""Prize"") + line.gsub!(""Prize: "", """") + puts ""line #{line.strip!}"" + splitted_coords = line.split("", "") + prize_X = splitted_coords[0].strip.gsub!(""X="", """").to_i + prize_Y = splitted_coords[1].strip.gsub!(""Y="", """").to_i + + tokens_min = calculate_min_tokens(button_A_X, button_A_Y, button_B_X, button_B_Y, prize_X, prize_Y) + tokens_sum += tokens_min + end + end + end + return tokens_sum + end + + def calculate_min_tokens(button_A_X, button_A_Y, button_B_X, button_B_Y, prize_X, prize_Y) + max_int = (2**(0.size * 8 -2) -1) + min_tokens = max_int + + for i in 0..100 + for j in 0..100 + if i * button_A_X + j * button_B_X == prize_X && i * button_A_Y + j * button_B_Y == prize_Y + tokens = i*3 + j*1 + if tokens < min_tokens + min_tokens = tokens + end + end + end + end + + if min_tokens == max_int + return 0 + end + + return min_tokens + end +end + +day13 = Day13.new() +puts day13.read_file",ruby +615,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +machines = File.read(path).split(""\n\n"").map do |machine| + button_a, button_b, prize = machine.split(""\n"") + button_a = button_a[12...button_a.length].split(', Y+').map(&:to_i) + button_b = button_b[12...button_b.length].split(', Y+').map(&:to_i) + prize = prize[9...prize.length].split(', Y=').map { _1.to_i + 10_000_000_000_000 } + [button_a, button_b, prize] +end + +res = machines.reduce(0) do |sum, machine| + target_x = machine.last[0] + target_y = machine.last[1] + button_a = machine[0] + button_b = machine[1] + denom = button_b[1] * button_a[0] - button_b[0] * button_a[1] + next sum if denom.zero? + b, rest_b = (target_y * button_a[0] - target_x * button_a[1]).divmod(denom) + next sum unless rest_b.zero? + a, rest_a = (target_x - b * button_b[0]).divmod(button_a[0]) + next sum unless rest_a.zero? + sum + 3 * a + b +end + +p res",ruby +616,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,"Machine = Struct.new('Machine', :ax, :ay, :bx, :by, :x, :y) do + COST_A = 3 + COST_B = 1 + MAX_PUSHES = 100 + + def solve_equations + det = ax * by - ay * bx + return nil if det == 0 + + n = by * x - bx * y + m = -ay * x + ax * y + + [n / det, m / det] if n % det == 0 && m % det == 0 + end + + def solve + n, m = solve_equations + n && m ? n * COST_A + m * COST_B : 0 + end + + def pushA(cost, dx, dy) + [cost + COST_A, dx - ax, dy - ay] + end + + def pushB(cost, dx, dy) + if dx % bx == 0 && dy % by == 0 && dx / bx == dy / by + b_pushes = (dx/bx) + return cost + b_pushes * COST_B + end + nil + end + + def solve_original + cost = 0 + dx = x + dy = y + lowest_cost = nil + a_pushes = 0 + until (lowest_cost && cost >= lowest_cost) || dx.negative? || dy.negative? + total_cost = pushB(cost, dx, dy) + lowest_cost = [total_cost, lowest_cost || Float::INFINITY].min if total_cost + cost, dx, dy = pushA(cost, dx, dy) + a_pushes += 1 + end + lowest_cost || 0 + end +end + +class Claw + attr_accessor :machines + + DIGITS = /\d+/ + BIGNUM = 10_000_000_000_000 + + def self.create(input) + claw = Claw.new + input.each_slice(4) do |a, b, prize| + ax, ay = a.scan(DIGITS).map(&:to_i) + bx, by = b.scan(DIGITS).map(&:to_i) + x, y = prize.scan(DIGITS).map(&:to_i) + claw.machines << Machine.new(ax, ay, bx, by, x, y) + end + claw + end + + def initialize + @machines = [] + end + + def part1 + machines.reduce(0) { |sum, m| sum + m.solve } + end + + def part2 + machines.reduce(0) do |sum, m| + m.x += BIGNUM + m.y += BIGNUM + sum + m.solve + end + end +end + +input = IO.readlines(ARGV[0]) + +claw = Claw.create(input) +puts claw.part1 +puts claw.part2",ruby +617,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,"require 'matrix' +2.times{|i| p File.read(""input.txt"").delete(""^0-9,\n"").split(""\n\n"").map{|game| game.split(""\n"").map{|line| line.split("","").map(&:to_i)}}.sum{|a,b,prize| + prize = prize.map{|coord| coord + 10000000000000} if i == 1 #part2 + res = Matrix[[a[0],b[0]],[a[1],b[1]]].inverse * Vector[prize[0],prize[1]] + res.all?{_1.denominator == 1} ? res[0].to_i*3+res[1].to_i : 0 + } +} + + + + + + + + + + +def day13_attempt1_bruteforce + games = File.read(""Day13.txt"").delete(""^0-9,\n"").split(""\n\n"").map{|game| game.split(""\n"").map{|line| line.split("","").map(&:to_i)}} + j=1 + 2.times{|i| + p games.sum{|a,b,prize| + p ""run #{j}"" + j+=1 + prize = prize.map{|coord| coord + 10000000000000} if i == 1 + bestcost = Float::INFINITY + min_a = prize.zip(a).map{_1.reduce(:/)}.min + min_a.downto(0){|apress| + coords_remain = prize.zip(a.map{_1*apress}).map{_1.reduce(:-)} + if (t=coords_remain.zip(b)).map{_1.reduce(:%)}.all?{_1==0} && t.map{_1.reduce(:/)}.uniq.size == 1 + cost = 3*apress + coords_remain[0]/b[0] + bestcost = [bestcost,cost].min + end + } + bestcost == Float::INFINITY ? 0 : bestcost + } + } + end",ruby +618,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,"#!/usr/bin/env ruby +# frozen_string_literal: true +require 'matrix' + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n\n"").map{ |l| l.split(""\n"").map{ |c| c.scan(/X(?:=|\+)(\d*), Y(?:=|\+)(\d*)/).map { |a, b| { X: a.to_i, Y: b.to_i} } }.flatten } + +sum = 0 +input.each do |l| + f, s, loc = l[0], l[1], l[2] + + a1, b1, c1 = f[:X], s[:X], loc[:X] + 10000000000000 + a2, b2, c2 = f[:Y], s[:Y], loc[:Y] + 10000000000000 + + coef = Matrix[[a1, b1], [a2, b2]] + const = Matrix[[c1], [c2]] + + if coef.square? && coef.determinant != 0 + solution = coef.inverse * const + x, y = solution[0, 0], solution[1, 0] + + sum += x * 3 + y if x.to_i == x && y.to_i == y + end +end + +puts sum.to_i",ruby +619,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,"#! /usr/bin/env ruby + +require 'matrix' + +OFFSET = 10_000_000_000_000 + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +total_tokens = 0 +while lines.any? + button_a = lines.shift + button_b = lines.shift + prize = lines.shift + + # Button A: X+12, Y+57 + button_a_x, button_a_y = button_a.split("":"").last.strip.split("","").map { |s| s.split('+').last.to_i } + button_b_x, button_b_y = button_b.split("":"").last.strip.split("","").map { |s| s.split('+').last.to_i } + + # Prize: X=14212, Y=3815 + prize_x, prize_y = prize.split("":"").last.strip.split("","").map { |s| s.split('=').last.to_i + OFFSET } + + # Create a system of equations: + # button_a_x * x + button_b_x * y = prize_x + # button_a_y * x + button_b_y * y = prize_y + coefficients = Matrix[ + [button_a_x, button_b_x], + [button_a_y, button_b_y] + ] + constants = Vector[prize_x, prize_y] + + # The solution is the number of presses for each button to reach the prize + solution = coefficients.inverse * constants + + # Check if the solution is an integer (we can only press buttons an integer number of times) + next unless solution.all? { |s| s.denominator == 1 } + + # Calculate the number of tokens (it costs 3 tokens to press button A, 1 to press button B) + total_tokens += solution[0].to_i * 3 + solution[1].to_i +end + +puts ""Total tokens: #{total_tokens}""",ruby +620,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,"class Day14 + def initialize() + @MAP_HEIGHT = 103 + @MAP_WIDTH = 101 + @matrix = Array.new(@MAP_HEIGHT) { Array.new(@MAP_WIDTH, ""."") } + @ITERATIONS = 100 + @middle_y = (@MAP_HEIGHT / 2).ceil + @middle_x = (@MAP_WIDTH / 2).ceil + @first_quadrant_count = 0 + @second_quadrant_count = 0 + @third_quadrant_count = 0 + @fourth_quadrant_count = 0 + end + + def read_process_input + + File.open(""Day14\\input14.txt"", ""r"") do |f| + f.each_line do |line| + line_data = line.split(""v="") + pos = line_data[0].gsub(""p="", """").strip + pos_x = pos.split("","")[0].to_i + pos_y = pos.split("","")[1].to_i + + vel = line_data[1].gsub(""v="", """").strip + vel_x = vel.split("","")[0].to_i + vel_y = vel.split("","")[1].to_i + + calculate_final_positions(pos_x, pos_y, vel_x, vel_y) + end + end + end + + def calculate_final_positions(pos_x, pos_y, vel_x, vel_y) + curr_x = pos_x + curr_y = pos_y + + for i in 1..@ITERATIONS + curr_x = curr_x + vel_x + curr_y = curr_y + vel_y + + if curr_x < 0 + curr_x = @MAP_WIDTH + curr_x + end + if curr_y < 0 + curr_y = @MAP_HEIGHT + curr_y + end + if curr_x > @MAP_WIDTH-1 + curr_x = curr_x - @MAP_WIDTH + end + if curr_y > @MAP_HEIGHT-1 + curr_y = curr_y - @MAP_HEIGHT + end + + if i == @ITERATIONS + if curr_x == @middle_x || curr_y == @middle_y + #skip + elsif curr_x < @middle_x && curr_y < @middle_y + @first_quadrant_count += 1 + elsif curr_x > @middle_x && curr_y < @middle_y + @second_quadrant_count += 1 + elsif curr_x < @middle_x && curr_y > @middle_y + @third_quadrant_count += 1 + elsif curr_x > @middle_x && curr_y > @middle_y + @fourth_quadrant_count += 1 + end + end + end + end + + def calculate_safety_factor() + return @first_quadrant_count * @second_quadrant_count * @third_quadrant_count * @fourth_quadrant_count + end +end + + +day14 = Day14.new() +day14.read_process_input +puts day14.calculate_safety_factor",ruby +621,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/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n"").map{ |l| l.scan(/p=(\d*),(\d*) v=(-?\d*),(-?\d*)/).map { |a, b, c, d| {p: { x: a.to_i, y: b.to_i}, v: { x: c.to_i, y: d.to_i} } } }.flatten + +maxX = 101 +maxY = 103 + +maxX -= 1 +maxY -= 1 + +quadrants = [0,0,0,0] + +100.times do |i| + input.each do |r| + r[:p][:x] += r[:v][:x] + + r[:p][:x] = r[:p][:x]-maxX-1 if r[:p][:x] > maxX + r[:p][:x] = r[:p][:x]+maxX+1 if r[:p][:x] < 0 + + r[:p][:y] += r[:v][:y] + + r[:p][:y] = r[:p][:y]-maxY-1 if r[:p][:y] > maxY + r[:p][:y] = r[:p][:y]+maxY+1 if r[:p][:y] < 0 + + if i == 99 + if r[:p][:x] < maxX/2 && r[:p][:y] < maxY/2 + quadrants[0] += 1 + elsif r[:p][:x] > maxX/2 && r[:p][:y] < maxY/2 + quadrants[1] += 1 + elsif r[:p][:x] < maxX/2 && r[:p][:y] > maxY/2 + quadrants[2] += 1 + elsif r[:p][:x] > maxX/2 && r[:p][:y] > maxY/2 + quadrants[3] += 1 + end + end + end + +end + +puts quadrants.reduce(:*)",ruby +622,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +STEPS = 100 +WIDTH = TEST ? 11 : 101 +HEIGHT = TEST ? 7 : 103 + +robots = File.read(path).split(""\n"").map do |robot| + robot[2...robot.length].split(' v=').map { _1.split(',').map(&:to_i) } +end + +def print_map(robots) + map = Array.new(HEIGHT) { Array.new(WIDTH) { 0 } } + robots.each do |robot| + map[robot[0][1]][robot[0][0]] += 1 + end + map.each do |line| + p line.map { _1.zero? ? '.' : _1.to_s }.join + end + p '' +end + +# p 'Initial state:' +# print_map(robots) + +STEPS.times do + robots.each do |robot| + robot[0][0] = (robot[0][0] + robot[1][0]) % WIDTH + robot[0][1] = (robot[0][1] + robot[1][1]) % HEIGHT + end +end + +# p ""After #{STEPS} seconds:"" +# print_map(robots) + +map = Array.new(HEIGHT) { Array.new(WIDTH) { 0 } } +robots.each do |robot| + map[robot[0][1]][robot[0][0]] += 1 +end +p [ + map[0...(HEIGHT - 1) / 2].flat_map { |line| line[0...(WIDTH - 1) / 2] }.sum, + map[0...(HEIGHT - 1) / 2].flat_map { |line| line[(WIDTH + 1) / 2...WIDTH] }.sum, + map[(HEIGHT + 1) / 2...HEIGHT].flat_map { |line| line[0...(WIDTH - 1) / 2] }.sum, + map[(HEIGHT + 1) / 2...HEIGHT].flat_map { |line| line[(WIDTH + 1) / 2...WIDTH] }.sum, +].reduce(1, &:*)",ruby +623,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,"data = File.read(""input.txt"").lines.map(&:strip) + +$positions = [] +$velocities = [] + +HEIGHT = 103 +WIDTH = 101 + +data.each do |line| + pos = line.split("" "")[0] + vel = line.split("" "")[1] + pos = pos.split(""="")[1] + vel = vel.split(""="")[1] + + $positions << pos.split("","").map(&:to_i) + $velocities << vel.split("","").map(&:to_i) +end + +$original_positions = $positions.map(&:dup) + +def part_1 + $positions.each_with_index do |pos, i| + x_vel = $velocities[i][0] + y_vel = $velocities[i][1] + x_pos_change = (x_vel * 100) % WIDTH + y_pos_change = (y_vel * 100) % HEIGHT + + $positions[i][0] += x_pos_change + if $positions[i][0] >= WIDTH + $positions[i][0] -= WIDTH + end + if $positions[i][0] < 0 + $positions[i][0] += WIDTH + end + $positions[i][1] += y_pos_change + if $positions[i][1] >= HEIGHT + $positions[i][1] -= HEIGHT + end + if $positions[i][1] < 0 + $positions[i][1] += HEIGHT + end + end + top_left = $positions.filter { |pos| pos[0] <= WIDTH/2-1 && pos[1] <= HEIGHT/2-1 }.count + top_right = $positions.filter { |pos| pos[0] >= WIDTH/2 +1 && pos[1] <= HEIGHT/2-1 }.count + bottom_left = $positions.filter { |pos| pos[0] <= WIDTH/2-1 && pos[1] >= HEIGHT/2 + 1 }.count + bottom_right = $positions.filter { |pos| pos[0] >= WIDTH/2 + 1 && pos[1] >= HEIGHT/2 + 1 }.count + + top_left * top_right * bottom_left * bottom_right +end + +p ""Part 1: #{part_1}""",ruby +624,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,"def solve + grid_width = 101 + grid_height = 103 + steps = 100 + + # Parse input + positions = File.readlines('inputs/14', chomp: true).map do |line| + px, py, vx, vy = line.scan(/-?\d+/).map(&:to_i) + [(px + steps * vx) % grid_width, (py + steps * vy) % grid_height] + end + + # Sort into quadrants + mid_x = (grid_width / 2).to_i + mid_y = (grid_height / 2).to_i + quadrant_counts = positions.each_with_object(Hash.new(0)) do |(x, y), counts| + quadrant = if x < mid_x + if y < mid_y + :left_up + elsif y > mid_y + :left_down + end + elsif x > mid_x + if y < mid_y + :right_up + elsif y > mid_y + :right_down + end + end + counts[quadrant] += 1 if quadrant != nil + end + + # Calculate safety factor + quadrant_counts.values.reduce(1, :*) +end + +puts solve",ruby +625,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,"def read_input(file_path) + positions = [] + velocities = [] + + File.foreach(file_path) do |line| + p_sec, v_sec = line.split + positions << p_sec.split(""="")[1].split("","").map(&:to_i) + velocities << v_sec.split(""="")[1].split("","").map(&:to_i) + end + + [positions, velocities] +end + +def standard_deviation(values) + return 0 if values.empty? + + mean = values.sum.to_f / values.size + variance = values.map { |v| (v - mean) ** 2 }.sum / values.size + Math.sqrt(variance) +end + +def simulate_motion(positions, velocities, num_x = 101, num_y = 103, steps = 10_000) + steps.times do |step| + block_counts = Hash.new(0) + new_positions = [] + + positions.each_with_index do |pos, i| + new_x = (pos[0] + velocities[i][0]) % num_x + new_y = (pos[1] + velocities[i][1]) % num_y + new_positions << [new_x, new_y] + block_counts[[new_x / 5, new_y / 5]] += 1 + end + + if standard_deviation(block_counts.values) > 3 + puts step + 1 + break + end + + positions = new_positions + end +end + +positions, velocities = read_input(""input.txt"") +simulate_motion(positions, velocities)",ruby +626,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,"# Read input from file +input_text = File.read('input.txt').split(""\n"") + +num_x = 101 +num_y = 103 +initial_positions = [] +velocities = [] + +# Parse positions and velocities +input_text.each do |line| + p_sec, v_sec = line.split + initial_positions << p_sec.split(""="")[1].split("","").map(&:to_i) + velocities << v_sec.split(""="")[1].split("","").map(&:to_i) +end + +# Loop through 10000 iterations +(0..9999).each do |counter| + block_counts = Hash.new(0) + new_initial_positions = [] + + initial_positions.each_with_index do |initial_pos, i| + velocity = velocities[i] + new_position = [ + (initial_pos[0] + velocity[0]) % num_x, + (initial_pos[1] + velocity[1]) % num_y + ] + new_initial_positions << new_position + block_counts[[new_position[0] / 5, new_position[1] / 5]] += 1 + end + + # Calculate mean and standard deviation + values = block_counts.values + mean = values.sum.to_f / values.size + stdev = Math.sqrt(values.sum { |v| (v - mean) ** 2 } / values.size) + + # Check if the standard deviation is greater than 3 + if stdev > 3 + puts counter + 1 + end + + initial_positions = new_initial_positions +end",ruby +627,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,"def read_input(file_path) + positions = [] + velocities = [] + + File.foreach(file_path) do |line| + p_sec, v_sec = line.split + positions << p_sec.split(""="")[1].split("","").map(&:to_i) + velocities << v_sec.split(""="")[1].split("","").map(&:to_i) + end + + [positions, velocities] +end + +def standard_deviation(values) + return 0 if values.empty? + + mean = values.sum.to_f / values.size + variance = values.map { |v| (v - mean) ** 2 }.sum / values.size + Math.sqrt(variance) +end + +num_x = 101 +num_y = 103 +positions, velocities = read_input(""input.txt"") + +10_000.times do |counter| + block_counts = Hash.new(0) + new_positions = [] + + positions.each_with_index do |pos, i| + new_x = (pos[0] + velocities[i][0]) % num_x + new_y = (pos[1] + velocities[i][1]) % num_y + new_positions << [new_x, new_y] + block_counts[[new_x / 5, new_y / 5]] += 1 + end + + if standard_deviation(block_counts.values) > 3 + puts counter + 1 + break + end + + positions = new_positions +end",ruby +628,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,"require 'pathname' +require 'matrix' + +lines = Pathname.new(""input.txt"").read.split(""\n"") + +iterations = 100 +width = 101 +height = 103 +robots = [] + +lines.each do |line| + matches = line.scan(/-?\d+/).map(&:to_i) + robots << matches +end + +quadrants = [0, 0, 0, 0] + +robots.each do |x, y, vx, vy| + x = (x + vx * iterations) % width + y = (y + vy * iterations) % height + + mid_x = width / 2 + mid_y = height / 2 + if x < mid_x && y < mid_y + quadrants[0] += 1 + elsif x < mid_x && y > mid_y + quadrants[1] += 1 + elsif x > mid_x && y < mid_y + quadrants[2] += 1 + elsif x > mid_x && y > mid_y + quadrants[3] += 1 + end +end + +safety_factor = quadrants.reduce(:*) +puts safety_factor + +pictures = 0 +(1..100_000).each do |i| + new_robots = [] + board = Array.new(height) { Array.new(width, 0) } + + robots.each do |x, y, vx, vy| + x = (x + vx * i) % width + y = (y + vy * i) % height + new_robots << [x, y] + board[y][x] = 1 + end + + if new_robots.uniq.length != new_robots.length + next + end + + max_sum = board.map { |row| row.sum }.max + if max_sum > 30 + puts i + break + end +end",ruby +629,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 ruby + +Point = Struct.new(:x, :y) do + def to_s + ""[#{x}, #{y}]"" + end + + def +(other) + Point.new(x + other.x, y + other.y) + end + + def -(other) + Point.new(x - other.x, y - other.y) + end + + def *(scalar) + Point.new(x * scalar, y * scalar) + end + + def distance(other) + (x - other.x).abs + (y - other.y).abs + end + + def modulo(width, height) + Point.new(x % width, y % height) + end +end + +input_file = ""input.txt"" +lines = File.readlines(input_file) + +robots = [] +lines.each do |line| + p, v = line.split(' ').map { |s| s.split('=').last.split(',').map(&:to_i) } + p = Point.new(p[0], p[1]) + v = Point.new(v[0], v[1]) + robots << { p:, v: } +end + +MAP_WIDTH = 101 +MAP_HEIGHT = 103 + +min_sum_of_distances = Float::INFINITY +min_sum_of_distances_seconds = 0 + +(MAP_WIDTH * MAP_HEIGHT).times do |seconds| + robot_positions = robots.map do |robot| + (robot[:p] + robot[:v] * seconds).modulo(MAP_WIDTH, MAP_HEIGHT) + end + + # The idea here is that if the robots are spread out across the map, + # there is no point in checking the sum of distances, since it will be high + x_variance = robot_positions.map { |p| p.x }.uniq.length + y_variance = robot_positions.map { |p| p.y }.uniq.length + next if x_variance == MAP_WIDTH || y_variance == MAP_HEIGHT + + # Find the sum of distances between all robots + # The idea here is that when they cluster together to form a christmas tree, + # the sum of distances will be minimal + sum_of_distances = 0 + early_exit = false + + 0.upto(robot_positions.length - 1) do |i| + (i + 1).upto(robot_positions.length - 1) do |j| + a = robot_positions[i] + b = robot_positions[j] + + sum_of_distances += a.distance(b) + + if sum_of_distances >= min_sum_of_distances + early_exit = true + break + end + end + break if early_exit + end + + next if early_exit + + if sum_of_distances < min_sum_of_distances + min_sum_of_distances = sum_of_distances + min_sum_of_distances_seconds = seconds + puts ""New minimum sum of distances: #{min_sum_of_distances} at #{min_sum_of_distances_seconds} seconds"" + end +end + +puts ""Minimum sum of distances: #{min_sum_of_distances} at #{min_sum_of_distances_seconds} seconds"" + +# 7709 - correct",ruby +630,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,"class Day15 + def initialize() + @matrix = [] + @directions = [] + @robot_initial_position = [] + end + + def read_process_input + started = false + ended = false + + File.open(""input.txt"", ""r"") do |f| + f.each_line.with_index do |line, index| + if !started && line.include?(""########"") + started = true + @matrix[index] = line.chars + elsif started && line.include?(""########"") + ended = true + @matrix[index] = line.chars + elsif !ended && line.strip.length > 0 + @matrix[index] = line.chars + end + + if line.include?(""@"") + @robot_initial_position = [index, line.index(""@"")] + end + + if ended && line.strip.length > 0 + @directions.concat(line.chars) + end + end + end + end + + def make_robot_moves + robot_pos = @robot_initial_position + + while @directions.length > 0 do + direction = @directions.shift + case direction + when '<' + left_char_pos = [robot_pos[0], robot_pos[1] - 1] + left_char = @matrix[left_char_pos[0]][left_char_pos[1]] + if left_char == ""O"" + left_of_left_char = @matrix[robot_pos[0]][robot_pos[1] - 2] + if left_of_left_char == ""#"" + # do nothing + elsif left_of_left_char == ""."" + @matrix[robot_pos[0]][robot_pos[1] - 2] = ""O"" + @matrix[robot_pos[0]][robot_pos[1] - 1] = ""@"" + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = [robot_pos[0], robot_pos[1] - 1] + elsif left_of_left_char == ""O"" + i = 2 + moves = true + tmp_left_of_left_char = left_of_left_char + change_pos = [robot_pos[0], robot_pos[1] - 2] + while tmp_left_of_left_char == ""O"" && moves do + tmp_left_of_left_char = @matrix[robot_pos[0]][robot_pos[1] - i] + if tmp_left_of_left_char == ""#"" + moves = false + elsif tmp_left_of_left_char == ""."" + moves = true + change_pos = [robot_pos[0], robot_pos[1] - i] + break + end + i += 1 + end + + if moves + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = left_char_pos + @matrix[left_char_pos[0]][left_char_pos[1]] = ""@"" + @matrix[change_pos[0]][change_pos[1]] = ""O"" + end + end + elsif left_char == ""#"" + # do nothing + else + # just move the robot to the left + @matrix[left_char_pos[0]][left_char_pos[1]] = ""@"" + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = left_char_pos + end + when '>' + right_char_pos = [robot_pos[0], robot_pos[1] + 1] + right_char = @matrix[right_char_pos[0]][right_char_pos[1]] + puts ""RIGHT CHAR: #{right_char}"" + puts ""RIGHT CHAR POS: #{right_char_pos}"" + if right_char == ""O"" + right_of_right_char = @matrix[robot_pos[0]][robot_pos[1] + 2] + if right_of_right_char == ""#"" + # do nothing + elsif right_of_right_char == ""."" + puts ""SHOULD BE HERE"" + @matrix[robot_pos[0]][robot_pos[1] + 2] = ""O"" + @matrix[robot_pos[0]][robot_pos[1] + 1] = ""@"" + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = [robot_pos[0], robot_pos[1] + 1] + elsif right_of_right_char == ""O"" + i = 2 + moves = true + tmp_right_of_right_char = right_of_right_char + change_pos = [robot_pos[0], robot_pos[1] + 2] + while tmp_right_of_right_char == ""O"" && moves do + tmp_right_of_right_char = @matrix[robot_pos[0]][robot_pos[1] + i] + if tmp_right_of_right_char == ""#"" + moves = false + elsif tmp_right_of_right_char == ""."" + moves = true + change_pos = [robot_pos[0], robot_pos[1] + i] + break + end + i += 1 + end + + if moves + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = right_char_pos + @matrix[right_char_pos[0]][right_char_pos[1]] = ""@"" + @matrix[change_pos[0]][change_pos[1]] = ""O"" + end + end + elsif right_char == ""#"" + # do nothing + else + # just move the robot to the left + @matrix[right_char_pos[0]][right_char_pos[1]] = ""@"" + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = right_char_pos + end + when '^' + up_char_pos = [robot_pos[0]-1, robot_pos[1]] + up_char = @matrix[up_char_pos[0]][up_char_pos[1]] + if up_char == ""O"" + up_of_up_char = @matrix[robot_pos[0] - 2][robot_pos[1]] + if up_of_up_char == ""#"" + # do nothing + elsif up_of_up_char == ""."" + @matrix[robot_pos[0] - 2][robot_pos[1]] = ""O"" + @matrix[robot_pos[0] - 1][robot_pos[1]] = ""@"" + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = [robot_pos[0] - 1, robot_pos[1]] + elsif up_of_up_char == ""O"" + i = 2 + moves = true + tmp_up_of_up_char = up_of_up_char + change_pos = [robot_pos[0] - 2, robot_pos[1]] + while tmp_up_of_up_char == ""O"" && moves do + tmp_up_of_up_char = @matrix[robot_pos[0] - i][robot_pos[1]] + if tmp_up_of_up_char == ""#"" + moves = false + elsif tmp_up_of_up_char == ""."" + moves = true + change_pos = [robot_pos[0] - i, robot_pos[1]] + break + end + i += 1 + end + + if moves + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = up_char_pos + @matrix[up_char_pos[0]][up_char_pos[1]] = ""@"" + @matrix[change_pos[0]][change_pos[1]] = ""O"" + end + end + elsif up_char == ""#"" + # do nothing + else + # just move the robot to the left + @matrix[up_char_pos[0]][up_char_pos[1]] = ""@"" + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = up_char_pos + end + when 'v' + down_char_pos = [robot_pos[0] + 1, robot_pos[1]] + down_char = @matrix[down_char_pos[0]][down_char_pos[1]] + if down_char == ""O"" + down_of_down_char = @matrix[robot_pos[0] + 2][robot_pos[1]] + if down_of_down_char == ""#"" + # do nothing + elsif down_of_down_char == ""."" + @matrix[robot_pos[0] + 2][robot_pos[1]] = ""O"" + @matrix[robot_pos[0] + 1][robot_pos[1]] = ""@"" + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = [robot_pos[0] + 1, robot_pos[1]] + elsif down_of_down_char == ""O"" + i = 2 + moves = true + tmp_down_of_down_char = down_of_down_char + change_pos = [robot_pos[0] + 2, robot_pos[1]] + while tmp_down_of_down_char == ""O"" && moves do + tmp_down_of_down_char = @matrix[robot_pos[0] + i][robot_pos[1]] + if tmp_down_of_down_char == ""#"" + moves = false + elsif tmp_down_of_down_char == ""."" + moves = true + change_pos = [robot_pos[0] + i, robot_pos[1]] + break + end + i += 1 + end + + if moves + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = down_char_pos + @matrix[down_char_pos[0]][down_char_pos[1]] = ""@"" + @matrix[change_pos[0]][change_pos[1]] = ""O"" + end + end + elsif down_char == ""#"" + # do nothing + else + # just move the robot to the left + @matrix[down_char_pos[0]][down_char_pos[1]] = ""@"" + @matrix[robot_pos[0]][robot_pos[1]] = ""."" + robot_pos = down_char_pos + end + end + + puts @matrix.join("""") + puts @directions.join("""") + end + end + + def calculate_boxes_sum + sum = 0 + @matrix.each_with_index do |row, i| + row.each_with_index do |v, j| + if v == ""O"" + sum += i*100 + j + end + end + end + return sum + end +end + +day15 = Day15.new() +day15.read_process_input +puts day15.make_robot_moves +puts day15.calculate_boxes_sum",ruby +631,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) +grid, moves = File.read(file_path).split(""\n\n"") + +moves = moves.gsub(""\n"", """").chars + +grid = grid.split(""\n"").map { |row| row.chars } +robot = {} +grid.each_with_index do |row, y| + breakout = false + row.each_with_index do |cell, x| + if cell == '@' + robot = { x: x, y: y } + breakout = true + break + end + end + break if breakout +end + +dirs= { 'v' => [1, 0], '^' => [-1, 0], '<' => [0, -1], '>' => [0, 1] } +moves.each do |move| + dx, dy = dirs[move] + + next_x = robot[:x] + dx + next_y = robot[:y] + dy + + if grid[next_x][next_y] == '.' + grid[robot[:x]][robot[:y]] = '.' + robot[:x] = next_x + robot[:y] = next_y + grid[robot[:x]][robot[:y]] = '@' + elsif grid[next_x][next_y] == 'O' + current_x, current_y = next_x, next_y + boxes_to_move = [] + + while grid[current_x][current_y] == 'O' + boxes_to_move << [current_x, current_y] + current_x += dx + current_y += dy + end + + if grid[current_x][current_y] == '.' + + grid[robot[:x]][robot[:y]] = '.' + robot[:x] = next_x + robot[:y] = next_y + grid[current_x][current_y] = 'O' + grid[robot[:x]][robot[:y]] = '@' + end + end + + #puts grid.map { |row| row.join('') }.join(""\n"") + #puts + +end + +sum = 0 +grid.each_with_index do |row, y| + + row.each_with_index do |cell, x| + sum += (x + y*100) if cell == 'O' + end +end + +puts sum",ruby +632,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,"#! /usr/bin/env ruby + +#------------------------------------------------------------------------------ +Point = Data.define(:x, :y) do + def to_s + ""[#{x}, #{y}]"" + end + + def +(other) + Point.new(x + other.x, y + other.y) + end + + def -(other) + Point.new(x - other.x, y - other.y) + end + + def distance(other) + (x - other.x).abs + (y - other.y).abs + end + + def vector(other) + Point.new(other.x - x, other.y - y) + end +end + +#------------------------------------------------------------------------------ +module Direction + UP = Point.new(0, -1) + DOWN = Point.new(0, +1) + LEFT = Point.new(-1, 0) + RIGHT = Point.new(+1, 0) + + ALL = [UP, DOWN, LEFT, RIGHT] + + MOVEMENTS = { + '>' => RIGHT, + '<' => LEFT, + '^' => UP, + 'v' => DOWN + } +end + +#------------------------------------------------------------------------------ +class Map + def initialize(lines) + @lines = lines + end + + def width + @lines.first.size + end + + def height + @lines.size + end + + def cell(point) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] + end + + def set(point, value) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] = value + end + + def each_point + 0.upto(height - 1) do |y| + 0.upto(width - 1) do |x| + yield Point.new(x, y) + end + end + end + + def to_s + @lines.join(""\n"") + end + + def inspect + result = <<~MAP + Map #{width}x#{height}: + #{to_s} + MAP + result + end +end + +#------------------------------------------------------------------------------ +def execute_movement(map, object_coordinates, direction) + object_cell = map.cell(object_coordinates) + # puts ""Executing movement #{direction} at #{object_coordinates} for object #{object_cell}"" + + neighbor_coordinates = object_coordinates + direction + neighbor_cell = map.cell(neighbor_coordinates) + # puts ""Neighbor coordinates: #{neighbor_coordinates}, neighbor cell: #{neighbor_cell}"" + + # Stop if we hit a wall + if neighbor_cell == '#' + # puts ""The neighbor is a wall, can't move"" + return object_coordinates + end + + # If we hit an object, we need to try pushing the object in the same direction + if neighbor_cell == 'O' + # puts ""The neighbor is an object, trying to push it"" + resulting_coordinates = execute_movement(map, neighbor_coordinates, direction) + if resulting_coordinates == neighbor_coordinates # the object did not move + # puts ""The object did not move, can't push it, so our position is unchanged"" + return object_coordinates + end + end + + # The space is empty (originally or after pushing the neighbor away), + # so we move the object to the neighbor coordinates + map.set(object_coordinates, '.') + map.set(neighbor_coordinates, object_cell) + neighbor_coordinates +end + +#------------------------------------------------------------------------------ +def execute_movements(map, robot_coordinates, movements) + movements.each_char do |movement| + direction = Direction::MOVEMENTS[movement] + robot_coordinates = execute_movement(map, robot_coordinates, direction) + end +end + +#------------------------------------------------------------------------------ +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file) + +map_size = lines.first.strip.length +map_lines = lines[0..map_size - 1].map(&:strip) +map = Map.new(map_lines) +movements = lines[map_size + 1..-1].map(&:strip).join + +robot_coordinates = nil +map.each_point do |p| + robot_coordinates = p if map.cell(p) == '@' +end + +execute_movements(map, robot_coordinates, movements) + +gps_sum = 0 +map.each_point do |p| + next unless map.cell(p) == 'O' + gps = 100 * p.y + p.x + gps_sum += gps +end + +puts ""GPS sum: #{gps_sum}"" + +# 1413675 - Correct",ruby +633,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +module Direction + UP = '^' + LEFT = '<' + DOWN = 'v' + RIGHT = '>' +end + +class Place + module Type + EMPTY = '.' + WALL = '#' + CRATE = 'O' + ROBOT = '@' + end + + + attr_accessor :type + + @@map = nil + @@robot = nil + + def self.map=(map) + @@map = map + end + + def self.map + @@map + end + + def self.print_map + @@map.each do |line| + puts line.join + end + end + + def initialize(char, x, y) + @type = char + @x = x + @y = y + @@robot = self if @type == Type::ROBOT + end + + def to_s + @type + end + + def self.move_robot(direction) + @@robot.pushed_by?(Type::EMPTY, direction) + end + + def neighbour(direction) + case direction + when Direction::UP + @@map[@y - 1][@x] + when Direction::LEFT + @@map[@y][@x - 1] + when Direction::DOWN + @@map[@y + 1][@x] + when Direction::RIGHT + @@map[@y][@x + 1] + end + end + + def pushed_by?(other_type, direction) + pushed = + case @type + when Type::WALL + false + when Type::EMPTY + true + else + neighbour(direction).pushed_by?(@type, direction) + end + if pushed + @type = other_type + @@robot = self if @type == Type::ROBOT + end + pushed + end + + def gps_coordinates + return 0 unless @type == Type::CRATE + 100 * @y + @x + end + + def self.map_gps_value + @@map.sum do |line| + line.sum(&:gps_coordinates) + end + end +end + +map_input, moves = File.read(path).split(""\n\n"") +map_input = map_input.split(""\n"").map(&:chars) + +Place.map = Array.new(map_input.count) { Array.new(map_input.first.count) } + +map_input.each_with_index do |line, y| + line.each_with_index do |c, x| + Place.map[y][x] = Place.new(c, x, y) + end +end + +p 'Initial state:' +Place.print_map +moves.split(""\n"").flat_map(&:chars).each do |dir| + Place.move_robot(dir) +end + +p 'Final state:' +Place.print_map + +p ""Sum of all boxes' GPS coordinates: #{Place.map_gps_value}""",ruby +634,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 parse_input + boxes = Set.new + walls = Set.new + moves = [] + robot = nil + rows = 0 + cols = 0 + current_section = :grid + + File.foreach('inputs/15', chomp: true).with_index do |line, i| + if line.empty? + current_section = :moves + next + end + + case current_section + when :grid + cols = line.size + line.chars.each_with_index do |char, pos| + case char + when '@' + robot = [i, pos] + when 'O' + boxes << [i, pos] + when '#' + walls << [i, pos] + end + end + rows = i if line.match?(/\A#+\z/) + when :moves + moves.concat(line.chars) + end + end + + [walls, boxes, moves, robot, rows, cols] +end + +def next_position((x, y), direction) + case direction + when '^' then [x - 1, y] + when 'v' then [x + 1, y] + when '<' then [x, y - 1] + when '>' then [x, y + 1] + end +end + +def out_bounds?(row, col, rows, cols) + row < 0 || row >= rows || col < 0 || col >= cols +end + +def solve + walls, boxes, moves, robot, rows, cols = parse_input + + moves.each do |move| + next_pos = next_position(robot, move) + next if out_bounds?(*next_pos, rows, cols) || walls.include?(next_pos) + + if boxes.include?(next_pos) + # Find the last box in a sequence of boxes + new_box_position = next_pos + new_box_position = next_position(new_box_position, move) while boxes.include?(new_box_position) + next if out_bounds?(*new_box_position, rows, cols) || walls.include?(new_box_position) + + # Remove first box in the sequence (the new robot position) + # and add a box at the end of the sequence + boxes.delete(next_pos) + boxes << new_box_position + end + + robot = next_pos + end + + # Calculate the sum of the Goods Positioning System + boxes.sum { |x, y| 100 * x + y } +end + +puts solve",ruby +635,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..# +#.....# +####### + +"" + $robot_position[1] += 1 if can_move?($robot_position, instruction) + when ""^"" + $robot_position[0] -= 1 if can_move?($robot_position, instruction) + when ""v"" + $robot_position[0] += 1 if can_move?($robot_position, instruction) + end + end + $boxes.filter! { |k, v| v }.sort { |a, b| a[0] <=> b[0] } + score = $boxes.map { |k, v| k[0] * 100 + k[1] }.sum + score +end + + +def can_move?(position, direction) + x, y = position + case direction + when ""<"" + if $walls[[x, y-1]] + false + else + if $boxes[[x, y-1]] + if can_move?([x, y-1], direction) + $boxes[[x, y-1]] = false + $boxes[[x, y-2]] = true + true + else + false + end + else + true + end + end + when "">"" + if $walls[[x, y+1]] + false + else + if $boxes[[x, y+1]] + if can_move?([x, y+1], direction) + $boxes[[x, y+1]] = false + $boxes[[x, y+2]] = true + true + else + false + end + else + true + end + end + when ""^"" + if $walls[[x-1, y]] + false + else + if $boxes[[x-1, y]] + if can_move?([x-1, y], direction) + $boxes[[x-1, y]] = false + $boxes[[x-2, y]] = true + true + else + false + end + else + true + end + end + when ""v"" + if $walls[[x+1, y]] + false + else + if $boxes[[x+1, y]] + if can_move?([x+1, y], direction) + $boxes[[x+1, y]] = false + $boxes[[x+2, y]] = true + true + else + false + end + else + true + end + end + end +end + +p ""Part 1: #{part_1}"" + +$grid_2 = $grid.map do |row| + row.map do |cell| + if cell == ""@"" + ""@."".chars + elsif cell == ""#"" + ""##"".chars + elsif cell == ""O"" + ""[]"".chars + elsif cell == ""."" + "".."".chars + end + end +end + +$grid_2.map! do |row| + row.flatten! +end + +$robot_position = nil +$walls = {} +$left_boxes = {} +$right_boxes = {} +$grid_2.each_with_index do |row, i| + row.each_with_index do |cell, j| + if cell == ""@"" + $robot_position = [i, j] + elsif cell == ""#"" + $walls[[i, j]] = true + elsif cell == ""["" + $left_boxes[[i, j]] = true + elsif cell == ""]"" + $right_boxes[[i, j]] = true + end + end +end + +def part_2 + $instructions.each do |instruction| + case instruction + when ""<"" + if can_move_2?($robot_position, instruction) + move_2($robot_position, instruction) + $robot_position[1] -= 1 + end + when "">"" + if can_move_2?($robot_position, instruction) + move_2($robot_position, instruction) + $robot_position[1] += 1 + end + when ""^"" + if can_move_2?($robot_position, instruction) + move_2($robot_position, instruction) + $robot_position[0] -= 1 + end + when ""v"" + if can_move_2?($robot_position, instruction) + move_2($robot_position, instruction) + $robot_position[0] += 1 + end + end + end + + $left_boxes.filter! { |k, v| v }.sort { |a, b| a[0] <=> b[0] } + $right_boxes.filter! { |k, v| v }.sort { |a, b| a[0] <=> b[0] } + + (0...$grid_2.length).each do |i| + line = """" + (0...$grid_2[0].length).each do |j| + if $walls[[i, j]] + line += ""#"" + elsif $left_boxes[[i, j]] + line += ""["" + elsif $right_boxes[[i, j]] + line += ""]"" + else + line += ""."" + end + end + p line + end + score = $left_boxes.map { |k, v| (k[0] * 100) + k[1] }.sum + score +end + + +def can_move_2?(position,instruction) + x, y = position + case instruction + when ""<"" + if $walls[[x, y-1]] + false + else + if $right_boxes[[x, y-1]] + if can_move_2?([x, y-2], instruction) + # $right_boxes[[x, y-1]] = false + # $left_boxes[[x, y-2]] = false + # $right_boxes[[x, y-2]] = true + # $left_boxes[[x, y-3]] = true + true + else + false + end + else + true + end + end + when "">"" + if $walls[[x, y+1]] + false + else + if $left_boxes[[x, y+1]] + if can_move_2?([x, y+2], instruction) + # $left_boxes[[x, y+1]] = false + # $left_boxes[[x, y+2]] = true + # $right_boxes[[x, y+2]] = false + # $right_boxes[[x, y+3]] = true + true + else + false + end + else + true + end + end + when ""^"" + if $walls[[x-1, y]] + false + elsif $right_boxes[[x-1, y]] + if can_move_double_box_up?([x-1, y-1], [x-1, y]) + # $right_boxes[[x-1, y]] = false + # $left_boxes[[x-1, y-1]] = false + # $right_boxes[[x-2, y]] = true + # $left_boxes[[x-2, y-1]] = true + true + else + false + end + elsif $left_boxes[[x-1, y]] + if can_move_double_box_up?([x-1, y], [x-1, y+1]) + # $left_boxes[[x-1, y]] = false + # $right_boxes[[x-1, y+1]] = false + # $left_boxes[[x-2, y]] = true + # $right_boxes[[x-2, y+1]] = true + true + else + false + end + else + true + end + when ""v"" + if $walls[[x+1, y]] + false + elsif $right_boxes[[x+1, y]] + if can_move_double_box_down?([x+1, y-1], [x+1, y]) + # $right_boxes[[x+1, y]] = false + # $left_boxes[[x+1, y-1]] = false + # $right_boxes[[x+2, y]] = true + # $left_boxes[[x+2, y-1]] = true + true + else + false + end + elsif $left_boxes[[x+1, y]] + if can_move_double_box_down?([x+1, y], [x+1, y+1]) + # $left_boxes[[x+1, y]] = false + # $right_boxes[[x+1, y+1]] = false + # $left_boxes[[x+2, y]] = true + # $right_boxes[[x+2, y+1]] = true + true + else + false + end + else + true + end + end +end + +def can_move_double_box_up?(position1, position2) + x1, y1 = position1 + x2, y2 = position2 + left_can_move_up = true + right_can_move_up = true + if $walls[[x1-1, y1]] || $walls[[x2-1, y2]] + return false + end + if $right_boxes[[x1-1, y1]] + if can_move_double_box_up?([x1-1, y1-1], [x1-1, y1]) + left_can_move_up = true + else + return false + end + end + if $left_boxes[[x2-1, y2]] + if can_move_double_box_up?([x2-1, y2], [x2-1, y2+1]) + right_can_move_up = true + else + return false + end + end + if $left_boxes[[x1-1, y1]] && $right_boxes[[x2-1, y2]] + if can_move_double_box_up?([x1-1, y1], [x2-1, y2]) + # $left_boxes[[x1-1, y1]] = false + # $right_boxes[[x2-1, y2]] = false + # $left_boxes[[x1-2, y1]] = true + # $right_boxes[[x2-2, y2]] = true + return true + else + return false + end + end + if left_can_move_up && right_can_move_up + if $left_boxes[[x2-1, y2]] + # $left_boxes[[x2-1, y2]] = false + # $right_boxes[[x2-1, y2+1]] = false + # $left_boxes[[x2-2, y2]] = true + # $right_boxes[[x2-2, y2+1]] = true + end + if $right_boxes[[x1-1, y1]] + # $right_boxes[[x1-1, y1]] = false + # $left_boxes[[x1-1, y1-1]] = false + # $right_boxes[[x1-2, y1]] = true + # $left_boxes[[x1-2, y1-1]] = true + end + return true + end +end + +def can_move_double_box_down?(position1, position2) + x1, y1 = position1 + x2, y2 = position2 + left_can_move_down = true + right_can_move_down = true + if $walls[[x1+1, y1]] || $walls[[x2+1, y2]] + return false + end + if $right_boxes[[x1+1, y1]] + if can_move_double_box_down?([x1+1, y1-1], [x1+1, y1]) + left_can_move_down = true + else + return false + end + end + if $left_boxes[[x2+1, y2]] + if can_move_double_box_down?([x2+1, y2], [x2+1, y2+1]) + right_can_move_down = true + else + return false + end + end + if $left_boxes[[x1+1, y1]] && $right_boxes[[x2+1, y2]] + if can_move_double_box_down?([x1+1, y1], [x2+1, y2]) + # $left_boxes[[x1+1, y1]] = false + # $right_boxes[[x2+1, y2]] = false + # $left_boxes[[x1+2, y1]] = true + # $right_boxes[[x2+2, y2]] = true + return true + else + return false + end + end + if left_can_move_down && right_can_move_down + if $left_boxes[[x2+1, y2]] + # $left_boxes[[x2+1, y2]] = false + # $right_boxes[[x2+1, y2+1]] = false + # $left_boxes[[x2+2, y2]] = true + # $right_boxes[[x2+2, y2+1]] = true + end + if $right_boxes[[x1+1, y1]] + # $right_boxes[[x1+1, y1]] = false + # $left_boxes[[x1+1, y1-1]] = false + # $right_boxes[[x1+2, y1]] = true + # $left_boxes[[x1+2, y1-1]] = true + end + return true + end +end + +def move_2(position,instruction) + x, y = position + case instruction + when ""<"" + if $walls[[x, y-1]] + false + else + if $right_boxes[[x, y-1]] + move_2([x, y-2], instruction) + $right_boxes[[x, y-1]] = false + $left_boxes[[x, y-2]] = false + $right_boxes[[x, y-2]] = true + $left_boxes[[x, y-3]] = true + end + end + when "">"" + if $walls[[x, y+1]] + false + else + if $left_boxes[[x, y+1]] + move_2([x, y+2], instruction) + $left_boxes[[x, y+1]] = false + $left_boxes[[x, y+2]] = true + $right_boxes[[x, y+2]] = false + $right_boxes[[x, y+3]] = true + end + end + when ""^"" + if $walls[[x-1, y]] + false + elsif $right_boxes[[x-1, y]] + move_double_box_up?([x-1, y-1], [x-1, y]) + $right_boxes[[x-1, y]] = false + $left_boxes[[x-1, y-1]] = false + $right_boxes[[x-2, y]] = true + $left_boxes[[x-2, y-1]] = true + elsif $left_boxes[[x-1, y]] + move_double_box_up?([x-1, y], [x-1, y+1]) + $left_boxes[[x-1, y]] = false + $right_boxes[[x-1, y+1]] = false + $left_boxes[[x-2, y]] = true + $right_boxes[[x-2, y+1]] = true + end + when ""v"" + if $walls[[x+1, y]] + false + elsif $right_boxes[[x+1, y]] + move_double_box_down?([x+1, y-1], [x+1, y]) + $right_boxes[[x+1, y]] = false + $left_boxes[[x+1, y-1]] = false + $right_boxes[[x+2, y]] = true + $left_boxes[[x+2, y-1]] = true + elsif $left_boxes[[x+1, y]] + move_double_box_down?([x+1, y], [x+1, y+1]) + $left_boxes[[x+1, y]] = false + $right_boxes[[x+1, y+1]] = false + $left_boxes[[x+2, y]] = true + $right_boxes[[x+2, y+1]] = true + end + end +end + +def move_double_box_up?(position1, position2) + x1, y1 = position1 + x2, y2 = position2 + left_can_move_up = true + right_can_move_up = true + if $walls[[x1-1, y1]] || $walls[[x2-1, y2]] + return false + end + if $right_boxes[[x1-1, y1]] + move_double_box_up?([x1-1, y1-1], [x1-1, y1]) + $right_boxes[[x1-1, y1]] = false + $left_boxes[[x1-1, y1-1]] = false + $right_boxes[[x1-2, y1]] = true + $left_boxes[[x1-2, y1-1]] = true + end + if $left_boxes[[x2-1, y2]] + move_double_box_up?([x2-1, y2], [x2-1, y2+1]) + $left_boxes[[x2-1, y2]] = false + $right_boxes[[x2-1, y2+1]] = false + $left_boxes[[x2-2, y2]] = true + $right_boxes[[x2-2, y2+1]] = true + end + if $left_boxes[[x1-1, y1]] && $right_boxes[[x2-1, y2]] + move_double_box_up?([x1-1, y1], [x2-1, y2]) + $left_boxes[[x1-1, y1]] = false + $right_boxes[[x2-1, y2]] = false + $left_boxes[[x1-2, y1]] = true + $right_boxes[[x2-2, y2]] = true + end +end + +def move_double_box_down?(position1, position2) + x1, y1 = position1 + x2, y2 = position2 + left_can_move_down = true + right_can_move_down = true + if $walls[[x1+1, y1]] || $walls[[x2+1, y2]] + return false + end + if $right_boxes[[x1+1, y1]] + move_double_box_down?([x1+1, y1-1], [x1+1, y1]) + $right_boxes[[x1+1, y1]] = false + $left_boxes[[x1+1, y1-1]] = false + $right_boxes[[x1+2, y1]] = true + $left_boxes[[x1+2, y1-1]] = true + end + if $left_boxes[[x2+1, y2]] + move_double_box_down?([x2+1, y2], [x2+1, y2+1]) + $left_boxes[[x2+1, y2]] = false + $right_boxes[[x2+1, y2+1]] = false + $left_boxes[[x2+2, y2]] = true + $right_boxes[[x2+2, y2+1]] = true + end + if $left_boxes[[x1+1, y1]] && $right_boxes[[x2+1, y2]] + move_double_box_down?([x1+1, y1], [x2+1, y2]) + $left_boxes[[x1+1, y1]] = false + $right_boxes[[x2+1, y2]] = false + $left_boxes[[x1+2, y1]] = true + $right_boxes[[x2+2, y2]] = true + end +end + +p ""Part 2: #{part_2}""",ruby +636,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..# +#.....# +####### + +' then Move.new(0, 1) + when 'v' then Move.new(1, 0) + when '<' then Move.new(0, -1) + else raise ""Illegal movement: #{move}"" + end +end + +# puts 'Movements' +# puts '---------' +# puts movements +# puts + +def swap_single(map, position, new_position) + map[position.x][position.y], map[new_position.x][new_position.y] = map[new_position.x][new_position.y], map[position.x][position.y] +end + +def swap_many(map, positions, new_positions) + positions.zip(new_positions).each do |position, new_position| + swap_single(map, position, new_position) + end +end + +def obstructed?(map, positions) + positions.any? { |position| map[position.x][position.y] == '#' } +end + +def all_clear?(map, positions) + positions.all? { |position| map[position.x][position.y] == '.' } +end + +def can_move?(map, positions, move) + new_positions = positions.map { |position| position + move } + + return false if obstructed?(map, new_positions) + return true if all_clear?(map, new_positions) + + new_positions.all? do |new_position| + case map[new_position.x][new_position.y] + when '[' then can_move?(map, [new_position, Coord.new(new_position.x, new_position.y + 1)], move) + when ']' then can_move?(map, [Coord.new(new_position.x, new_position.y - 1), new_position], move) + when '.' then true + else raise ""Unknown thing at map #{new_position}: #{map[new_position.x][new_position.y]}"" + end + end +end + +def one_movement(map, positions, move) + new_positions = positions.map { |position| position + move } + + if obstructed?(map, new_positions) + puts 'No nothing' + return positions + end + + if all_clear?(map, new_positions) + puts 'Move to empty space' + swap_many(map, positions, new_positions) + return new_positions + end + + if move.horizontal? + puts 'Attempt to move box horizontally' + one_movement(map, new_positions, move) + if all_clear?(map, new_positions) + puts 'Move to now empty space' + swap_many(map, positions, new_positions) + return new_positions + else + return positions + end + else + puts 'Attempt to move box(es) vertically' + + box_positions = new_positions.collect do |new_position| + case map[new_position.x][new_position.y] + when '[' then [new_position, Coord.new(new_position.x, new_position.y + 1)] + when ']' then [Coord.new(new_position.x, new_position.y - 1), new_position] + when '.' then [] + else raise ""Unknown thing at map #{new_position}: #{map[new_position.x][new_position.y]}"" + end + end.flatten.uniq + + if can_move?(map, box_positions, move) + one_movement(map, box_positions, move) + swap_many(map, positions, new_positions) + return new_positions + else + puts 'Cannot move boxes' + return positions + end + end +end + +movements.each do |move| + puts ""Move: #{move}"" + robot = one_movement(map, [robot], move).first + # print_map(map) + # puts +end + +def get_box_coords(map) + map.collect.with_index do |row, x| + row.collect.with_index do |cell, y| + (cell == '[') ? Coord.new(x, y) : nil + end + end.flatten.compact +end + +coordinates = get_box_coords(map) + +# puts 'Coordinates' +# puts '-----------' +# puts coordinates +# puts + +total = coordinates.sum(&:gps) + +puts +puts ""Total: #{total}""",ruby +637,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], '^' => [-1, 0], '<' => [0, -1], '>' => [0, 1] } + +moves.each_with_index do |move, i| + dx, dy = dirs[move] + + next_x = robot[:x] + dx + next_y = robot[:y] + dy + + if grid[next_x][next_y] == '.' + grid[robot[:x]][robot[:y]] = '.' + robot[:x] = next_x + robot[:y] = next_y + grid[robot[:x]][robot[:y]] = '@' + elsif grid[next_x][next_y] == '[' || grid[next_x][next_y] == ']' + + if move == '<' || move == '>' + current_x, current_y = next_x, next_y + boxes_to_move = [] + + while grid[current_x][current_y] == '[' || grid[current_x][current_y] == ']' + boxes_to_move << [current_x, current_y, grid[current_x][current_y]] + current_x += dx + current_y += dy + end + + if grid[current_x][current_y] == '.' + + grid[robot[:x]][robot[:y]] = '.' + robot[:x] = next_x + robot[:y] = next_y + grid[robot[:x]][robot[:y]] = '@' + + boxes_to_move.each do |box| + grid[box[0] + dx][box[1] + dy] = box[2] + end + end + else + current = [{x: next_x, y:next_y, box: grid[next_x][next_y]}] + if current.first[:box] == '[' + current.push({x: next_x, y: next_y + 1, box: grid[next_x][next_y + 1]}) + else + current.push({x: next_x, y: next_y - 1, box: grid[next_x][next_y - 1]}) + end + + current.sort_by! { |c| c[:y] } + boxes_to_move = [] + boxes_to_move.push(current) + can_move = false + + loop do + current = current.map do |c| + { x: c[:x] + dx, y: c[:y], box: grid[c[:x] + dx][c[:y]] } + end + + if current.all? { |c| c[:box] == '.' } + can_move = true + break + end + + if current.all? { |c| c[:box] == '[' || c[:box] == ']' || c[:box] == '.' } + current = current.select { |c| c[:box] == '[' || c[:box] == ']' } + current.unshift({x: current.first[:x], y:current.first[:y]-1, box:'['}) if current.first[:box] == ']' + current.push({x: current.last[:x], y:current.last[:y]+1, box:']'}) if current.last[:box] == '[' + + boxes_to_move.push(current) + else + break + end + end + + if can_move + grid[robot[:x]][robot[:y]] = '.' + + boxes_to_move.each do |boxes| + boxes.each do |box| + grid[box[:x]][box[:y]] = '.' + end + end + + + boxes_to_move.each do |boxes| + boxes.each do |box| + grid[box[:x] + dx][box[:y]] = box[:box] + end + end + + robot[:x] = next_x + robot[:y] = next_y + grid[robot[:x]][robot[:y]] = '@' + end + + end + end + +end + +sum = 0 +grid.each_with_index do |row, y| + + row.each_with_index do |cell, x| + sum += (x + y*100) if cell == '[' + end +end + +puts sum",ruby +638,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..# +#.....# +####### + +' => RIGHT, + '<' => LEFT, + '^' => UP, + 'v' => DOWN + } +end + +#------------------------------------------------------------------------------ +class Map + def initialize(lines) + @lines = lines + end + + def width + @lines.first.size + end + + def height + @lines.size + end + + def cell(point) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] + end + + def set(point, value) + return nil if point.y < 0 || point.y >= height + return nil if point.x < 0 || point.x >= width + + @lines[point.y][point.x] = value + end + + def each_point + 0.upto(height - 1) do |y| + 0.upto(width - 1) do |x| + yield Point.new(x, y) + end + end + end + + def to_s + @lines.join(""\n"") + end + + def inspect + result = <<~MAP + Map #{width}x#{height}: + #{to_s} + MAP + result + end + + def move(from, to) + object = cell(from) + set(from, '.') + set(to, object) + end +end + +#------------------------------------------------------------------------------ +def box?(cell) + cell == '[' || cell == ']' +end + +def wall?(cell) + cell == '#' +end + +def robot?(cell) + cell == '@' +end + +def empty?(cell) + cell == '.' +end + +#------------------------------------------------------------------------------ +def parts_for_object_at(map, object_coordinates) + object_part = map.cell(object_coordinates) + # There are no parts for empty space + return [] if empty?(object_part) + + # The robot is a single part + return [object_coordinates] if robot?(object_part) + + # The object is a box (left part) + if object_part == '[' + return [object_coordinates, object_coordinates + Direction::RIGHT] + end + + # The object is a box (right part) + if object_part == ']' + return [object_coordinates + Direction::LEFT, object_coordinates] + end + + raise ""Unknown object part: #{object_part} at #{object_coordinates}"" +end + +#------------------------------------------------------------------------------ +def execute_horizontal_movement(map, object_coordinates, direction) + neighbor_coordinates = object_coordinates + direction + neighbor = map.cell(neighbor_coordinates) + + # Stop if we hit a wall + return object_coordinates if wall?(neighbor) + + # If we hit a box, we need to try pushing it in the same direction + if box?(neighbor) + resulting_coordinates = execute_horizontal_movement(map, neighbor_coordinates, direction) + return object_coordinates if resulting_coordinates == neighbor_coordinates # the box did not move + end + + # The space is empty (originally or after pushing the neighbor away), + # so we move the object to the neighbor coordinates + map.move(object_coordinates, neighbor_coordinates) + + neighbor_coordinates +end + +#------------------------------------------------------------------------------ +# Check if we can move the object vertically (recursively checks each part of the object and its neighbours) +def can_move_vertically?(map, object_coordinates, direction) + # If the cell is empty, we can move an object here + return true if empty?(map.cell(object_coordinates)) + + object_parts = parts_for_object_at(map, object_coordinates) + neighbour_coordinates = object_parts.map { |part| part + direction } + + # If any of the neighbours are walls, we can't move the current object + return false if neighbour_coordinates.any? { |neighbour| wall?(map.cell(neighbour)) } + + # If none of the neighbours are walls, we need to check if we can move all non-empty neighbours + neighbour_coordinates.all? { |neighbour| can_move_vertically?(map, neighbour, direction) } +end + +#------------------------------------------------------------------------------ +# Moves an object identified by coordinates of one of its parts in a given direction assuming +# it is OK to perform the move (since we already checked that in can_move_vertically?) +def move_vertically(map, object_coordinates, direction) + object_parts = parts_for_object_at(map, object_coordinates) + neighbour_coordinates = object_parts.map { |part| part + direction } + + neighbour_coordinates.each do |neighbour| + if box?(map.cell(neighbour)) + move_vertically(map, neighbour, direction) + end + end + + object_parts.each do |part| + map.move(part, part + direction) + end + + object_coordinates + direction +end + +#------------------------------------------------------------------------------ +# Safely tries to move the object identified by coordinates of one of its parts one step in a given direction +def execute_vertical_movement(map, object_coordinates, direction) + # Check if we can move the object vertically (recursively checks each part of the object and its neighbours) + return object_coordinates unless can_move_vertically?(map, object_coordinates, direction) + + # Perform the actual move if we know it is OK to do so + move_vertically(map, object_coordinates, direction) +end + +#------------------------------------------------------------------------------ +def execute_movements(map, movements) + # Find the robot + robot_coordinates = nil + map.each_point do |p| + robot_coordinates = p if robot?(map.cell(p)) + end + + # Execute each movement in the sequence, moving the robot each time + movements.each_char do |movement| + direction = Direction::MOVEMENTS[movement] + robot_coordinates = if direction.vertical? + execute_vertical_movement(map, robot_coordinates, direction) + else + execute_horizontal_movement(map, robot_coordinates, direction) + end + end +end + +#------------------------------------------------------------------------------ +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file) + +map_size = lines.first.strip.length +map_lines = lines[0...map_size].map(&:strip) + +# Render the map by replacing each cell with a cell twice as wide +# 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. +rendered_map_lines = map_lines.map do |line| + line.chars.map do |char| + char == '#' ? '##' : char == 'O' ? '[]' : char == '.' ? '..' : char == '@' ? '@.' : char + end.join +end + +map = Map.new(rendered_map_lines) +movements = lines[map_size + 1..-1].map(&:strip).join + +# Execute all the movements +execute_movements(map, movements) + +# Calculate the GPS value for all boxes (using their left side to calculate the distance from the left edge) +gps_sum = 0 +map.each_point do |p| + next unless map.cell(p) == '[' + gps_sum += 100 * p.y + p.x +end + +puts ""GPS sum: #{gps_sum}""",ruby +639,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..# +#.....# +####### + +' + Coordinate.new(1, 0) + when '<' + Coordinate.new(-1, 0) + end +end + +def perform_move!(map, move) + mv = movement_vector(move) + + potential_location = map[:robot] + mv + box_count = 0 + while map[:boxes].include?(potential_location) + potential_location += mv + box_count += 1 + end + + # Can't move if this hits a wall + return map if map[:walls].include?(potential_location) + + map[:boxes].add(map[:robot] + mv.times(box_count + 1)) + map[:boxes].delete(map[:robot] + mv) + map[:robot] += mv +end + +def perform_move_wide_boxes!(map, move) + mv = movement_vector(move) + + return map if map[:walls].include?(map[:robot] + mv) + + if ['>', '<'].include?(move) + potential_location = map[:robot] + mv + + boxes_to_move = { left: Set.new, right: Set.new } + while map[:boxes_left].include?(potential_location) || map[:boxes_right].include?(potential_location) + boxes_to_move[:left].add(potential_location) if map[:boxes_left].include?(potential_location) + boxes_to_move[:right].add(potential_location) if map[:boxes_right].include?(potential_location) + potential_location += mv + end + + return map if map[:walls].include?(potential_location) + + boxes_to_move[:left].each do |b| + map[:boxes_left].delete(b) + map[:boxes_left].add(b + mv) + end + + boxes_to_move[:right].each do |b| + map[:boxes_right].delete(b) + map[:boxes_right].add(b + mv) + end + + map[:robot] += mv + return map + end + + potential_locations = Set[map[:robot] + mv] + boxes_to_move = { left: Set.new, right: Set.new } + + reached_space = !map[:boxes_left].include?(map[:robot] + mv) && !map[:boxes_right].include?(map[:robot] + mv) + + until reached_space + new_potential_locations_used = Set.new + map[:boxes_left].intersection(potential_locations).each do |b| + boxes_to_move[:left].add(b) + boxes_to_move[:right].add(b + Coordinate.new(1, 0)) + new_potential_locations_used.add(b + mv) + new_potential_locations_used.add(b + mv + Coordinate.new(1, 0)) + end + + map[:boxes_right].intersection(potential_locations).each do |b| + boxes_to_move[:right].add(b) + boxes_to_move[:left].add(b - Coordinate.new(1, 0)) + new_potential_locations_used.add(b + mv) + new_potential_locations_used.add(b + mv - Coordinate.new(1, 0)) + end + + return map if map[:walls].intersect?(new_potential_locations_used) + + unless map[:boxes_left].intersect?(new_potential_locations_used) || map[:boxes_right].intersect?(new_potential_locations_used) + reached_space = true + end + + potential_locations = new_potential_locations_used + end + + map[:robot] += mv + # Either both or neither sholud be empty + return map if boxes_to_move[:left].empty? + + map[:boxes_left] -= boxes_to_move[:left] + map[:boxes_left] += (boxes_to_move[:left].map { |box| box + mv }) + + map[:boxes_right] -= boxes_to_move[:right] + map[:boxes_right] += (boxes_to_move[:right].map { |box| box + mv }) + + map +end + +def sum_box_gps_coordinates(map) + map[:boxes].sum { |box| box.x + 100 * box.y } +end + +def sum_box_gps_coordinates2(map) + map[:boxes_left].sum { |box| box.x + 100 * box.y } +end + +def part1 + map, movements = parse + movements.each do |move| + perform_move!(map, move) + end + sum_box_gps_coordinates(map) +end + +def part2 + map, movements = parse + map = twice_as_wide(map) + movements.each do |move| + perform_move_wide_boxes!(map, move) + end + + sum_box_gps_coordinates2(map) +end + +puts 'Part 1' +puts part1 +puts '---' +puts 'Part 2' +puts part2",ruby +640,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,"class Point + attr_accessor :y, :x + + def initialize(y, x) + @y = y + @x = x + end + + def eql?(other) + other.is_a?(Point) && @y == other.y && @x == other.x + end + + def hash + @y.hash ^ @x.hash + end +end + +class Position + attr_accessor :point, :direction + + def initialize(point, direction) + @point = point + @direction = direction + end + + def ==(other) + eql?(other) + end + + def eql?(other) + other.is_a?(Position) && @point.eql?(other.point) && @direction == other.direction + end + + def hash + @point.hash ^ @direction.hash + end +end + +DIRECTIONS = [0, 90, 180, 270].freeze + +def ahead(position) + point_ahead = case position.direction + when 0 + Point.new(position.point.y - 1, position.point.x) + when 90 + Point.new(position.point.y, position.point.x + 1) + when 180 + Point.new(position.point.y + 1, position.point.x) + else # 270 + Point.new(position.point.y, position.point.x - 1) + end + Position.new(point_ahead, position.direction) +end + +def left(position) + Position.new(position.point, (position.direction - 90) % 360) +end + +def right(position) + Position.new(position.point, (position.direction + 90) % 360) +end + +def next_positions(position) + [ahead(position), left(position), right(position)] +end + +# Breadth-first search. +def lowest_score_to_end_point(map, start_position, end_point) + queue = [start_position] + while queue.size > 0 + position = queue.shift + + if position.point.eql?(end_point) + return map[position] + end + + next_positions(position).each do |next_position| + next unless map.key?(next_position) + + next_position_score_delta = next_position.point.eql?(position.point) ? 1000 : 1 + next if map[next_position] <= map[position] + next_position_score_delta + + # Don't turn towards a wall + next if next_position.point.eql?(position.point) && !map.key?(ahead(next_position)) + + map[next_position] = map[position] + next_position_score_delta + + queue << (next_position) + end + + # Sort the queue by the lowest score, such that as soon as we reach the end point, + # we're guaranteed that the score is the lowest possible to reach it (because no + # subsequent moves could possibly have a lower score). + queue.sort_by! { |position| map[position] } + end + + nil +end + +# Hash map of positions to lowest score to reach that position +map = {} + +start_position = nil +end_point = nil +File.readlines('day-16/input.txt').map(&:chomp).each_with_index do |line, y| + line.each_char.with_index do |char, x| + next if char == '#' + + point = Point.new(y, x) + DIRECTIONS.each do |direction| + position = Position.new(point, direction) + if char == 'S' && direction == 90 + start_position = position + map[position] = 0 + else + map[position] = Float::INFINITY + end + end + if char == 'E' + end_point = point + end + end +end + +pp lowest_score_to_end_point(map, start_position, end_point)",ruby +641,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,"class MinHeap + def initialize + @heap = [] + end + + def push(item) + @heap.push(item) + sift_up(@heap.length - 1) + end + + def pop + return nil if @heap.empty? + + top = @heap[0] + last = @heap.pop + if @heap.any? + @heap[0] = last + sift_down(0) + end + top + end + + def empty? + @heap.empty? + end + + private + + def sift_up(index) + while index > 0 + parent = (index - 1) / 2 + break if @heap[parent][0] <= @heap[index][0] + @heap[parent], @heap[index] = @heap[index], @heap[parent] + index = parent + end + end + + def sift_down(index) + size = @heap.length + while true + left = 2 * index + 1 + right = 2 * index + 2 + smallest = index + + if left < size && @heap[left][0] < @heap[smallest][0] + smallest = left + end + + if right < size && @heap[right][0] < @heap[smallest][0] + smallest = right + end + + break if smallest == index + @heap[index], @heap[smallest] = @heap[smallest], @heap[index] + index = smallest + end + end +end + +def dijkstra(grid) + start = nil + grid.each_with_index do |row, i| + row.each_with_index do |cell, j| + if cell == 'S' + start = [[i, j], [0, 1]] + end + end + end + + pq = MinHeap.new + pq.push([0, start]) + + costs = { start => 0 } + + while !pq.empty? + cost, (pos, direction) = pq.pop + + if grid[pos[0]][pos[1]] == 'E' + return cost + end + + turns = [ + [1000, [pos, [direction[1] * -1, direction[0] * -1]]], + [1000, [pos, [direction[1] * 1, direction[0] * 1]]] + ] + + step = [pos[0] + direction[0], pos[1] + direction[1]] + + neighbors = turns + if grid[step[0]] && grid[step[0]][step[1]] != '#' + neighbors << [1, [step, direction]] + end + + neighbors.each do |neighbor| + next_cost = cost + neighbor[0] + if next_cost < (costs[neighbor[1]] || Float::INFINITY) + pq.push([next_cost, neighbor[1]]) + costs[neighbor[1]] = next_cost + end + end + end + + puts ""Could not find min path"" + nil +end + +grid = File.read('input.txt').strip.split(""\n"").map { |line| line.chars } + +puts dijkstra(grid)",ruby +642,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,"# No priority queue in Ruby I guess? +class Element + + attr_accessor :cost, :location + + def initialize(cost, location, direction) + @cost = cost + @location = location + @direction = direction + end + + def get_values + return @cost, @location, @direction + end + +end + +class MinHeap + + def initialize + @data = [] + @dirty = true + end + + def <<(element) + @dirty = true + @data << element + end + + def swap!(a, b) + temp = @data[b] + @data[b] = @data[a] + @data[a] = temp + end + + def heapify!(i) + if @data.length > 1 + smallest = i + + left = 2 * i + 1 + right = 2 * i + 2 + + smallest = left if left < @data.length && @data[left].cost < @data[smallest].cost + smallest = right if right < @data.length && @data[right].cost < @data[smallest].cost + + if smallest != i + swap!(i, smallest) + heapify!(smallest) + end + end + end + + def get_min + if @data.length > 0 + if @dirty + (@data.length / 2 - 1).downto(0) do |i| + heapify!(i) + @dirty = false + end + end + + elem = @data[0] + swap!(0, @data.length - 1) + @data.pop + + heapify!(0) + end + + elem + end +end + + + +def parse_map(filename) + start_location = nil + map = [] + IO.readlines(filename).map(&:strip).each.with_index do |line, y| + start_location_x = line.index('S') + start_location = [start_location_x, y] if start_location_x + + map.append(line) + end + + return map, start_location +end + +def move(map, location, direction) + next_x, next_y = location + if direction == :right + next_x += 1 + elsif direction == :left + next_x -= 1 + elsif direction == :up + next_y -= 1 + elsif direction == :down + next_y += 1 + else + raise ""Unknown direction #{direction}"" + end + + return nil if (next_x.negative? || next_x > map[0].length - 1) || + (next_y.negative? || next_y > map.length - 1) + + return next_x, next_y +end + +def turn_left(direction) + if direction == :up + return :left + elsif direction == :down + return :right + elsif direction == :left + return :down + elsif direction == :right + return :up + else + raise ""Unknown direction #{direction}"" + end +end + +def turn_right(direction) + if direction == :up + return :right + elsif direction == :down + return :left + elsif direction == :left + return :up + elsif direction == :right + return :down + else + raise ""Unknown direction #{direction}"" + end +end + +def keep_straight(direction) + direction +end + +def debug_map(map, position) + target_x, target_y = position + map.each.with_index do |line, y| + line = line.dup + line[target_x] = 'X' if target_y == y + + puts line + end +end + +def navigate(map, start_location, direction) + initial_cost = 0 + mh = MinHeap.new + mh << Element.new(1, move(map, start_location, :right), :right) + mh << Element.new(1001, move(map, start_location, :up), :up) + + already_visited = {} + + loop do + elem = mh.get_min + cost, location, direction = elem.get_values + x, y = location + + loc_tuple = [location, direction] + + return cost if map[y][x] == ""E"" + + next if already_visited[loc_tuple] == true + next if map[y][x] == ""#"" + + already_visited[loc_tuple] = true + + #puts ""Navigating location #{location}, direction #{direction}, cost #{cost}"" + #debug_map(map, location) + #$stdin.gets + + [:keep_straight, :turn_right, :turn_left].each do |possibility| + new_direction = send(possibility, direction) + new_location = move(map, location, new_direction) + new_cost = possibility == :keep_straight ? cost + 1 : cost + 1001 + + new_elem = Element.new(new_cost, new_location, new_direction) + mh << new_elem + end + end +end + + +map, start_location = parse_map(ARGV[0]) +min_cost = navigate(map, start_location, :right) + +puts ""Minimum cost is #{min_cost}""",ruby +643,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +def where_straight(x, y, dir, map, visited) + where = nil + case dir + when '>' + where = {x: x + 1, y: y} if map[y][x + 1] == '.' || map[y][x + 1] == 'E' + when '<' + where = {x: x -1 , y: y} if map[y][x - 1] == '.' || map[y][x - 1] == 'E' + when '^' + where = {x: x , y: y - 1} if map[y - 1][x] == '.' || map[y - 1][x] == 'E' + when 'v' + where = {x: x , y: y + 1} if map[y + 1][x] == '.' || map[y + 1][x] == 'E' + end + + where = nil if !where.nil? && visited.has_key?(""#{where[:x]},#{where[:y]}"") + + return where +end + +def where_left(x, y, dir, map, visited) + where = nil + case dir + when '>' + where = {x: x, y: y - 1} if map[y - 1][x] == '.' || map[y - 1][x] == 'E' + when '<' + where = {x: x, y: y + 1} if map[y + 1][x] == '.' || map[y + 1][x] == 'E' + when '^' + where = {x: x - 1, y: y} if map[y][x - 1] == '.' || map[y][x - 1] == 'E' + when 'v' + where = {x: x + 1, y: y} if map[y][x + 1] == '.' || map[y][x + 1] == 'E' + end + + where = nil if !where.nil? && visited.has_key?(""#{where[:x]},#{where[:y]}"") + + return where +end + +def where_right(x, y, dir, map, visited) + where = nil + case dir + when '>' + where = {x: x, y: y + 1} if map[y + 1][x] == '.' || map[y + 1][x] == 'E' + when '<' + where = {x: x, y: y - 1} if map[y - 1][x] == '.' || map[y - 1][x] == 'E' + when '^' + where = {x: x + 1, y: y} if map[y][x + 1] == '.' || map[y][x + 1] == 'E' + when 'v' + where = {x: x - 1, y: y} if map[y][x - 1] == '.' || map[y][x - 1] == 'E' + end + + where = nil if !where.nil? && visited.has_key?(""#{where[:x]},#{where[:y]}"") + + return where +end + +def new_dir(dir, turn) + case dir + when '>' + return turn == 'L' ? '^' : 'v' + when '<' + return turn == 'L' ? 'v' : '^' + when '^' + return turn == 'L' ? '<' : '>' + when 'v' + return turn == 'L' ? '>' : '<' + end +end + + +map = File.read(file_path).split(""\n"").map { |line| line.chars } + +start = {x: 0, y: 0} +goal = {x: 0, y: 0} + +map.each_with_index do |row, y| + row.each_with_index do |cell, x| + if cell == 'S' + start = {x: x, y: y, dir: '>', score: 0, visited: {""#{x},#{y}"": true}} + elsif cell == 'E' + goal = {x: x, y: y} + end + end +end + +moves_left = true +paths = {} +paths[""#{start[:x]},#{start[:y]},#{start[:dir]}""] = start +visited_with_score = {} +visited_with_score = {""#{start[:x]},#{start[:y]},#{start[:dir]}"": 0} + + +while moves_left + moves_left = false + + new_paths = {} + paths_before = paths.clone + paths.each do |key, path| + x, y, dir, score, visited = path[:x], path[:y], path[:dir], path[:score], path[:visited] + + if x == goal[:x] && y == goal[:y] + if (visited_with_score[key].nil? || visited_with_score[key] >= score) && (!new_paths.has_key?(key) || new_paths[key][:score] >= score) + new_paths[key] = path + visited_with_score[key] = score + next + end + end + + straight_visited = visited.clone + where = where_straight(x, y, dir, map, visited) + if !where.nil? + if (!new_paths.has_key?(""#{where[:x]},#{where[:y]},#{dir}"") || new_paths[""#{where[:x]},#{where[:y]},#{dir}""][:score] >= score + 1) && (visited_with_score[""#{where[:x]},#{where[:y]},#{dir}""].nil? || visited_with_score[""#{where[:x]},#{where[:y]},#{dir}""] >= score) + straight_visited[""#{where[:x]},#{where[:y]}""] = true + new_paths[""#{where[:x]},#{where[:y]},#{dir}""] = {x: where[:x], y: where[:y], dir: dir, score: score + 1, visited: straight_visited} + visited_with_score[""#{where[:x]},#{where[:y]},#{dir}""] = score + 1 + moves_left = true + end + end + + left_visited = visited.clone + where = where_left(x, y, dir, map, visited) + if !where.nil? + if (!new_paths.has_key?(""#{where[:x]},#{where[:y]},#{new_dir(dir, 'L')}"") || new_paths[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'L')}""][:score] >= score + 1001) && (visited_with_score[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'L')}""].nil? || visited_with_score[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'L')}""] >= score + 1001) + left_visited[""#{where[:x]},#{where[:y]}""] = true + new_paths[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'L')}""] = {x: where[:x], y: where[:y], dir: new_dir(dir, 'L'), score: score + 1001, visited: left_visited} + visited_with_score[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'L')}""] = score + 1001 + moves_left = true + end + end + + right_visited = visited.clone + where = where_right(x, y, dir, map, visited) + if !where.nil? + if (!new_paths.has_key?(""#{where[:x]},#{where[:y]},#{new_dir(dir, 'R')}"") || new_paths[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'R')}""][:score] >= score + 1001) && (visited_with_score[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'R')}""].nil? || visited_with_score[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'R')}""] >= score + 1001) + right_visited[""#{where[:x]},#{where[:y]}""] = true + new_paths[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'R')}""] = {x: where[:x], y: where[:y], dir: new_dir(dir, 'R'), score: score + 1001, visited: right_visited} + visited_with_score[""#{where[:x]},#{where[:y]},#{new_dir(dir, 'R')}""] = score + 1001 + moves_left = true + end + end + end + paths = new_paths +end + +puts visited_with_score.keys.select { |key| key.to_s.split(',')[0].to_i == goal[:x] && key.to_s.split(',')[1].to_i == goal[:y] }.map { |key| visited_with_score[key] }.min",ruby +644,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,"require 'set' + +# MinHeap implementation for Ruby +class MinHeap + def initialize + @heap = [] + end + + def push(item) + @heap.push(item) + sift_up(@heap.length - 1) + end + + def pop + return nil if @heap.empty? + + top = @heap[0] + last = @heap.pop + if @heap.any? + @heap[0] = last + sift_down(0) + end + top + end + + def empty? + @heap.empty? + end + + private + + def sift_up(index) + while index > 0 + parent = (index - 1) / 2 + break if @heap[parent][0] <= @heap[index][0] + @heap[parent], @heap[index] = @heap[index], @heap[parent] + index = parent + end + end + + def sift_down(index) + size = @heap.length + while true + left = 2 * index + 1 + right = 2 * index + 2 + smallest = index + + if left < size && @heap[left][0] < @heap[smallest][0] + smallest = left + end + + if right < size && @heap[right][0] < @heap[smallest][0] + smallest = right + end + + break if smallest == index + @heap[index], @heap[smallest] = @heap[smallest], @heap[index] + index = smallest + end + end +end + +def get_lowest_score(maze) + m = maze.length + n = maze[0].length + start = [-1, -1] + finish = [-1, -1] + + m.times do |i| + n.times do |j| + if maze[i][j] == 'S' + start = [i, j] + elsif maze[i][j] == 'E' + finish = [i, j] + end + end + end + + maze[finish[0]][finish[1]] = '.' + dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]] + visited = Set.new + heap = MinHeap.new + heap.push([0, 0, *start]) + + while !heap.empty? + score, dI, i, j = heap.pop + + if [i, j] == finish + return score + end + + next if visited.include?([dI, i, j]) + + visited.add([dI, i, j]) + + x, y = i + dirs[dI][0], j + dirs[dI][1] + + if maze[x][y] == '.' && !visited.include?([dI, x, y]) + heap.push([score + 1, dI, x, y]) + end + + left = (dI - 1) % 4 + if !visited.include?([left, i, j]) + heap.push([score + 1000, left, i, j]) + end + + right = (dI + 1) % 4 + if !visited.include?([right, i, j]) + heap.push([score + 1000, right, i, j]) + end + end + + nil +end + +if __FILE__ == $0 + maze = [] + File.readlines('day16-1.txt').each do |line| + maze << line.strip.chars + end + + puts ""Lowest Score: #{get_lowest_score(maze)}"" +end",ruby +645,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,"class MinHeap + def initialize + @heap = [] + end + + def push(item) + @heap.push(item) + sift_up(@heap.length - 1) + end + + def pop + return nil if @heap.empty? + + top = @heap[0] + last = @heap.pop + if @heap.any? + @heap[0] = last + sift_down(0) + end + top + end + + def empty? + @heap.empty? + end + + private + + def sift_up(index) + while index > 0 + parent = (index - 1) / 2 + break if @heap[parent][0] <= @heap[index][0] + @heap[parent], @heap[index] = @heap[index], @heap[parent] + index = parent + end + end + + def sift_down(index) + size = @heap.length + while true + left = 2 * index + 1 + right = 2 * index + 2 + smallest = index + + if left < size && @heap[left][0] < @heap[smallest][0] + smallest = left + end + + if right < size && @heap[right][0] < @heap[smallest][0] + smallest = right + end + + break if smallest == index + @heap[index], @heap[smallest] = @heap[smallest], @heap[index] + index = smallest + end + end +end + +def part2(puzzle_input) + grid = puzzle_input.split(""\n"") + m, n = grid.length, grid[0].length + start = nil + end_pos = nil + + # Find start and end positions + grid.each_with_index do |row, i| + row.each_char.with_index do |char, j| + if char == 'S' + start = [i, j] + elsif char == 'E' + end_pos = [i, j] + end + end + end + + grid[end_pos[0]] = grid[end_pos[0]].sub('E', '.') + + # Initialize variables + visited = {} + directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] + heap = MinHeap.new + heap.push([0, 0, *start, Set.new([start])]) # start with (score, direction, i, j, path) + lowest_score = nil + winning_paths = Set.new + + # Function to check if we can visit a position + def can_visit(visited, d, i, j, score) + prev_score = visited[[d, i, j]] + return false if prev_score && prev_score < score + visited[[d, i, j]] = score + true + end + + # Dijkstra-like algorithm + while !heap.empty? + score, d, i, j, path = heap.pop + + if lowest_score && lowest_score < score + break + end + + if [i, j] == end_pos + lowest_score = score + winning_paths.merge(path) + next + end + + if !can_visit(visited, d, i, j, score) + next + end + + # Move in the current direction + x, y = i + directions[d][0], j + directions[d][1] + if grid[x][y] == '.' && can_visit(visited, d, x, y, score + 1) + heap.push([score + 1, d, x, y, path + [[x, y]]]) + end + + # Turn left + left = (d - 1) % 4 + if can_visit(visited, left, i, j, score + 1000) + heap.push([score + 1000, left, i, j, path]) + end + + # Turn right + right = (d + 1) % 4 + if can_visit(visited, right, i, j, score + 1000) + heap.push([score + 1000, right, i, j, path]) + end + end + + winning_paths.length +end + +# Read input file and execute the function +input_text = File.read('input.txt') +res = part2(input_text) +puts res",ruby +646,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,"require 'set' + +DIRECTIONS = [ + { ""x"" => 1, ""y"" => 0 }, + { ""x"" => 0, ""y"" => 1 }, + { ""x"" => -1, ""y"" => 0 }, + { ""x"" => 0, ""y"" => -1 } +] + +class MinHeap + def initialize + @heap = [] + end + + def insert(element) + @heap.push(element) + bubble_up(@heap.size - 1) + end + + def extract_min + return nil if @heap.empty? + swap(0, @heap.size - 1) + min = @heap.pop + bubble_down(0) + min + end + + def size + @heap.size + end + + private + + def bubble_up(index) + while index > 0 && @heap[parent(index)].first > @heap[index].first + swap(index, parent(index)) + index = parent(index) + end + end + + def bubble_down(index) + left = left_child(index) + right = right_child(index) + smallest = index + + if left < @heap.size && @heap[left].first < @heap[smallest].first + smallest = left + end + + if right < @heap.size && @heap[right].first < @heap[smallest].first + smallest = right + end + + if smallest != index + swap(index, smallest) + bubble_down(smallest) + end + end + + def parent(index) + (index - 1) / 2 + end + + def left_child(index) + 2 * index + 1 + end + + def right_child(index) + 2 * index + 2 + end + + def swap(i, j) + @heap[i], @heap[j] = @heap[j], @heap[i] + end +end + +# Dijkstra's Algorithm implementation +def dijkstra(graph, start, directionless) + queue = MinHeap.new + distances = {} + + starting_key = if directionless + ""#{start['x']},#{start['y']}"" + else + ""#{start['x']},#{start['y']},0"" + end + + 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 + next + end + + next unless graph[current_node] + + graph[current_node].each do |next_node, weight| + new_score = current_score + weight + if distances[next_node].nil? || distances[next_node] > new_score + distances[next_node] = new_score + queue.insert([new_score, next_node]) + end + end + end + + distances +end + +# Parsing the grid and building the movement graph +def parse_grid(grid) + width, height = grid[0].length, grid.length + start, finish = { ""x"" => 0, ""y"" => 0 }, { ""x"" => 0, ""y"" => 0 } + forward, reverse = {}, {} + + grid.each_with_index do |row, y| + row.each_char.with_index do |char, x| + if char == ""S"" + start = { ""x"" => x, ""y"" => y } + elsif char == ""E"" + finish = { ""x"" => x, ""y"" => y } + end + + if char != ""#"" + DIRECTIONS.each_with_index do |direction, i| + pos = { ""x"" => x + direction[""x""], ""y"" => y + direction[""y""] } + key = ""#{x},#{y},#{i}"" + move_key = ""#{pos['x']},#{pos['y']},#{i}"" + + if pos['x'].between?(0, width - 1) && pos['y'].between?(0, height - 1) && grid[pos['y']][pos['x']] != ""#"" + forward[key] ||= {} + forward[key][move_key] = 1 + reverse[move_key] ||= {} + reverse[move_key][key] = 1 + end + + [i + 3, i + 1].each do |new_dir| + new_dir %= 4 + forward[key] ||= {} + forward[key][""#{x},#{y},#{new_dir}""] = 1000 + reverse[""#{x},#{y},#{new_dir}""] ||= {} + reverse[""#{x},#{y},#{new_dir}""][""#{x},#{y},#{i}""] = 1000 + end + end + end + end + end + + DIRECTIONS.each_with_index do |_, i| + key = ""#{finish['x']},#{finish['y']}"" + rotate_key = ""#{finish['x']},#{finish['y']},#{i}"" + forward[rotate_key] ||= {} + forward[rotate_key][key] = 0 + reverse[key] ||= {} + reverse[key][rotate_key] = 0 + end + + { ""start"" => start, ""end"" => finish, ""forward"" => forward, ""reverse"" => reverse } +end + +# The main function +def tilesApartFromMaze + file = File.read(""input.txt"") + grid = file.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 = ""#{parsed['end']['x']},#{parsed['end']['y']}"" + target = from_start[end_key] + spaces = Set.new + + from_start.each do |position, _| + # Ensure positions in both forward and reverse directions contribute to the path. + if position != end_key && from_start[position] + (to_end[position] || Float::INFINITY) == target + x, y = position.split(',')[0..1] + spaces.add(""#{x},#{y}"") + end + end + puts ""Number of reachable spaces: #{spaces.length}"" +end + +tilesApartFromMaze",ruby +647,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,"require 'set' + +input = File.read('16.input').split(""\n"").map(&:strip) + +# problem 1 + +walls = Set.new +goal = nil +start = nil + +input.each.with_index do |line, y| + line.chars.each.with_index do |c, x| + if c == '#' + walls.add([x, y]) + next + end + + if c == 'S' + start = [x, y] + next + end + + if c == 'E' + goal = [x, y] + next + end + end +end + +def search(start, goal, walls, known_best_cost) + dir_offsets = { + '^' => [0, -1], + 'v' => [0, 1], + '<' => [-1, 0], + '>' => [1, 0], + } + + rotations = { + '^' => ['<', '>'], + 'v' => ['<', '>'], + '<' => ['^', 'v'], + '>' => ['^', 'v'], + } + + x, y = start + to_search = [[x, y, '>', 0, [start]]] + key = [x, y, '>'].join(',') + visited = {} + visited[key] = 0 + best_cost = known_best_cost + best_seats = Set.new + best_seats.add(start) + best_seats.add(goal) + + while to_search.size > 0 + move = to_search.pop + + x, y, dir, cost, path = move + next if !best_cost.nil? && cost >= best_cost + next if !known_best_cost.nil? && cost >= known_best_cost + + offset_x, offset_y = dir_offsets[dir] + new_x = x + offset_x + new_y = y + offset_y + + if !walls.include?([new_x, new_y]) + if goal[0] == new_x && goal[1] == new_y + if best_cost.nil? || best_cost > cost + 1 + best_cost = cost + 1 + end + + if !known_best_cost.nil? && known_best_cost == cost + 1 + path.each do |pos| + best_seats.add(pos) + end + end + end + + key = [new_x, new_y, dir].join(',') + + past_cost = visited[key] + if past_cost.nil? || past_cost >= cost + 1 + visited[key] = cost + 1 + to_search.unshift([new_x, new_y, dir, cost + 1, path + [[new_x, new_y]]]) + end + end + + rotations[dir].each do |other_dir| + key = [x, y, other_dir].join(',') + + past_cost = visited[key] + if past_cost.nil? || past_cost >= cost + 1000 + visited[key] = cost + 1000 + to_search.push([x, y, other_dir, cost + 1000, path]) + end + end + end + + [best_cost, best_seats] +end + +best_cost, = search(start, goal, walls, nil) + +puts best_cost + +# problem 2 + +_, best_seats = search(start, goal, walls, best_cost) + +puts best_seats.size",ruby +648,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,"# Strategy for part 2: Instead of instantly returning when I find the end point, continue +# searching until the next score would be greater than the end point score. This should +# populate ALL map positions that are part of a best path. +# Then, starting from the end point, walk the map BACKWARDS from the end point back to the start, +# taking a step only if the target position's score is one step worth than the current score, and +# recording each stepped-on tile as I go. Then, just count the flagged tiles. + +require 'set' + +class Point + attr_accessor :y, :x + + def initialize(y, x) + @y = y + @x = x + end + + def eql?(other) + other.is_a?(Point) && @y == other.y && @x == other.x + end + + def hash + @y.hash ^ @x.hash + end +end + +class Position + attr_accessor :point, :direction + + def initialize(point, direction) + @point = point + @direction = direction + end + + def ==(other) + eql?(other) + end + + def eql?(other) + other.is_a?(Position) && @point.eql?(other.point) && @direction == other.direction + end + + def hash + @point.hash ^ @direction.hash + end +end + +DIRECTIONS = [0, 90, 180, 270].freeze + +def ahead(position) + point_ahead = case position.direction + when 0 + Point.new(position.point.y - 1, position.point.x) + when 90 + Point.new(position.point.y, position.point.x + 1) + when 180 + Point.new(position.point.y + 1, position.point.x) + else # 270 + Point.new(position.point.y, position.point.x - 1) + end + Position.new(point_ahead, position.direction) +end + +def left(position) + Position.new(position.point, (position.direction - 90) % 360) +end + +def right(position) + Position.new(position.point, (position.direction + 90) % 360) +end + +def next_positions(position) + [ahead(position), left(position), right(position)] +end + +# Breadth-first search. +def find_best_paths(map, start_position, end_point) + queue = [start_position] + best_path_score = nil + while queue.size > 0 + position = queue.shift + + # Stop exploring after we've found ALL of the best paths. + return if !best_path_score.nil? && map[position] > best_path_score + + best_path_score = map[position] if position.point.eql?(end_point) + + next_positions(position).each do |next_position| + next unless map.key?(next_position) + + next_position_score_delta = next_position.point.eql?(position.point) ? 1000 : 1 + next if map[next_position] <= map[position] + next_position_score_delta + + # Don't turn towards a wall + next if next_position.point.eql?(position.point) && !map.key?(ahead(next_position)) + + map[next_position] = map[position] + next_position_score_delta + + queue << (next_position) + end + + # Sort the queue by the lowest score, such that as soon as we reach the end point, + # we're guaranteed that the score is the lowest possible to reach it (because no + # subsequent moves could possibly have a lower score). + queue.sort_by! { |position| map[position] } + end + + nil +end + +def backward(position) + point_ahead = case position.direction + when 0 + Point.new(position.point.y + 1, position.point.x) + when 90 + Point.new(position.point.y, position.point.x - 1) + when 180 + Point.new(position.point.y - 1, position.point.x) + else # 270 + Point.new(position.point.y, position.point.x + 1) + end + Position.new(point_ahead, position.direction) +end + +def backwards_next_positions(position) + [backward(position), left(position), right(position)] +end + +def positions_on_best_paths(map, end_point) + best_path_points = Set[end_point] + + queue = [] + DIRECTIONS.each do |direction| + queue << Position.new(end_point, direction) + end + + while queue.size > 0 + position = queue.shift + + backwards_next_positions(position).each do |next_position| + next unless map.key?(next_position) + next if map[next_position] == Float::INFINITY + + next unless map[next_position] == map[position] - 1 || map[next_position] == map[position] - 1000 + + best_path_points.add(next_position.point) + queue << next_position + end + end + + best_path_points.count +end + +# Hash map of positions to lowest score to reach that position +map = {} + +start_position = nil +end_point = nil +File.readlines('day-16/input.txt').map(&:chomp).each_with_index do |line, y| + line.each_char.with_index do |char, x| + next if char == '#' + + point = Point.new(y, x) + DIRECTIONS.each do |direction| + position = Position.new(point, direction) + if char == 'S' && direction == 90 + start_position = position + map[position] = 0 + else + map[position] = Float::INFINITY + end + end + if char == 'E' + end_point = point + end + end +end + +find_best_paths(map, start_position, end_point) + +p positions_on_best_paths(map, end_point)",ruby +649,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,"require 'set' + +day = ""16"" +file_name = ""12-#{day}-24/sampleIn.txt"" +file_name = ""12-#{day}-24/input.txt"" + +data = File.read(file_name).split(""\n"").map { |i| i.strip } + +def getManDist(start, goal) + return (start[0] - goal[0]).abs + (start[1] - goal[1]).abs +end + +def part1(input) + grid = input.map { |i| i.split("""") } + start = nil + goal = nil + for i in 0...grid.length + for j in 0...grid[i].length + if grid[i][j] == ""S"" + start = [i, j] + grid[i][j] = ""."" + end + if grid[i][j] == ""E"" + goal = [i, j] + grid[i][j] = ""."" + end + end + end + + visited = Set[] + + dirs = { + ""E"" => [0, 1], + ""N"" => [-1, 0], + ""S"" => [1, 0], + ""W"" => [0, -1] + } + + queue = { + getManDist(start, goal) => [[start, ""E"", 0]] + } + + while true + shortest = queue.keys.min + cur = queue[shortest].shift + if queue[shortest].length == 0 + queue.delete(shortest) + end + loc = cur[0] + visited.add(loc) + dir = cur[1] + score = cur[2] + if loc == goal + return score + end + + for d in [""E"", ""S"", ""N"", ""W""] + nextLoc = [loc[0] + dirs[d][0], loc[1] + dirs[d][1]] + next if grid[nextLoc[0]][nextLoc[1]] == ""#"" + next if visited.include? nextLoc + + nextScore = score + 1 + if d != dir + nextScore += 1000 + end + + heuristic = nextScore + getManDist(nextLoc, goal) + + if not queue[heuristic] + queue[heuristic] = [] + end + queue[heuristic].append([nextLoc, d, nextScore]) + end + end + +end + + +# returns a list of +# [ list of sets of best paths starting at start and ending at goal, +# the score of that path] +def getBestPaths(grid, start, dir, goal, bestScore, curScore, path, dirs, memo) +# if curScore > bestScore +# return [[], false] +# end + if start == goal + return [[Set[goal]], 0] + end + if memo[[start, dir]] + # remScore = memo[[start, dir]][1] + # if curScore + remScore > bestScore + # return [[], 0] + # end + return memo[[start, dir]] + end + + bestPaths = [] + + for d in [""E"", ""S"", ""N"", ""W""] + nextLoc = [start[0] + dirs[d][0], start[1] + dirs[d][1]] + + next if grid[nextLoc[0]][nextLoc[1]] == ""#"" + + next if path.include? nextLoc + + score = 1 + if d != dir + score += 1000 + end + + newPath = path + Set[nextLoc] + + gbp = getBestPaths(grid, nextLoc, d, goal, bestScore, score, newPath, dirs, memo) + + # print nextLoc + # puts + # puts d + # puts score + + # print gbp + # puts + + for p in gbp[0] + pNew = p + Set[start] + bestPaths.append([pNew, gbp[1] + score]) + end + + end + + if bestPaths == [] + # puts ""weird"" + memo[[start, dir]] = [[], Float::INFINITY] + return [[], Float::INFINITY] + end + + fastest = bestPaths.min { |i, j| i[1] <=> j[1] } + fastest = fastest[1] + + bestPaths = bestPaths.filter { |i| i[1] == fastest }.map { |i| i[0] } + + +# if bestPaths.length > 0 + memo[[start, dir]] = [bestPaths, fastest] + return [bestPaths, fastest] +# else +# return [bestPaths, false] +# end + +end + +# what if we: +# look at every combination of square and direction, sorted by reverse manhattan distance from goal +# then, calculate the shortest path from start to goal and its score +# remember that score +# move out by MD 1, do the same + +def part2(input) + grid = input.map { |i| i.split("""") } + start = nil + goal = nil + for i in 0...grid.length + for j in 0...grid[i].length + if grid[i][j] == ""S"" + start = [i, j] + grid[i][j] = ""."" + end + if grid[i][j] == ""E"" + goal = [i, j] + grid[i][j] = ""."" + end + end + end + + bestScore = part1(input) + bestMoves = bestScore % 1000 + + # puts bestMoves + + visited = {} + + dirs = { + ""E"" => [0, 1], + ""N"" => [-1, 0], + ""S"" => [1, 0], + ""W"" => [0, -1] + } + + bestPaths = [] + queue = { + getManDist(start, goal) => [[Set[start], ""E"", 0, start, false]] + } + + while queue.keys.length > 0 + shortest = queue.keys.min + cur = queue[shortest].shift + if queue[shortest].length == 0 + queue.delete(shortest) + end + curPath = cur[0] + loc = cur[3] + dir = cur[1] + score = cur[2] + onTurn = cur[4] + visited[loc] = score + if not onTurn + visited[loc] += 1000 + end + if loc == goal + bestPaths.append(curPath) + end + + for d in [""E"", ""S"", ""N"", ""W""] + nextLoc = [loc[0] + dirs[d][0], loc[1] + dirs[d][1]] + next if grid[nextLoc[0]][nextLoc[1]] == ""#"" + next if curPath.include? nextLoc + + nextScore = score + 1 + if d != dir + nextScore += 1000 + end + + next if visited[nextLoc] and visited[nextLoc] < nextScore + + heuristic = nextScore + getManDist(nextLoc, goal) + + next if heuristic > bestScore + + nextPath = curPath + Set[nextLoc] + + next if nextPath.size > bestMoves + 1 + + if not queue[heuristic] + queue[heuristic] = [] + end + queue[heuristic].append([nextPath, d, nextScore, nextLoc, (d != dir)]) + end + end + + onPaths = Set[] + for i in 0...bestPaths.length + onPaths += bestPaths[i] + end + + return onPaths.size +end + +puts part1(data) +puts part2(data)",ruby +650,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","############################################################################# +# 1 +############################################################################# + +lines = File.readlines('input17.txt') +@a = lines[0][/\d+/].to_i +@b = lines[1][/\d+/].to_i +@c = lines[2][/\d+/].to_i +program = lines[4].scan(/\d+/).map(&:to_i) +pointer = 0 + +def combo(n) + return @a if n == 4 + return @b if n == 5 + return @c if n == 6 + n +end + +output = [] + +loop do + if program[pointer] == 0 + @a /= 2 ** combo(program[pointer + 1]) + pointer += 2 + elsif program[pointer] == 1 + @b ^= program[pointer + 1] + pointer += 2 + elsif program[pointer] == 2 + @b = combo(program[pointer + 1]) % 8 + pointer += 2 + elsif program[pointer] == 3 + @a == 0 ? pointer += 2 : pointer = program[pointer + 1] + elsif program[pointer] == 4 + @b ^= @c + pointer += 2 + elsif program[pointer] == 5 + output << combo(program[pointer + 1]) % 8 + pointer += 2 + elsif program[pointer] == 6 + @b = @a / 2 ** combo(program[pointer + 1]) + pointer += 2 + elsif program[pointer] == 7 + @c = @a / 2 ** combo(program[pointer + 1]) + pointer += 2 + end + + break if pointer >= program.length +end + +puts output.join(',')",ruby +651,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/env ruby + +class ChronoSpatialComputer + attr_reader :a, :b, :c, :program, :ip, :output + + def initialize(a:, b:, c:, program:) + @a = a.to_i + @b = b.to_i + @c = c.to_i + @program = program.split(',').map(&:to_i) + @ip = 0 + @output = [] + end + + def run! + while ip < program.size do + instruction = program[ip] + operand = program[ip + 1] + + puts ""ip: #{ip}, instruction: #{instruction}, operand: #{operand}"" + execute_instruction(instruction, operand) + puts ""ip: #{ip}, a: #{a}, b: #{b}, c: #{c}, output: #{output.join(',')}"" + end + end + + def execute_instruction(instruction, operand) + case instruction + when 0 then execute_adv(operand) + when 1 then execute_bxl(operand) + when 2 then execute_bst(operand) + when 3 then execute_jnz(operand) + when 4 then execute_bxc(operand) + when 5 then execute_out(operand) + when 6 then execute_bdv(operand) + when 7 then execute_cdv(operand) + else raise ""Unknown instruction #{instruction} with operand #{operand}"" + end + end + + def combo_operand(operand) + case operand + when 0, 1, 2, 3 then operand + when 4 then a + when 5 then b + when 6 then c + when 7 then raise ""Invalid combo operand: #{operand}"" + end + end + + def execute_adv(operand) + numerator = a + denominator = 2**combo_operand(operand) + @a = numerator / denominator # integer division, truncate the remainder + @ip += 2 + end + + def execute_bxl(operand) + @b = b ^ operand # Bitwise xor + @ip += 2 + end + + def execute_bst(operand) + @b = combo_operand(operand) % 8 # Combo operand modulo 8 + @ip += 2 + end + + def execute_jnz(operand) + if a == 0 + @ip += 2 + else + @ip = operand + end + end + + def execute_bxc(_operand) + @b = b ^ c # Bitwise xor + @ip += 2 + end + + def execute_out(operand) + @output << (combo_operand(operand) % 8) # Combo operand modulo 8 + @ip += 2 + end + + def execute_bdv(operand) + numerator = a + denominator = 2**combo_operand(operand) + @b = numerator / denominator # integer division, truncate the remainder + @ip += 2 + end + + def execute_cdv(operand) + numerator = a + denominator = 2**combo_operand(operand) + @c = numerator / denominator # integer division, truncate the remainder + @ip += 2 + end +end + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file) + +a, b, c, program = lines.map(&:strip).reject(&:empty?).map(&:split).map(&:last) + +computer = ChronoSpatialComputer.new(a:, b:, c:, program:) +computer.run! +puts computer.output.join(',') + + +# 7,4,2,0,5,0,5,3,7 - correct",ruby +652,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","def parse_input + a = nil + b = nil + c = nil + program = [] + + File.readlines('inputs/17', chomp: true).each do |line| + case line + when /Register A: (\d+)/ + a = $1.to_i + when /Register B: (\d+)/ + b = $1.to_i + when /Register C: (\d+)/ + c = $1.to_i + when /Program: ([\d,]+)/ + program = $1.split(',').map(&:to_i) + end + end + + [a, b, c, program] +end + +def execute + a, b, c, program = parse_input + pc = 0 + output = [] + + combo = ->(operand) do + case operand + when 0, 1, 2, 3 then operand + when 4 then a + when 5 then b + when 6 then c + else raise 'Invalid combo operand' + end + end + + loop do + break if pc >= program.size + + opcode, operand = program[pc..pc+1] + + case opcode + when 0 # adv + a = (a / (2**combo.call(operand))).to_i + when 1 # bxl + b ^= operand + when 2 # bst + b = combo.call(operand) % 8 + when 3 # jnz + if a != 0 + pc = operand + next + end + when 4 # bxc + b ^= c + when 5 # out + output << (combo.call(operand) % 8) + when 6 # bdv + b = (a / (2**combo.call(operand))).to_i + when 7 # cdv + c = (a / (2**combo.call(operand))).to_i + end + + pc += 2 + end + + puts ""Register A: #{a}"" + puts ""Register B: #{b}"" + puts ""Register C: #{c}"" + puts ""Output: #{output.join(',')}"" +end + +execute",ruby +653,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","class CPU + def initialize(filename) + lines = File.readlines(filename) + @a = lines[0].match(/Register A: (\d+)/)[1].to_i + @b = lines[1].match(/Register B: (\d+)/)[1].to_i + @c = lines[2].match(/Register C: (\d+)/)[1].to_i + @instructions = lines[4].split("" "")[1].delete(""\n"").split("","").map(&:to_i) + @ip = 0 + @output = [] + puts self + end + + def to_s + ""A[#{@a}] B[#{@b}] C[#{@c}] IP[#{@ip}] Instructions#{@instructions.to_s} Output#{@output.to_s}"" + end + + def get_combo_operand_value(operand) + # 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. + case operand + when 0..3 then operand + when 4 then @a + when 5 then @b + when 6 then @c + when 7 then + puts ""Error! Invalid combo operand '7'"" + abort + end + end + + def step + opcode = @instructions[@ip] + operand = @instructions[@ip + 1] + @ip += 2 + + case opcode + # 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. + when 0 + @a = @a / (2**get_combo_operand_value(operand)) + + # 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. + when 1 + @b = @b ^ operand + + # 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. + when 2 + @b = get_combo_operand_value(operand) & 0x7 + + # 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. + when 3 + if @a != 0 + @ip = operand + end + + # 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.) + when 4 + @b = @b ^ @c + + # 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.) + when 5 + @output.append(get_combo_operand_value(operand) & 0x7) + + # 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.) + when 6 + @b = @a / (2**get_combo_operand_value(operand)) + + # 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.) + when 7 + @c = @a / (2**get_combo_operand_value(operand)) + end + end + + def run + while @ip < @instructions.length + step + end + + puts self + end +end + +cpu = CPU.new(""day_17_input.txt"") +cpu.run",ruby +654,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","TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +output = [] + +registers, program = File.read(path).split(""\n\n"") +register_a, register_b, register_c = registers.split(""\n"").map do |line| + line.split(': ').last.to_i +end +code_bytes = program.split(': ').last.split(',').map(&:to_i) + +module OpCode + ADV = 0 + BXL = 1 + BST = 2 + JNZ = 3 + BXC = 4 + OUT= 5 + BDV = 6 + CDV = 7 +end + +instruction_pointer = 0 + +while instruction_pointer + 1 < code_bytes.count + jumped = false + opcode = code_bytes[instruction_pointer] + literal_operand = code_bytes[instruction_pointer + 1] + combo_operand = + case literal_operand + when (0..3) + literal_operand + when 4 + register_a + when 5 + register_b + when 6 + register_c + end + + case opcode + when 0 + register_a = register_a / 2**combo_operand + when 1 + register_b = register_b ^ literal_operand + when 2 + register_b = combo_operand % 8 + when 3 + unless register_a == 0 + instruction_pointer = literal_operand + jumped = true + end + when 4 + register_b = register_b ^ register_c + when 5 + output << (combo_operand % 8).to_s + when 6 + register_b = register_a / 2**combo_operand + when 7 + register_c = register_a / 2**combo_operand + end + instruction_pointer += 2 unless jumped +end + +p ""Output: #{output.join(',')}""",ruby +655,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 parse_input(file_path) + lines = File.readlines(file_path, chomp: true) + registers = lines[0..2].map { |line| line.split("": "")[1].to_i } + program = lines[4].split("": "")[1].split("","").map(&:to_i) + [registers, program] +end + +def run(program, regs) + reg_a, reg_b, reg_c = 4, 5, 6 + ip = 0 + combo = [0, 1, 2, 3, *regs] + + Enumerator.new do |yielder| + while ip < program.length + opcode, operand = program[ip, 2] + + case opcode + when 0 + combo[reg_a] /= 2**combo[operand] + when 1 + combo[reg_b] ^= operand + when 2 + combo[reg_b] = combo[operand] % 8 + when 3 + ip = operand - 2 if combo[reg_a] != 0 + when 4 + combo[reg_b] ^= combo[reg_c] + when 5 + yielder << (combo[operand] % 8) + when 6 + combo[reg_b] = combo[reg_a] / (2**combo[operand]) + when 7 + combo[reg_c] = combo[reg_a] / (2**combo[operand]) + end + + ip += 2 + end + end +end + +def expect(program, target_output, prev_a = 0) + helper = lambda do |program, target_output, prev_a| + return prev_a if target_output.empty? + + (0...(1 << 10)).each do |a| + if (a >> 3) == (prev_a & 127) && run(program, [a, 0, 0]).next == target_output.last + result = helper.call(program, target_output[0...-1], (prev_a << 3) | (a % 8)) + return result unless result.nil? + end + end + nil + end + + helper.call(program, target_output, prev_a) +end + +if __FILE__ == $PROGRAM_NAME + file_path = 'input.txt' + registers, program = parse_input(file_path) + + target_output = program.dup + initial_value = expect(program, target_output) + + if initial_value + puts ""The initial value for register A that produces the target output is: #{initial_value}"" + else + puts ""No initial value found that produces the target output within the given attempts."" + end +end",ruby +656,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n\n"") + +registars = input.first.split(""\n"").map { |line| line.split(' ').last.to_i } +program = input.last.split(' ').last.split(',').map(&:to_i) + +a = registars[0] + + +len = program.size + +found = 22 +result_output = [] +required_output = [3,0] +l = 2 +new_digit = 0 +loop do + + a = found + new_digit + original_a = a + b = registars[1] + c = registars[2] + + bad = false + skip = false + pointer = 0 + output = [] + + while pointer < len-1 + skip = false + + opcode = program[pointer] + operand = program[pointer + 1] + + combo = operand + combo = a if operand == 4 + combo = b if operand == 5 + combo = c if operand == 6 + + case opcode + when 0 + result = a.to_f / 2**combo + a = result.to_i + when 1 + b = b^operand + when 2 + b = combo % 8 + when 3 + if a != 0 + skip = true + pointer = operand + end + when 4 + b = b^c + when 5 + output.push(combo%8) + when 6 + result = a.to_f / 2**combo + b = result.to_i + when 7 + result = a.to_f / 2**combo + c = result.to_i + end + + pointer += 2 unless skip + end + + result_output = output + if output == required_output + break if l == len + found = original_a * 8 + new_digit = 0 + l += 1 + required_output = program.last(l) + else + new_digit += 1 + end +end + +puts found + new_digit",ruby +657,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 = instructions.length + i = 0 + output = [] + + get_combo = lambda do |operand| + case operand + when 0..3 then operand + when 4 then regs['a'] + when 5 then regs['b'] + when 6 then regs['c'] + else 0 + end + end + + while i < n + curr = instructions[i] + operand = instructions[i + 1] + + case curr + when 0 + regs['a'] /= 2**get_combo.call(operand) + when 1 + regs['b'] ^= operand + when 2 + regs['b'] = get_combo.call(operand) % 8 + when 3 + if regs['a'] != 0 + i = operand + next + end + when 4 + regs['b'] ^= regs['c'] + when 5 + output << get_combo.call(operand) % 8 + when 6 + regs['b'] = regs['a'] / 2**get_combo.call(operand) + when 7 + regs['c'] = regs['a'] / 2**get_combo.call(operand) + end + + i += 2 + end + + output +end + +def get_lowest_a(regs, instructions) + regs['a'] = 0 + j = 1 + i_floor = 0 + + while j <= instructions.length && j >= 0 + regs['a'] <<= 3 + + found = false + (i_floor...8).each do |i| + regs_copy = regs.clone + regs_copy['a'] += i + + if instructions[-j..] == run(regs_copy, instructions) + regs['a'] += i + found = true + break + end + end + + unless found + j -= 1 + regs['a'] >>= 3 + i_floor = regs['a'] % 8 + 1 + regs['a'] >>= 3 + next + end + + j += 1 + i_floor = 0 + end + + regs['a'] +end + +if __FILE__ == $0 + regs = {} + instructions = [] + + File.open('day17-2.txt', 'r') do |file| + file.each_line do |line| + line.strip! + next if line.empty? || !line.include?(': ') + + key, value = line.split(': ', 2) + + case key + when 'a' then regs['a'] = 0 + when 'b' then regs['b'] = value.to_i + when 'c' then regs['c'] = value.to_i + else + instructions = value.split(',').map(&:to_i).select { |val| val.to_s.length == 1 } + end + end + end + + puts ""Lowest value of Register A: #{get_lowest_a(regs, instructions)}"" +end",ruby +658,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,"# frozen_string_literal: true + +INPUT_PATH = 'input.txt' + +def parse + lines = File.readlines(INPUT_PATH) + + register_a = lines[0].split(': ')[1].to_i + register_b = lines[1].split(': ')[1].to_i + register_c = lines[2].split(': ')[1].to_i + + program = lines[4].split(': ')[1].split(',').map(&:to_i) + + [register_a, register_b, register_c, program] +end + +def run_program(initial_a, initial_b, initial_c, program) + pointer = 0 + + register_a = initial_a + register_b = initial_b + register_c = initial_c + + output = [] + + until pointer.negative? || pointer >= program.length + case program[pointer] + when 0 + combo_operand = case program[pointer + 1] + when 0 + 0 + when 1 + 1 + when 2 + 2 + when 3 + 3 + when 4 + register_a + when 5 + register_b + when 6 + register_c + end + denominator = 2**combo_operand + register_a = register_a.div(denominator) # integer division + pointer += 2 + when 1 + register_b ^= program[pointer + 1] + pointer += 2 + when 2 + combo_operand = case program[pointer + 1] + when 0 + 0 + when 1 + 1 + when 2 + 2 + when 3 + 3 + when 4 + register_a + when 5 + register_b + when 6 + register_c + end + register_b = combo_operand % 8 + pointer += 2 + when 3 + if register_a.zero? + pointer += 2 + else + pointer = program[pointer + 1] + end + when 4 + register_b ^= register_c + pointer += 2 + when 5 + combo_operand = case program[pointer + 1] + when 0 + 0 + when 1 + 1 + when 2 + 2 + when 3 + 3 + when 4 + register_a + when 5 + register_b + when 6 + register_c + end + output.push(combo_operand % 8) + pointer += 2 + when 6 + combo_operand = case program[pointer + 1] + when 0 + 0 + when 1 + 1 + when 2 + 2 + when 3 + 3 + when 4 + register_a + when 5 + register_b + when 6 + register_c + end + denominator = 2**combo_operand + register_b = register_a.div(denominator) # integer division + pointer += 2 + when 7 + combo_operand = case program[pointer + 1] + when 0 + 0 + when 1 + 1 + when 2 + 2 + when 3 + 3 + when 4 + register_a + when 5 + register_b + when 6 + register_c + end + denominator = 2**combo_operand + register_c = register_a.div(denominator) # integer division + pointer += 2 + end + end + + output +end + +def part1 + register_a, register_b, register_c, program = parse + output = run_program(register_a, register_b, register_c, program) + output.join(',') +end + +def part2 + _register_a, register_b, register_c, program = parse + # Notes + # Halts once floor(A/8) = 0, so have range of things to check given length + # B and C get reset each time - Can work backwards to narrow down! + + length_to_check = 1 + options = Set[0] + while length_to_check <= program.length + desired_output = program.slice(-length_to_check, length_to_check) + next_options = Set.new + options.each do |option| + a = option * 8 + while a < (option + 1) * 8 + next_options.add(a) if run_program(a, register_b, register_c, program) == desired_output + a += 1 + end + end + options = next_options + length_to_check += 1 + end + + options.min +end + +puts 'Part 1' +puts part1 +puts '---' +puts 'Part 2' +puts part2",ruby +659,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 reader + File.readlines(""17.txt"", chomp: true) +end + +def simulate(program, a) + l = [0, 1, 2, 3, a, 0, 0, -1] + out = [] + i = 0 + + while i < program.length + op = program[i] + operand = program[i + 1] + + case op + when 0 + l[4] /= 2**l[operand] + when 1 + l[5] ^= operand + when 2 + l[5] = l[operand] % 8 + when 3 + if l[4] != 0 + i = operand + next + end + when 4 + l[5] ^= l[6] + when 5 + out << l[operand] % 8 + when 6 + l[5] = l[4] / (2**l[operand]) + when 7 + l[6] = l[4] / (2**l[operand]) + end + + i += 2 + end + + out +end + +def part2 + f = reader + program = f[4].split("": "")[1].split("","").map(&:to_i) + + backtrack = lambda do |a = 0, j = -1| + return a if -j > program.length + + m = Float::INFINITY + (0...8).each do |i| + t = (a << 3) | i + if simulate(program, t)[j..] == program[j..] + m = [m, backtrack.call(t, j - 1)].min + end + end + + m + end + + puts backtrack.call +end + +part2",ruby +660,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,"require 'set' + +def solve(bytes, cols, rows) + corrupt_bytes = File + .readlines('inputs/18', chomp: true) + .map { |line| line.split(',').map(&:to_i) } + .take(bytes) + + start = [0, 0] + target = [cols - 1, rows - 1] + queue = [[start, 0]] # [[position, steps]] + visited = Set.new([start]) + + directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] + until queue.empty? + (current, steps) = queue.shift + x, y = current + + return steps if [x, y] == target + + directions.each do |dx, dy| + nx, ny = x + dx, y + dy + + next if nx < 0 || nx >= cols || ny < 0 || ny >= rows + next if visited.include?([nx, ny]) + next if corrupt_bytes.include?([ny, nx]) + + visited.add([nx, ny]) + queue << [[nx, ny], steps + 1] + end + end + + nil +end + +puts solve(1024, 71, 71)",ruby +661,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_pos = [x_len - 1, y_len - 1] + visited = Set.new + frontier = [[start]] + + until frontier.empty? + path = frontier.shift + cur = path.last + + return path if cur == end_pos + + visited.add(cur) + + neighbors = [[1, 0], [-1, 0], [0, 1], [0, -1]].map { |dx, dy| [cur[0] + dx, cur[1] + dy] } + neighbors.select! { |x, y| (0...x_len).cover?(x) && (0...y_len).cover?(y) && !byte_locs.include?([x, y]) } + + neighbors.each do |neighbor| + unless visited.include?(neighbor) + frontier << (path + [neighbor]) + visited.add(neighbor) + end + end + end + + puts ""no path found"" + nil +end + +byte_locs = File.readlines('input.txt', chomp: true).map { |line| line.split(',').map(&:to_i) } +x_len = 71 +y_len = 71 + +puts bfs(byte_locs[0, 1024].to_set, x_len, y_len)&.length.to_i - 1",ruby +662,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +SIZE = TEST ? 7 : 71 +BYTES_TO_FALL = TEST ? 12 : 1024 +MOVES = [[0, 1], [1, 0], [0, -1], [-1, 0]] + +falling_bytes = File.read(path).split(""\n"").map { _1.split(',').map(&:to_i) } +map = Array.new(SIZE) { Array.new(SIZE) { Array.new(2) { |i| i.zero? ? nil : true } } } + +def print_map(map) + puts 'map' + map.each { |line| puts line.map { |(score, pass)| pass ? '.' : '#' }.join } + puts '' +end + +BYTES_TO_FALL.times do |byte_index| + byte = falling_bytes[byte_index] + map[byte[1]][byte[0]][1] = false +end + +print_map(map) + +start = [0, 0] +map[0][0][0] = 0 +finish = [SIZE - 1, SIZE - 1] + +to_do = [start] + +current = nil +loop do + from = to_do.shift + current = map[from[0]][from[1]][0] + break if from == finish + MOVES.each do |(yOffset, xOffset)| + y = from[0] + yOffset + x = from[1] + xOffset + next unless (0...SIZE).include?(x) && (0...SIZE).include?(y) + next unless map[y][x][1] + next unless map[y][x][0].nil? + map[y][x][0] = current + 1 + to_do << [y, x] + end +end + +print_map(map) + +puts ""Number of steps needed: #{current}""",ruby +663,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,"############################################################################# +# 1 +############################################################################# + +lines = File.readlines('input.txt') + +map = [] +71.times do + map << [0] * 71 +end + +lines[0..1023].each do |line| + x, y = line.scan(/\d+/).map(&:to_i) + map[y][x] = -1 +end + +paths = [[0, 0]] +cur_value = 1 +map[0][0] = 1 + +loop do + new_paths = [] + paths.each do |y, x| + if x < 70 && map[y][x + 1] == 0 + map[y][x + 1] = cur_value + 1 + new_paths << [y, x + 1] + end + if x > 0 && map[y][x - 1] == 0 + map[y][x - 1] = cur_value + 1 + new_paths << [y, x - 1] + end + if y < 70 && map[y + 1][x] == 0 + map[y + 1][x] = cur_value + 1 + new_paths << [y + 1, x] + end + if y > 0 && map[y - 1][x] == 0 + map[y - 1][x] = cur_value + 1 + new_paths << [y - 1, x] + end + end + + break if new_paths.include?([70, 70]) + paths = new_paths + cur_value += 1 +end + +puts cur_value",ruby +664,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +def move_up(x, y, corrupted, visited, len) + return nil if y == 0 || corrupted[y - 1][x] == '#' || visited.has_key?(""#{x},#{y - 1}"") + return { x: x, y: y - 1 } +end + +def move_down(x, y, corrupted, visited, len) + return nil if y == len - 1 || corrupted[y + 1][x] == '#' || visited.has_key?(""#{x},#{y + 1}"") + return { x: x, y: y + 1 } +end + +def move_left(x, y, corrupted, visited, len) + return nil if x == 0 || corrupted[y][x - 1] == '#' || visited.has_key?(""#{x - 1},#{y}"") + return { x: x - 1, y: y } +end + +def move_right(x, y, corrupted, visited, len) + return nil if x == len - 1 || corrupted[y][x + 1] == '#' || visited.has_key?(""#{x + 1},#{y}"") + return { x: x + 1, y: y } +end + +input = File.read(file_path).split(""\n"").map{ |line| {x: line.split(',')[0], y: line.split(',')[1] } }.take(1024) + + +len = 71 +#len = 7 + +corrupted = Array.new(len) { Array.new(len, '.') } +input.each do |point| + corrupted[point[:x].to_i][point[:y].to_i] = '#' +end + + +start = { x: 0, y: 0 } +finish = { x: len-1, y: len-1 } +candidates = [{last: start, score: 1, visited: { ""0,0"" => 1 }}] +all_visited = { ""0,0"" => 1 } +moves_left = true + +while moves_left + moves_left = false + + new_candidates = [] + candidates.each do |candidate| + x = candidate[:last][:x] + y = candidate[:last][:y] + visited = candidate[:visited] + score = candidate[:score] + + if x == finish[:x] && y == finish[:y] + puts score-1 + exit + end + + up = move_up(x, y, corrupted, visited, len) + down = move_down(x, y, corrupted, visited, len) + left = move_left(x, y, corrupted, visited, len) + right = move_right(x, y, corrupted, visited, len) + + if !up.nil? && (!all_visited.has_key?(""#{up[:x]},#{up[:y]}"") || all_visited[""#{up[:x]},#{up[:y]}""] > score + 1) + new_visited = visited.dup + new_visited[""#{up[:x]},#{up[:y]}""] = 1 + candidates.push({ last: up, score: score + 1, visited: new_visited }) + all_visited[""#{up[:x]},#{up[:y]}""] = score + 1 + moves_left = true + end + + if !down.nil? && (!all_visited.has_key?(""#{down[:x]},#{down[:y]}"") || all_visited[""#{down[:x]},#{down[:y]}""] > score + 1) + new_visited = visited.dup + new_visited[""#{down[:x]},#{down[:y]}""] = 1 + candidates.push({ last: down, score: score + 1, visited: new_visited }) + all_visited[""#{down[:x]},#{down[:y]}""] = score + 1 + moves_left = true + end + + if !left.nil? && (!all_visited.has_key?(""#{left[:x]},#{left[:y]}"") || all_visited[""#{left[:x]},#{left[:y]}""] > score + 1) + new_visited = visited.dup + new_visited[""#{left[:x]},#{left[:y]}""] = 1 + candidates.push({ last: left, score: score + 1, visited: new_visited }) + all_visited[""#{left[:x]},#{left[:y]}""] = score + 1 + moves_left = true + end + + if !right.nil? && (!all_visited.has_key?(""#{right[:x]},#{right[:y]}"") || all_visited[""#{right[:x]},#{right[:y]}""] > score + 1) + new_visited = visited.dup + new_visited[""#{right[:x]},#{right[:y]}""] = 1 + candidates.push({ last: right, score: score + 1, visited: new_visited }) + all_visited[""#{right[:x]},#{right[:y]}""] = score + 1 + moves_left = true + end + + end + + candidates = new_candidates +end",ruby +665,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","# frozen_string_literal: true + +INPUT_PATH = 'input.txt' + +Coordinate = Data.define(:x, :y) do + def +(other) + return unless other.is_a?(self.class) + + Coordinate.new(x + other.x, y + other.y) + end + + def -(other) + return unless other.is_a?(self.class) + + Coordinate.new(x - other.x, y - other.y) + end +end + +def parse + lines = File.readlines(INPUT_PATH) + + lines.map do |line| + position = line.split(',').map(&:to_i) + Coordinate.new(position[0], position[1]) + end +end + +SPACE_MAX_COORDINATE = 70 + +def neighbours(location) + [ + (location + Coordinate.new(1, 0) if location.x < SPACE_MAX_COORDINATE), + (location - Coordinate.new(1, 0) if location.x.positive?), + (location + Coordinate.new(0, 1) if location.y < SPACE_MAX_COORDINATE), + (location - Coordinate.new(0, 1) if location.y.positive?) + ].compact +end + +def find_shortest_path_length(corrupted_memory) + initial_location = Coordinate.new(0, 0) + target_location = Coordinate.new(SPACE_MAX_COORDINATE, SPACE_MAX_COORDINATE) + + seen = Set[initial_location] + + current = Set[initial_location] + steps = 0 + until current.empty? + steps += 1 + next_locations = Set.new + current.each do |location| + neighbours(location).each do |neighbour| + next if corrupted_memory.include?(neighbour) + next if seen.include?(neighbour) + + return steps if neighbour == target_location + + next_locations.add(neighbour) + seen.add(neighbour) + end + end + current = next_locations + end + + -1 +end + +def part1 + falling_bytes = parse + corrupted_memory = falling_bytes.take(1024).to_set + find_shortest_path_length(corrupted_memory) +end + +def part2 + falling_bytes = parse + min_t = 1024 + max_t = falling_bytes.length + while max_t > min_t + 1 + t = (max_t + min_t).div(2) + path_length = find_shortest_path_length(falling_bytes.take(t).to_set) + if path_length == -1 + max_t = t + else + min_t = t + end + end + falling_bytes[max_t - 1] +end + +puts 'Part 1' +puts part1 +puts '---' +puts 'Part 2' +puts part2",ruby +666,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","Node = Struct.new('Node', :x, :y, :corrupted, :score) + +class RamRun + attr_accessor :grid, :corruptions, :end_node + + DIRECTIONS = [[0, -1], [1, 0], [0, 1], [-1, 0]].freeze + + def self.create(input, grid_size) + ramrun = RamRun.new(grid_size) + ramrun.corruptions = input.map do |line| + line.split(',').map(&:to_i) + end + ramrun + end + + def initialize(size) + @grid = {} + (size + 1).times do |y| + (size + 1).times do |x| + @grid[[x, y]] = Node.new(x, y, false, Float::INFINITY) + end + end + @end_node = @grid[[size, size]] + end + + def reset + @grid.each_value do |node| + node.score = Float::INFINITY unless node.corrupted + end + end + + def neighbors(node) + DIRECTIONS.map do |(dx, dy)| + neighbor = grid[[node.x + dx, node.y + dy]] + if neighbor && !neighbor.corrupted && neighbor.score > node.score + 1 + neighbor.score = node.score + 1 + neighbor + end + end.compact + end + + def process(queue, shortest) + new_queue = Set.new + queue.each do |node| + if node == end_node + shortest = node.score if node.score < shortest + next + end + + new_queue.merge(neighbors(node)) + end + [new_queue, shortest] + end + + def traverse + start_node = grid[[0, 0]] + start_node.score = 0 + queue = Set[start_node] + shortest = Float::INFINITY + queue, shortest = process(queue, shortest) until queue.empty? + shortest + end + + def corrupt(num) + corruptions.each_with_index do |coord, i| + break if i == num + + grid[coord].corrupted = true + end + end + + def part1(num_corruptions) + corrupt(num_corruptions) + traverse + end + + def part2(num_corruptions) + corrupt(num_corruptions) + while num_corruptions < corruptions.size + coord = corruptions[num_corruptions] + grid[coord].corrupted = true + reset + return coord.join(',') if traverse == Float::INFINITY + + num_corruptions += 1 + end + end +end + +LINES_TO_READ = 1024 +GRID_SIZE = 70 + +ramrun = RamRun.create(IO.readlines(ARGV[0]), GRID_SIZE) +puts ramrun.part1(LINES_TO_READ) +puts ramrun.part2(LINES_TO_READ)",ruby +667,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 ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +def move_up(x, y, corrupted, visited, len) + return nil if y == 0 || corrupted[y - 1][x] == '#' || visited.has_key?(""#{x},#{y - 1}"") + return { x: x, y: y - 1 } +end + +def move_down(x, y, corrupted, visited, len) + return nil if y == len - 1 || corrupted[y + 1][x] == '#' || visited.has_key?(""#{x},#{y + 1}"") + return { x: x, y: y + 1 } +end + +def move_left(x, y, corrupted, visited, len) + return nil if x == 0 || corrupted[y][x - 1] == '#' || visited.has_key?(""#{x - 1},#{y}"") + return { x: x - 1, y: y } +end + +def move_right(x, y, corrupted, visited, len) + return nil if x == len - 1 || corrupted[y][x + 1] == '#' || visited.has_key?(""#{x + 1},#{y}"") + return { x: x + 1, y: y } +end + +input = File.read(file_path).split(""\n"").map{ |line| {x: line.split(',')[0], y: line.split(',')[1] } } + + +len = 71 +#len = 7 + +bytes = 1024 + + +for i in bytes..input.length do + +corrupted = Array.new(len) { Array.new(len, '.') } + input.take(i).each do |point| + corrupted[point[:x].to_i][point[:y].to_i] = '#' + end + + exited = false + + start = { x: 0, y: 0 } + finish = { x: len-1, y: len-1 } + candidates = [{last: start, score: 1, visited: { ""0,0"" => 1 }}] + all_visited = { ""0,0"" => 1 } + moves_left = true + + while moves_left + moves_left = false + + new_candidates = [] + candidates.each do |candidate| + x = candidate[:last][:x] + y = candidate[:last][:y] + visited = candidate[:visited] + score = candidate[:score] + + if x == finish[:x] && y == finish[:y] + exited = true + break + end + + up = move_up(x, y, corrupted, visited, len) + down = move_down(x, y, corrupted, visited, len) + left = move_left(x, y, corrupted, visited, len) + right = move_right(x, y, corrupted, visited, len) + + if !up.nil? && (!all_visited.has_key?(""#{up[:x]},#{up[:y]}"") || all_visited[""#{up[:x]},#{up[:y]}""] > score + 1) + new_visited = visited.dup + new_visited[""#{up[:x]},#{up[:y]}""] = 1 + candidates.push({ last: up, score: score + 1, visited: new_visited }) + all_visited[""#{up[:x]},#{up[:y]}""] = score + 1 + moves_left = true + end + + if !down.nil? && (!all_visited.has_key?(""#{down[:x]},#{down[:y]}"") || all_visited[""#{down[:x]},#{down[:y]}""] > score + 1) + new_visited = visited.dup + new_visited[""#{down[:x]},#{down[:y]}""] = 1 + candidates.push({ last: down, score: score + 1, visited: new_visited }) + all_visited[""#{down[:x]},#{down[:y]}""] = score + 1 + moves_left = true + end + + if !left.nil? && (!all_visited.has_key?(""#{left[:x]},#{left[:y]}"") || all_visited[""#{left[:x]},#{left[:y]}""] > score + 1) + new_visited = visited.dup + new_visited[""#{left[:x]},#{left[:y]}""] = 1 + candidates.push({ last: left, score: score + 1, visited: new_visited }) + all_visited[""#{left[:x]},#{left[:y]}""] = score + 1 + moves_left = true + end + + if !right.nil? && (!all_visited.has_key?(""#{right[:x]},#{right[:y]}"") || all_visited[""#{right[:x]},#{right[:y]}""] > score + 1) + new_visited = visited.dup + new_visited[""#{right[:x]},#{right[:y]}""] = 1 + candidates.push({ last: right, score: score + 1, visited: new_visited }) + all_visited[""#{right[:x]},#{right[:y]}""] = score + 1 + moves_left = true + end + + end + + candidates = new_candidates + end + + if exited == false + puts ""#{input[i-1][:x]},#{input[i-1][:y]}"" + exit + end + +end",ruby +668,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","lines = File.readlines('input.txt') + +all_coords = lines.map { |line| line.scan(/\d+/).map(&:to_i) } + +current_index = 1024 + +loop do + map = [] + 71.times do + map << [0] * 71 + end + + all_coords[0..current_index].each do |x, y| + map[y][x] = -1 + end + + paths = [[0, 0]] + cur_value = 1 + map[0][0] = 1 + + found = true + loop do + new_paths = [] + paths.each do |y, x| + if x < 70 && map[y][x + 1] == 0 + map[y][x + 1] = cur_value + 1 + new_paths << [y, x + 1] + end + if x > 0 && map[y][x - 1] == 0 + map[y][x - 1] = cur_value + 1 + new_paths << [y, x - 1] + end + if y < 70 && map[y + 1][x] == 0 + map[y + 1][x] = cur_value + 1 + new_paths << [y + 1, x] + end + if y > 0 && map[y - 1][x] == 0 + map[y - 1][x] = cur_value + 1 + new_paths << [y - 1, x] + end + end + + break if new_paths.include?([70, 70]) + + if new_paths.empty? + found = false + break + end + + paths = new_paths + cur_value += 1 + end + + break unless found + current_index += 1 +end + +puts all_coords[current_index].join(',')",ruby +669,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","TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +SIZE = TEST ? 7 : 71 +MOVES = [[0, 1], [1, 0], [0, -1], [-1, 0]] + +falling_bytes = File.read(path).split(""\n"").map { _1.split(',').map(&:to_i) } + +def print_map(map) + puts 'map' + map.each { |line| puts line.map { |pass| pass ? '.' : '#' }.join } + puts '' +end + +def possible(map) +start = [0, 0] +finish = [SIZE - 1, SIZE - 1] +scores = Array.new(SIZE) { Array.new(SIZE) { nil } } +scores[0][0] = 0 + +to_do = [start] + +current = nil +loop do + from = to_do.shift + return false if from.nil? + current = scores[from[0]][from[1]] + return true if from == finish + MOVES.each do |(yOffset, xOffset)| + y = from[0] + yOffset + x = from[1] + xOffset + next unless (0...SIZE).include?(x) && (0...SIZE).include?(y) + next unless map[y][x] + next unless scores[y][x].nil? + scores[y][x] = current + 1 + to_do << [y, x] + end +end +end + +success_index = 0 +fail_index = falling_bytes.count - 1 +loop do + break if success_index == fail_index - 1 + try_index = (fail_index + 1 + success_index) / 2 + map = Array.new(SIZE) { Array.new(SIZE) { true } } + (0..try_index).each do |byte_index| + byte = falling_bytes[byte_index] + map[byte[1]][byte[0]] = false + end + if possible(map) + success_index = try_index + else + fail_index = try_index + end +end + +# print_map(map) + +puts ""First impossible byte: #{falling_bytes[fail_index]}""",ruby +670,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n\n"") +$cache = {} + +def possible_towel(rule, possible_towels) + return $cache[rule] if $cache.has_key?(rule) + return 1 if rule == """" + + $cache[rule] = possible_towels.reduce(0) { |sum, towel| sum += (rule.start_with?(towel) ? possible_towel(rule[towel.size..-1], possible_towels) : 0) } + + return $cache[rule] +end + +towels = input[0].split("", "").sort_by { |towel| towel.size }.reverse +rules = input[1].split(""\n"") + +puts rules.map { |rule| possible_towel(rule, towels) }.select { |possible| possible != 0 }.size",ruby +671,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 parse_input + parsing = :patterns + patterns = [] + designs = [] + + File.readlines('inputs/19', chomp: true).each do |line| + if line == '' + parsing = :designs + next + end + + case parsing + when :patterns + patterns.concat(line.split(', ')) + when :designs + designs << line + end + end + + [patterns, designs] +end + +def solve + patterns, designs = parse_input + viable = Set.new + + designs.each do |design| + stack = [0] + visited = Set.new + + found = false + until stack.empty? || found + position = stack.pop + next if visited.include?(position) + visited << position + + if position == design.size + viable << design + found = true + break + end + + patterns.each do |pattern| + stack << position + pattern.size if design[position..-1].start_with?(pattern) + end + end + end + + viable.size +end + +p solve",ruby +672,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,"#! /usr/bin/env ruby + +def possible_design?(design, towels_by_start) + return true if design.empty? + + potential_towels = towels_by_start.fetch(design[0], []) + + # Check if any of the potential towels match the beginning of the design + matching_towels = potential_towels.select { |towel| design.start_with?(towel) } + return false if matching_towels.empty? + + matching_towels.any? do |towel| + remaining_design = design[towel.size..] + possible_design?(remaining_design, towels_by_start) + end +end + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file) + +towels = lines.first.split(',').map(&:strip) +designs = lines[2..].map(&:strip) +towels_by_start = towels.group_by { |t| t[0] } + +possible_designs = [] +designs.each do |design| + possible_designs << design if possible_design?(design, towels_by_start) +end + +puts ""Possible designs: #{possible_designs.inspect}"" +puts +puts ""Possible designs count: #{possible_designs.size}""",ruby +673,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,"#!/usr/bin/env ruby + +# Login to https://adventofcode.com/2024/day/19/input to download 'input.txt'. + +# lines = readlines +# lines = File.readlines('sample.txt', chomp: true) # Answer: 6 (in 39 ms) +lines = File.readlines('input.txt', chomp: true) # Answer: 213 (in 92 ms) + +separators = lines.map.with_index { |line, i| line.empty? ? i : nil }.compact + +towels = lines[0...(separators.first)].map { |line| line.split(', ') }.flatten + +puts 'Towels' +puts '------' +puts towels +puts + +wanted_designs = lines[(separators.first + 1)..] + +puts 'Wanted Designs' +puts '--------------' +puts wanted_designs +puts + +def possible?(design, towels) + return true if design.empty? + + towels.any? do |towel| + design.start_with?(towel) && possible?(design[(towel.size)..], towels) + end +end + +possible_designs = wanted_designs.select do |design| + possible?(design, towels) +end + +puts 'Possible Designs' +puts '----------------' +puts possible_designs +puts + +answer = possible_designs.size + +puts ""Answer: #{answer}""",ruby +674,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,"class Day19 + def initialize() + + end + + def read_process_input + res = 0 + towers = [] + + File.open(""Day19\\input19.txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + if i == 0 + towers = line.gsub(""\n"", """").split("", "") + towers = towers.sort_by { |element| element.length }.reverse + end + + if i > 0 && !line.strip.empty? + pattern = line + res += 1 if shuffle_and_try(towers, pattern) + end + end + end + return res + end + + def shuffle_and_try(towels, pattern) + works = false + + for i in 0..700 + shuffled_towels = towels.shuffle + works = true if is_pattern_possible?(shuffled_towels, pattern) + if works + break + end + end + return works + end + + def is_pattern_possible?(towels, pattern) + original_pattern = pattern + for t in towels + changed_pattern = pattern.gsub(t, ""|"") + if changed_pattern != pattern + pattern = changed_pattern + end + end + + if pattern.strip.gsub(""|"", """") == """" + return true + else + return false + end + end + +end + +day19 = Day19.new() +puts day19.read_process_input",ruby +675,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,"@designs_buff = {} + +def isPossible?(design,towels) + return true if design == """" + f=towels.any?{|t| design.start_with?(t) && isPossible?(design[t.size..],towels) } +end +def isPossible2?(design,towels) + return 1 if design == """" + return @designs_buff[design] if @designs_buff.key? design + f=towels.sum{|t| design.start_with?(t) ? isPossible2?(design[t.size..],towels) : 0 } + @designs_buff[design] = f + return f +end + +towels,designs = File.read(""Day19.txt"").split(""\n\n"") + +towels = towels.split("", "") +designs = designs.split +p designs.count{|design| isPossible?(design,towels)} +p designs.sum{|design| isPossible2?(design,towels)}",ruby +676,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,"class Towels + def initialize(filename) + @patterns = [] + @designs = [] + File.readlines(filename).each do |line| + if @patterns.empty? + @patterns = line.split("","").map { |pattern| pattern.strip } + elsif !line.strip.empty? + @designs.append(line.strip) + end + end + + @patterns = @patterns.sort_by(&:length).reverse + + #p @patterns + #p @designs + end + + def solve_part_1 + num_possible = 0 + @memo = Set.new + @memo_no = Set.new + @designs.each do |design| + puts ""Checking #{design}"" + if is_design_possible(design) + num_possible += 1 + puts "" #{design} is possible"" + else + puts "" #{design} is NOT possible"" + end + end + + puts ""Part 1 Answer: #{num_possible}"" + end + + def is_design_possible(design) + if @memo.include?(design) + return true + end + + if @memo_no.include?(design) + return false + end + + if design.length == 0 + return true + end + + @patterns.each do |pattern| + if pattern.length > design.length + next + end + + is_possible = true + pattern.chars.each_with_index do |c, index| + if c != design[index] + is_possible = false + break + end + end + + if !is_possible + next + end + + substr = design[pattern.length..] + #puts ""Checking #{substr} for patterns #{pattern}"" + if is_design_possible(substr) + @memo.add(substr) + return true + end + end + + @memo_no.add(design) + return false + end + + def solve_part_2 + num_possible = 0 + @memo_count = Hash.new + @memo_no = Set.new + @designs.each do |design| + puts ""Checking #{design}"" + num_possible += is_design_possible2(design) + end + + puts ""Part 2 Answer: #{num_possible}"" + end + + def is_design_possible2(design) + if @memo_count.key?(design) + return @memo_count[design] + end + + if @memo_no.include?(design) + return 0 + end + + if design.length == 0 + return 1 + end + + count = 0 + @patterns.each do |pattern| + if pattern.length > design.length + next + end + + is_possible = true + pattern.chars.each_with_index do |c, index| + if c != design[index] + is_possible = false + break + end + end + + if !is_possible + next + end + + substr = design[pattern.length..] + #puts ""Checking #{substr} for patterns #{pattern}"" + count += is_design_possible2(substr) + end + + if count == 0 + @memo_no.add(design) + else + @memo_count[design] = count + end + + return count + end +end + +towels = Towels.new(""day_19_input.txt"") +towels.solve_part_2",ruby +677,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,"#!/usr/bin/env ruby + +# Login to https://adventofcode.com/2024/day/19/input to download 'input.txt'. + +# lines = readlines +# lines = File.readlines('sample.txt', chomp: true) # Answer: 16 (in 43 ms) +lines = File.readlines('input.txt', chomp: true) # Answer: 1016700771200474 (in 267 ms) + +separators = lines.map.with_index { |line, i| line.empty? ? i : nil }.compact + +towels = lines[0...(separators.first)].map { |line| line.split(', ') }.flatten + +puts 'Towels' +puts '------' +puts towels +puts + +wanted_designs = lines[(separators.first + 1)..] + +puts 'Wanted Designs' +puts '--------------' +puts wanted_designs +puts + +DESIGN_CACHE = {} +def count_possibilities(design, towels) + return 1 if design.empty? + return DESIGN_CACHE[design] if DESIGN_CACHE.include?(design) + + count = towels + .select { |towel| design.start_with?(towel) } + .collect { |towel| count_possibilities(design[(towel.size)..], towels) } + .sum + + DESIGN_CACHE[design] = count + + count +end + +possible_designs = wanted_designs.map do |design| + count_possibilities(design, towels) +end + +puts 'Possible Designs' +puts '----------------' +puts possible_designs +puts + +answer = possible_designs.sum + +puts ""Answer: #{answer}""",ruby +678,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,"#! /usr/bin/env ruby + +def count_arrangements(suffix: design, towels:, count_cache: {}) + return 1 if suffix.empty? + return count_cache[suffix] if count_cache.key?(suffix) + + # Check if any of the towels match the beginning of the design + matching_towels = towels.select { |towel| suffix.start_with?(towel) } + return 0 if matching_towels.empty? + + result = matching_towels.sum do |towel| + remaining_design = suffix[towel.size..] + count_arrangements(suffix: remaining_design, towels:, count_cache:) + end + + count_cache[suffix] = result + result +end + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file) + +towels = lines.first.split(',').map(&:strip) +designs = lines[2..].map(&:strip) + +arrangements_count = 0 +designs.each do |design| + puts ""Checking design: #{design}"" + count = count_arrangements(suffix: design, towels:) + + if count > 0 + puts "" - Found #{count} possible arrangements"" + arrangements_count += count + else + puts "" - No possible arrangements found"" + end +end + +puts +puts ""Total arrangements: #{arrangements_count}"" + +# 848076019766013 - correct",ruby +679,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n\n"") +$cache = {} + +def possible_towel(rule, possible_towels) + return $cache[rule] if $cache.has_key?(rule) + return 1 if rule == """" + + $cache[rule] = possible_towels.reduce(0) { |sum, towel| sum += (rule.start_with?(towel) ? possible_towel(rule[towel.size..-1], possible_towels) : 0) } + + return $cache[rule] +end + +towels = input[0].split("", "").sort_by { |towel| towel.size }.reverse +rules = input[1].split(""\n"") + +puts rules.map { |rule| possible_towel(rule, towels) }.sum",ruby +680,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +THRESHOLD = 100 + +module Direction + UP = 0 + LEFT = 1 + DOWN = 2 + RIGHT = 3 + ALL = [UP, LEFT, DOWN, RIGHT] +end + +map = File.read(path).split(""\n"").map(&:chars) +start = nil +finish = nil +path_values = Array.new(map.count) { Array.new(map.first.count) { nil } } + +map.each_with_index do |line, y| + line.each_with_index do |char, x| + start = [y, x] if char == 'S' + finish = [y, x] if char == 'E' + end +end + +y_range = (0...map.count) +x_range = (0...map.first.count) + +def neighbor(y, x, dir) + case dir + when Direction::UP + [y - 1, x] + when Direction::LEFT + [y, x - 1] + when Direction::DOWN + [y + 1, x] + when Direction::RIGHT + [y, x + 1] + end +end + +current = start +path_values[start[0]][start[1]] = 0 + + +while current != finish + Direction::ALL.each do |dir| + forward = neighbor(current[0], current[1], dir) + if map[forward[0]][forward[1]] != '#' && path_values[forward[0]][forward[1]].nil? + path_values[forward[0]][forward[1]] = path_values[current[0]][current[1]] + 1 + current = forward + break + end + end +end + +cheats = Hash.new { |hash, key| Array.new } + +path_values.each_with_index do |line, y| + line.each_with_index do |time, x| + next if time.nil? + Direction::ALL.each do |dir1| + move1 = neighbor(y, x, dir1) + next unless y_range.include?(move1[0]) && x_range.include?(move1[1]) && path_values[move1[0]][move1[1]].nil? + Direction::ALL.each do |dir2| + move2 = neighbor(move1[0], move1[1], dir2) + next unless y_range.include?(move2[0]) && x_range.include?(move2[1]) && !path_values[move2[0]][move2[1]].nil? + time_saved = path_values[move2[0]][move2[1]] - time - 2 + cheats[time_saved] = cheats[time_saved] << [move1, move2] if time_saved.positive? + end + end + end +end + +number_of_good_cheats = cheats.keys.filter {_1 >= THRESHOLD}.reduce(0) do |sum, k| + sum + cheats[k].count +end + +puts ""There are #{number_of_good_cheats} cheats that saves more than #{THRESHOLD} picoseconds.""",ruby +681,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,"# Assumptions: +# +# (1) Even though the problem statement says that ""a program may disable collision for up to 2 picoseconds"", +# only ONE wall segment may be passed through. +# +# (2) A cheat will always be a straight pass-through -- not cutting a corner. That is, there will be no map +# sections like this: +# #. +# .# + +class Point + attr_accessor :y, :x + + def initialize(y, x) + @y = y + @x = x + end + + def eql?(other) + other.is_a?(Point) && @y == other.y && @x == other.x + end + + def hash + @y.hash ^ @x.hash + end + + def ==(other) + eql?(other) + end + + def +(other) + Point.new(@y + other.y, @x + other.x) + end +end + +# Walk the (single-path) map, and set the map_steps for each point as we go. +# When we're done, any map position that doesn't have an entry in map_steps +# is a wall. +def assign_position_costs(map, start_point) + map_steps = { start_point => 0 } + directions = [Point.new(-1, 0), Point.new(1, 0), Point.new(0, -1), Point.new(0, 1)] + point = start_point + reached_the_end = false + + until reached_the_end + reached_the_end = true + + directions.each do |step| + next_point = point + step + next if map[next_point.y][next_point.x] == '#' + + # If we already have a step count for a point, then we already visited it. + next if map_steps.key?(next_point) + + map_steps[next_point] = map_steps[point] + 1 + point = next_point + reached_the_end = false + break + end + end + + map_steps +end + +# For each wall, if there's open space on opposite sides of the wall (either vertically or +# horizontally), then the time saved by cheating will be the difference in steps between those +# two open spaces, minus 2 (the time it takes to walk through the wall). +def cheats_time_saved(map, map_steps) + cheats_time_saved = [] + map.each_index do |y| + map[y].each_char.with_index do |char, x| + next unless char == '#' + + if map_steps.key?(Point.new(y - 1, x)) && map_steps.key?(Point.new(y + 1, x)) + cheats_time_saved << (map_steps[Point.new(y - 1, x)] - map_steps[Point.new(y + 1, x)]).abs - 2 + elsif map_steps.key?(Point.new(y, x - 1)) && map_steps.key?(Point.new(y, x + 1)) + cheats_time_saved << (map_steps[Point.new(y, x - 1)] - map_steps[Point.new(y, x + 1)]).abs - 2 + end + end + end + cheats_time_saved +end + +start_point = nil +map = File.readlines('day-20/input.txt').map(&:chomp) +map.each_with_index do |line, y| + line.each_char.with_index do |char, x| + start_point = Point.new(y, x) if char == 'S' + end +end + +map_steps = assign_position_costs(map, start_point) + +times_saved = cheats_time_saved(map, map_steps) +p times_saved.select { |time_saved| time_saved >= 100 }.count",ruby +682,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,"require 'set' + +day = ""20"" +file_name = ""12-#{day}-24/sampleIn.txt"" +file_name = ""input.txt"" + +data = File.read(file_name).split(""\n"").map { |i| i.rstrip } + +def manhattan(a, b) + return (a[0] - b[0]).abs + (a[1] - b[1]).abs +end + +def aStar(start, goal, walls, memo) + if walls.include? start + memo[start] = Float::INFINITY + return Float::INFINITY + end + if memo[start] + return memo[start] + end + seen = Set[start] + queue = { + manhattan(start, goal) => [[[start], 0]] + } + + while queue.size > 0 + quickest = queue.keys.min + cur = queue[quickest].shift + curPath = cur[0] + curLoc = curPath.last + if queue[quickest].length == 0 + queue.delete(quickest) + end + if memo[curLoc] + return memo[curLoc] + end + curDist = cur[1] + if curLoc == goal + for i in 0...curPath.length + memo[curPath[i].clone] = curDist - i + end + return curDist + end + + for d in [[1, 0], [0, 1], [-1, 0], [0, -1]] + nextLoc = [curLoc[0] + d[0], curLoc[1] + d[1]] + next if seen.include? nextLoc + next if walls.include? nextLoc + seen.add(nextLoc) + + heuristic = curDist + 1 + manhattan(nextLoc, goal) + + newPath = curPath + [nextLoc] + + if not queue[heuristic] + queue[heuristic] = [] + end + queue[heuristic].append([newPath, curDist + 1]) + end + end + memo[start] = Float::INFINITY + return Float::INFINITY +end + +def cheatStar(start, goal, walls, toBeat, yMax, xMax, noCheatFastest) + cheats = {} + + seen = Set[start] + queue = { + manhattan(start, goal) => [[Set[start], 0, false, start]] + } + + maxIter = 10 + iter = 0 + + while queue.keys.size > 0 + # if iter >= maxIter + # break + # end + iter += 1 + quickest = queue.keys.min + cur = queue[quickest].shift + curPath = cur[0] + curDist = cur[1] + cheat = cur[2] + curLoc = cur[3] + if queue[quickest].length == 0 + queue.delete(quickest) + end + if curLoc == goal + cheats[cheat] = curDist + next + end + if cheat and not curLoc == cheat + if not noCheatFastest[curLoc] + aStar(curLoc, goal, walls, noCheatFastest) + end + # print noCheatFastest + # puts + # print curLoc + # puts + cheats[cheat] = curDist + noCheatFastest[curLoc] - 1 + next + end + + for d in [[1, 0], [0, 1], [-1, 0], [0, -1]] + cheat = cur[2] + nextLoc = [curLoc[0] + d[0], curLoc[1] + d[1]] + if nextLoc[0] < 0 or nextLoc[1] < 0 or nextLoc[0] >= yMax or nextLoc[1] >= xMax + next + end + next if curPath.include? nextLoc + + if walls.include? nextLoc + next if cheat + next if cheats[nextLoc] + cheat = nextLoc.clone + end + + heuristic = curDist + 1 + manhattan(nextLoc, goal) + next if heuristic >= toBeat - 100 + + newPath = curPath + Set[nextLoc] + + if not queue[heuristic] + queue[heuristic] = [] + end + queue[heuristic].append([newPath, curDist + 1, cheat, nextLoc]) + end + # print queue + # puts + end + + return cheats +end + +def countCheats(start, goal, walls, toBeat, yMax, xMax, noCheatFastest, cheatDist=20, timeSave=100) + cheats = 0 + + queue = { + manhattan(start, goal) => [[Set[start], 0, start]] + } + + while queue.keys.size > 0 + quickest = queue.keys.min + cur = queue[quickest].shift + curPath = cur[0] + curDist = cur[1] + curLoc = cur[2] + if queue[quickest].length == 0 + queue.delete(quickest) + end + if curLoc == goal + return cheats + end + + for dy in (-1 * cheatDist)..(cheatDist) + dxMax = cheatDist - dy.abs + for dx in (-1 * dxMax)..(dxMax) + cheatTo = [curLoc[0] + dy, curLoc[1] + dx] + next if walls.include? cheatTo + if cheatTo[0] < 0 or cheatTo[1] < 0 or cheatTo[0] >= yMax or cheatTo[1] >= xMax + next + end + aStar(cheatTo, goal, walls, noCheatFastest) + totalDist = curDist + manhattan(curLoc, cheatTo) + noCheatFastest[cheatTo] + if totalDist <= toBeat - timeSave + cheats += 1 + end + end + end + + for d in [[1, 0], [0, 1], [-1, 0], [0, -1]] + nextLoc = [curLoc[0] + d[0], curLoc[1] + d[1]] + + next if walls.include? nextLoc + next if curPath.include? nextLoc + + heuristic = curDist + 1 + manhattan(nextLoc, goal) + next if heuristic > toBeat - timeSave + + newPath = curPath + Set[nextLoc] + + if not queue[heuristic] + queue[heuristic] = [] + end + queue[heuristic].append([newPath, curDist + 1, nextLoc]) + end + end + + return cheats +end + +def part1(input) + + start = nil + goal = nil + walls = Set[] + for i in 0...input.length + for j in 0...input[i].length + if input[i][j] == ""S"" + start = [i, j] + # input[i][j] = ""."" + end + if input[i][j] == ""E"" + goal = [i, j] + # input[i][j] = ""."" + end + if input[i][j] == ""#"" + walls.add([i, j]) + end + end + end + + memo = {} + + minDist = aStar(start, goal, walls, memo) + + # puts minDist + + # cheatList = cheatStar(start, goal, walls, minDist, input.length, input[0].length, memo) + + # # print cheatList + # # puts + + # good = 0 + + # for i in cheatList.keys + # if minDist - cheatList[i] >= 100 + # good += 1 + # end + # end + + # return good + # + return countCheats(start, goal, walls, minDist, input.length, input[0].length, memo, cheatDist=2, timeSave=100) +end + +def cheatStar2(start, goal, walls, toBeat, yMax, xMax, noCheatFastest) + cheats = {} + + queue = { + manhattan(start, goal) => [[Set[start], 0, ""unused"", start, nil, nil, 0]] + } + + + # path, dist, cheatUsed, curNode, cheatStart, cheatEnd, cheatLen + + maxIter = 20000 + iter = 0 + + while queue.keys.size > 0 + # if iter >= maxIter + # break + # end + # iter += 1 + quickest = queue.keys.min + cur = queue[quickest].shift + curPath = cur[0] + curDist = cur[1] + cheat = cur[2] + curLoc = cur[3] + cheatStart = cur[4] + cheatEnd = cur[5] + cheatLen = cur[6] + if queue[quickest].length == 0 + queue.delete(quickest) + end + if cheat == ""done"" + if walls.include? curLoc + cheats[[cheatStart, cheatEnd]] = Float::INFINITY + else + if not noCheatFastest[curLoc] + aStar(curLoc, goal, walls, noCheatFastest) + end + # print noCheatFastest + # puts + # print curLoc + # puts + if (not cheats[[cheatStart, cheatEnd]]) or (curDist + noCheatFastest[curLoc] - 1 < cheats[[cheatStart, cheatEnd]]) + cheats[[cheatStart, cheatEnd]] = curDist + noCheatFastest[curLoc] + end + end + next + end + if curLoc == goal + if cheat == ""done"" or cheat == ""in progress"" + if cheatStart == [3, 1] + puts ""here"" + end + cheats[[cheatStart, goal]] = curDist + end + next + end + + for d in [[1, 0], [0, 1], [-1, 0], [0, -1]] + cheatStart = cur[4] + cheatEnd = cur[5] + cheatLen = cur[6] + cheat = cur[2] + nextLoc = [curLoc[0] + d[0], curLoc[1] + d[1]] + if nextLoc[0] < 0 or nextLoc[1] < 0 or nextLoc[0] >= yMax or nextLoc[1] >= xMax + next + end + + if walls.include? nextLoc + if cheat == ""done"" + raise ""I don't think this should happen"" + end + next if cheatLen >= 20 + if cheat == ""unused"" + cheatStart = curLoc + # nextCheatEnd = nextLoc + cheatLen = 1 + cheat = ""in progress"" + elsif cheat == ""in progress"" + # nextCheatEnd = nextLoc + # nextCheatStart = cheatStart + cheatLen = cheatLen + 1 + # nextCheat = ""in progress"" + end + elsif cheat == ""in progress"" + cheat = ""done"" + cheatEnd = nextLoc + cheatLen = cheatLen + end + next if curPath.include? nextLoc + + heuristic = curDist + 1 + manhattan(nextLoc, goal) + aStar(nextLoc, goal, walls, noCheatFastest) + if cheat == ""done"" + heuristic = curDist + noCheatFastest[nextLoc] + end + next if heuristic > toBeat - 50 + + newPath = curPath + Set[nextLoc] + + if not queue[heuristic] + queue[heuristic] = [] + end + queue[heuristic].append([newPath, curDist + 1, cheat, nextLoc, cheatStart, cheatEnd, cheatLen]) + end + # print queue + # puts + end + + return cheats +end + +puts part1(data)",ruby +683,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,"def parse_input + tiles = [] + start = nil + destination = nil + + File.readlines('inputs/20', chomp: true).each_with_index do |line, row| + line.chars.each_with_index do |char, col| + start = [row, col] if char == 'S' + destination = [row, col] if char == 'E' + tiles << [row, col] if char != '#' + end + end + + [tiles, start, destination] +end + +def find_path(tiles, start, destination) + path = [start] + current = start + + while current != destination + path << current + x, y = current + + # Find the next valid tile (only one option) + current = [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]].find do |nx, ny| + tiles.include?([nx, ny]) && !path.include?([nx, ny]) + end + end + + path << destination + path +end + +def find_shortcuts(path) + shortcuts = Hash.new(0) + + path.each_with_index do |(row, col), index| + directions = [[2, 0], [-2, 0], [0, 2], [0, -2]] + directions.each do |dx, dy| + next_position = [row + dx, col + dy] + next unless path.include?(next_position) + + next_index = path.index(next_position) + if next_index && next_index > index + shortcut_length = next_index - index - 2 + shortcuts[shortcut_length] += 1 if shortcut_length >= 100 + end + end + end + + shortcuts +end + +tiles, start, destination = parse_input +path = find_path(tiles, start, destination) +shortcuts = find_shortcuts(path) + +puts shortcuts.values.sum",ruby +684,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,"require 'set' + +input = File.read('input.txt').split(""\n"").map(&:strip) + +# problem 1 + +track_coords = Set.new +start = nil +goal = nil + +input.each.with_index do |line, y| + line.chars.each.with_index do |c, x| + if c == 'S' + start = [x, y] + track_coords.add([x, y]) + elsif c == 'E' + goal = [x, y] + track_coords.add([x, y]) + elsif c == '.' + track_coords.add([x, y]) + end + end +end + +visited = Set.new +track_path = [start] + +pos = start + +while pos != goal + visited.add(pos) + x, y = pos + + [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ].each do |offsets| + offset_x, offset_y = offsets + + new_x = x + offset_x + new_y = y + offset_y + + if track_coords.include?([new_x, new_y]) && !visited.include?([new_x, new_y]) + pos = [new_x, new_y] + + track_path.push(pos) + break + end + end +end + +visited = Set.new +total = 0 + +track_indexes = {} + +track_path.each.with_index do |pos, idx| + track_indexes[pos] = idx +end + +track_path.each.with_index do |pos, idx| + visited.add(pos) + + x, y = pos + + [ + [2, 0], + [-2, 0], + [0, 2], + [0, -2], + ].each do |offsets| + offset_x, offset_y = offsets + + new_x = x + offset_x + new_y = y + offset_y + + new_idx = track_indexes[[new_x, new_y]] + next if new_idx.nil? || new_idx < idx + + savings = new_idx - idx - 2 + + total += 1 if savings >= 100 + end +end + +puts total",ruby +685,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,"class Point + attr_accessor :y, :x + + def initialize(y, x) + @y = y + @x = x + end + + def eql?(other) + other.is_a?(Point) && @y == other.y && @x == other.x + end + + def hash + @y.hash ^ @x.hash + end + + def ==(other) + eql?(other) + end + + def +(other) + Point.new(@y + other.y, @x + other.x) + end +end + +# Walk the (single-path) map, and set the map_steps for each point as we go. +# When we're done, any map position that doesn't have an entry in map_steps +# is a wall. +def assign_position_costs(map, start_point) + map_steps = { start_point => 0 } + directions = [Point.new(-1, 0), Point.new(1, 0), Point.new(0, -1), Point.new(0, 1)] + point = start_point + reached_the_end = false + + until reached_the_end + reached_the_end = true + + directions.each do |step| + next_point = point + step + next if map[next_point.y][next_point.x] == '#' + + # If we already have a step count for a point, then we already visited it. + next if map_steps.key?(next_point) + + map_steps[next_point] = map_steps[point] + 1 + point = next_point + reached_the_end = false + break + end + end + + map_steps +end + +# The instructions for this problem are ambiguous in that they don't specify whether a given cheat +# needs to actually be strictly ""advantageous"" to be counted. For example, consider the following map: +# +# ######################### +# #S......................# +# #######################.# +# #.......................# +# #.####################### +# #E# +# ### +# +# It turns out that a cheat from that start point all the way to the end point -- with a step distance of 4 -- +# IS supposed to be counted as a possible cheat, even though the last 2 steps of that distance (after passing +# through the long horizontal wall; and then continuing on to unnecessarily ""cheat"" through 2 more steps of open +# space) are only partially really ""cheating"". +# +# This does actually make the code simpler, as we don't need to do any kind of check that a cheat +# begins with entering a wall, or ends with emerging from a wall. (Including figuring out how to deal with +# possible cases where the endpoint might be reachable from one direction (e.g. north) through a wall, but +# reachable from the other direction (e.g. west) through an open space.) +MAX_CHEAT_DISTANCE = 20 +def cheat_destinations(start_point, map_steps) + destinations = [] + ((start_point.y - MAX_CHEAT_DISTANCE)..(start_point.y + MAX_CHEAT_DISTANCE)).each do |y| + ((start_point.x - MAX_CHEAT_DISTANCE)..(start_point.x + MAX_CHEAT_DISTANCE)).each do |x| + next if (y - start_point.y).abs + (x - start_point.x).abs > MAX_CHEAT_DISTANCE + next if y == start_point.y && x == start_point.x + + destination = Point.new(y, x) + + next unless map_steps.key?(destination) + next if map_steps[start_point] > map_steps[destination] + + destinations << destination + end + end + destinations +end + +def cheats_time_saved(map, map_steps) + cheats_time_saved = Hash.new(0) + map.each_index do |y| + map[y].each_char.with_index do |char, x| + next unless char != '#' + + start_point = Point.new(y, x) + destinations = cheat_destinations(start_point, map_steps) + destinations.each do |destination| + time_saved = (map_steps[destination] - map_steps[start_point]) - (start_point.y - destination.y).abs - (start_point.x - destination.x).abs + cheats_time_saved[time_saved] += 1 if time_saved.positive? + end + end + end + cheats_time_saved +end + +def find_start_point(map) + map.each_with_index do |line, y| + line.each_char.with_index do |char, x| + return Point.new(y, x) if char == 'S' + end + end +end + +map = File.readlines('day-20/input.txt').map(&:chomp) +start_point = find_start_point(map) +map_steps = assign_position_costs(map, start_point) + +times_saved = cheats_time_saved(map, map_steps) + +p times_saved.select { |time_saved, _| time_saved >= 100 }.values.sum",ruby +686,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,"require 'set' + +input = File.read('input.txt').split(""\n"").map(&:strip) + +# problem 1 + +track_coords = Set.new +start = nil +goal = nil + +input.each.with_index do |line, y| + line.chars.each.with_index do |c, x| + if c == 'S' + start = [x, y] + track_coords.add([x, y]) + elsif c == 'E' + goal = [x, y] + track_coords.add([x, y]) + elsif c == '.' + track_coords.add([x, y]) + end + end +end + +visited = Set.new +track_path = [start] + +pos = start + +while pos != goal + visited.add(pos) + x, y = pos + + [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ].each do |offsets| + offset_x, offset_y = offsets + + new_x = x + offset_x + new_y = y + offset_y + + if track_coords.include?([new_x, new_y]) && !visited.include?([new_x, new_y]) + pos = [new_x, new_y] + + track_path.push(pos) + break + end + end +end + +visited = Set.new +total = 0 + +track_indexes = {} + +track_path.each.with_index do |pos, idx| + track_indexes[pos] = idx +end + + +# problem 2 + +total = 0 + +def distance(a, b) + (a[0] - b[0]).abs + (a[1] - b[1]).abs +end + +track_path.each.with_index do |pos1, idx1| + track_path.each.with_index do |pos2, idx2| + next if idx1 >= idx2 + + dist = distance(pos1, pos2) + next if distance(pos1, pos2) > 20 + + savings = idx2 - idx1 - dist + + total += 1 if savings >= 100 + end +end + +puts total",ruby +687,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,"# frozen_string_literal: true + +INPUT_PATH = 'input.txt' + +Coordinate = Data.define(:x, :y) do + def +(other) + return unless other.is_a?(self.class) + + Coordinate.new(x + other.x, y + other.y) + end + + def -(other) + return unless other.is_a?(self.class) + + Coordinate.new(x - other.x, y - other.y) + end +end + +def parse + lines = File.readlines(INPUT_PATH).map(&:strip) + + track_start = nil + track_end = nil + track = Set.new + + y = 0 + while y < lines.length + x = 0 + while x < lines[y].length + case lines[y][x] + when '.' + track.add(Coordinate.new(x, y)) + when 'S' + track_start = Coordinate.new(x, y) + track.add(Coordinate.new(x, y)) + when 'E' + track_end = Coordinate.new(x, y) + track.add(Coordinate.new(x, y)) + end + x += 1 + end + y += 1 + end + + max_x = x - 1 + max_y = y - 1 + + seen = Set[track_start] + track_indices = {} + track_indices[track_start] = 0 + last = track_start + i = 0 + while track_indices.size < track.size + i += 1 + neighbours = neighbours_in_map(last, max_x, max_y).filter { |n| track.include?(n) && !seen.include?(n) } + puts ""Not a single track: #{last}, #{neighbours}"" if neighbours.size != 1 + + track_indices[neighbours[0]] = i + seen.add(neighbours[0]) + last = neighbours[0] + end + + [track_start, track_end, track, track_indices, max_x, max_y] +end + +def neighbours_in_map(location, max_x, max_y) + [ + (location + Coordinate.new(1, 0) if location.x < max_x), + (location - Coordinate.new(1, 0) if location.x.positive?), + (location + Coordinate.new(0, 1) if location.y < max_y), + (location - Coordinate.new(0, 1) if location.y.positive?) + ].compact +end + +def locations_within_distance(location, distance, max_x, max_y) + locations = Set.new + i = 0 + while i <= distance + j = 0 + while j <= distance - i + locations.add(location + Coordinate.new(i, j)) if location.x <= max_x - i && location.y <= max_y - j + locations.add(location + Coordinate.new(i, -j)) if location.x <= max_x - i && location.y >= j + locations.add(location + Coordinate.new(-i, j)) if location.x >= i && location.y <= max_y - j + locations.add(location + Coordinate.new(-i, -j)) if location.x >= i && location.y >= j + j += 1 + end + i += 1 + end + locations.delete(location) + locations +end + +def find_cheats_from_location(location, track, track_indices, max_cheat_distance, max_x, max_y) + cheats = {} + locations_within_distance(location, max_cheat_distance, max_x, max_y).each do |position| + if track.include?(position) + saved = (track_indices[position] - track_indices[location]) - ((position.x - location.x).abs + (position.y - location.y).abs) + cheats[position] = saved + end + end + + cheats +end + +def part1 + track_start, track_end, track, track_indices, max_x, max_y = parse + count = 0 + track.each do |location| + next if location == track_end + + cheats = find_cheats_from_location(location, track, track_indices, 2, max_x, max_y) + cheats.each_value do |value| + count += 1 if value >= 100 + end + end + + count +end + +def part2 + track_start, track_end, track, track_indices, max_x, max_y = parse + count = 0 + track.each do |location| + next if location == track_end + + cheats = find_cheats_from_location(location, track, track_indices, 20, max_x, max_y) + cheats.each_value do |value| + count += 1 if value >= 100 + end + end + + count +end + +puts 'Part 1' +puts part1 +puts '---' +puts 'Part 2' +puts part2",ruby +688,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +THRESHOLD = TEST ? 50 : 100 +MAX_CHEAT_TIME = 20 + +module Direction + UP = 0 + LEFT = 1 + DOWN = 2 + RIGHT = 3 + ALL = [UP, LEFT, DOWN, RIGHT] +end + +map = File.read(path).split(""\n"").map(&:chars) +start = nil +finish = nil +path_values = Array.new(map.count) { Array.new(map.first.count) { nil } } + +map.each_with_index do |line, y| + line.each_with_index do |char, x| + start = [y, x] if char == 'S' + finish = [y, x] if char == 'E' + end +end + +y_range = (0...map.count) +x_range = (0...map.first.count) + +def neighbor(y, x, dir) + case dir + when Direction::UP + [y - 1, x] + when Direction::LEFT + [y, x - 1] + when Direction::DOWN + [y + 1, x] + when Direction::RIGHT + [y, x + 1] + end +end + +current = start +path_values[start[0]][start[1]] = 0 + + +while current != finish + Direction::ALL.each do |dir| + forward = neighbor(current[0], current[1], dir) + if map[forward[0]][forward[1]] != '#' && path_values[forward[0]][forward[1]].nil? + path_values[forward[0]][forward[1]] = path_values[current[0]][current[1]] + 1 + current = forward + break + end + end +end + +cheats = Hash.new { |hash, key| Set.new } + +path_values.each_with_index do |line, y| + line.each_with_index do |time, x| + next if time.nil? + tmp = 0 + ((y - MAX_CHEAT_TIME)..(y + MAX_CHEAT_TIME)).each do |end_y| + ((x - MAX_CHEAT_TIME)..(x + MAX_CHEAT_TIME)).each do |end_x| + next unless y_range.include?(end_y) && x_range.include?(end_x) && !path_values[end_y][end_x].nil? + distance = (end_y - y).abs + (end_x - x).abs + if (2..MAX_CHEAT_TIME).include?(distance) && map[end_y][end_x] != '#' + tmp += 1 + time_saved = path_values[end_y][end_x] - time - distance + cheats[time_saved] = cheats[time_saved] << [[y, x], [end_y, end_x]] if time_saved.positive? + end + end + end + end +end + +number_of_good_cheats = cheats.keys.filter {_1 >= THRESHOLD}.reduce(0) do |sum, k| + sum + cheats[k].count +end + +cheats.keys.sort.filter {_1 >= THRESHOLD}.each do |k| + puts ""There are #{cheats[k].count} cheats that save #{k} picoseconds."" +end + +puts ""There are #{number_of_good_cheats} cheats that saves more than #{THRESHOLD} picoseconds.""",ruby +689,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,"require 'set' + +input_text = File.readlines(""input.txt"", chomp: true) + +start = [-1, -1] +end_pos = [-1, -1] +walls = Set.new + +input_text.each_with_index do |line, row| + line.chars.each_with_index do |char, col| + case char + when ""S"" + start = [row, col] + when ""E"" + end_pos = [row, col] + when ""#"" + walls.add([row, col]) + end + end +end + +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_pos + moves.each do |row_move, col_move| + new_pos = [current_pos[0] + row_move, current_pos[1] + col_move] + unless walls.include?(new_pos) || no_cheat_move_count.key?(new_pos) + move_count += 1 + current_pos = new_pos + no_cheat_move_count[current_pos] = move_count + break + end + end +end + +cheat_moves = [] +(-20..20).each do |delta_row| + (-(20 - delta_row.abs)..(20 - delta_row.abs)).each do |delta_col| + cheat_moves << [delta_row, delta_col] + end +end + +cheats = Hash.new(0) + +no_cheat_move_count.each do |(initial_row, initial_col), step| + cheat_moves.each do |row_move, col_move| + cheat_pos = [initial_row + row_move, initial_col + col_move] + if no_cheat_move_count.key?(cheat_pos) && + no_cheat_move_count[cheat_pos] > step + row_move.abs + col_move.abs + cheats[no_cheat_move_count[cheat_pos] - step - row_move.abs - col_move.abs] += 1 + end + end +end + +puts cheats.select { |saving, count| saving >= 100 }.values.sum",ruby +690,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,"require 'set' +require 'json' + +keypad_sequences = File.read('input.txt').split(""\n"") + +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] +} +keypad_bad_position = [3, 0] +start_keypad = [3, 2] + +directional_pad = { + '#' => [0, 0], '^' => [0, 1], 'A' => [0, 2], + '<' => [1, 0], 'v' => [1, 1], '>' => [1, 2] +} +directional_pad_bad_position = [0, 0] +start_directional_pad = [0, 2] + +def get_numeric_part(code) + code.chars.select { |char| char =~ /\d/ }.join +end + +def get_directions(drow, dcol) + res = [] + res << 'v' * drow if drow > 0 + res << '^' * drow.abs if drow < 0 + res << '>' * dcol if dcol > 0 + res << '<' * dcol.abs if dcol < 0 + res.join +end + +def get_possible_permutations(pos, directions, bad_position) + perms = directions.chars.permutation.to_a.map(&:join).to_set + perms.select { |perm| validate_path(pos, perm, bad_position) } +end + +def validate_path(pos, directions, bad_position) + _pos = pos.dup + directions.chars.each do |direction| + case direction + when 'v' then _pos = [_pos[0] + 1, _pos[1]] + when '^' then _pos = [_pos[0] - 1, _pos[1]] + when '>' then _pos = [_pos[0], _pos[1] + 1] + when '<' then _pos = [_pos[0], _pos[1] - 1] + end + return false if _pos == bad_position + end + true +end + +def get_direction_to_write_code(input, start_keypad, keypad, keypad_bad_position) + pos = start_keypad + result = [] + + input.chars.each do |elem| + next_pos = keypad[elem] + drow = next_pos[0] - pos[0] + dcol = next_pos[1] - pos[1] + directions = get_directions(drow, dcol) + valid_paths = get_possible_permutations(pos, directions, keypad_bad_position) + + if result.empty? + valid_paths.each { |path| result << path + 'A' } + else + result = result.flat_map { |res| valid_paths.map { |path| res + path + 'A' } } + end + + pos = next_pos + end + + result +end + +def get_direction_to_write_direction(input, start_directional_pad, directional_pad, directional_pad_bad_position) + pos = start_directional_pad + result = [] + + input.chars.each do |elem| + next_pos = directional_pad[elem] + drow = next_pos[0] - pos[0] + dcol = next_pos[1] - pos[1] + directions = get_directions(drow, dcol) + valid_paths = get_possible_permutations(pos, directions, directional_pad_bad_position) + + if result.empty? + valid_paths.each { |path| result << path + 'A' } + else + result = result.flat_map { |res| valid_paths.map { |path| res + path + 'A' } } + end + + pos = next_pos + end + + min_length = result.map(&:length).min + result.select { |r| r.length == min_length } +end + +def get_direction_to_write_direction_sample(input, start_directional_pad, directional_pad, directional_pad_bad_position) + pos = start_directional_pad + result = [] + + input.chars.each do |elem| + next_pos = directional_pad[elem] + drow = next_pos[0] - pos[0] + dcol = next_pos[1] - pos[1] + directions = get_directions(drow, dcol) + valid_paths = get_possible_permutations(pos, directions, directional_pad_bad_position).first + result << valid_paths + result << 'A' + pos = next_pos + end + + result.join +end + +def calculate_complexity(code, start_keypad, keypad, keypad_bad_position, start_directional_pad, directional_pad, directional_pad_bad_position) + sol1 = get_direction_to_write_code(code, start_keypad, keypad, keypad_bad_position) + sol2 = sol1.flat_map { |sol| get_direction_to_write_direction(sol, start_directional_pad, directional_pad, directional_pad_bad_position) } + sol3 = sol2.map { |elem| get_direction_to_write_direction_sample(elem, start_directional_pad, directional_pad, directional_pad_bad_position) } + + puts sol3.first + puts sol2.first + puts sol1.first + puts code + + min_length = sol3.map(&:length).min + num = get_numeric_part(code) + + puts ""Code: Numeric: #{num}, minimum length: #{min_length}"" + min_length * num.to_i +end + +total = 0 +keypad_sequences.each do |code| + score = calculate_complexity(code, start_keypad, keypad, keypad_bad_position, start_directional_pad, directional_pad, directional_pad_bad_position) + total += score + puts +end + +puts total",ruby +691,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,"def numeric_keypad_best_path(from, to) + case from + when 'A' + case to + when 'A'; '' + when '0'; '<' + when '1'; '^<<' + when '2'; '<^' + when '3'; '^' + when '4'; '^^<<' + when '5'; '<^^' + when '6'; '^^' + when '7'; '^^^<<' + when '8'; '<^^^' + when '9'; '^^^' + end + when '0' + case to + when 'A'; '>' + when '0'; '' + when '1'; '^<' + when '2'; '^' + when '3'; '^>' + when '4'; '^^<' + when '5'; '^^' + when '6'; '^^>' + when '7'; '^^^<' + when '8'; '^^^' + when '9'; '^^^>' + end + when '1' + case to + when 'A'; '>>v' + when '0'; '>v' + when '1'; '' + when '2'; '>' + when '3'; '>>' + when '4'; '^' + when '5'; '^>' + when '6'; '^>>' + when '7'; '^^' + when '8'; '^^>' + when '9'; '^^>>' + end + when '2' + case to + when 'A'; 'v>' + when '0'; 'v' + when '2'; '' + when '1'; 'v' + when '3'; '>' + when '4'; '<^' + when '5'; '^' + when '6'; '^>' + when '7'; '<^^' + when '8'; '^^' + when '9'; '^^>' + end + when '3' + case to + when 'A'; 'v' + when '0'; '>vv' + when '0'; '>vv' + when '1'; 'v' + when '2'; 'v>' + when '3'; 'v>>' + when '4'; '' + when '5'; '>' + when '6'; '>>' + when '7'; '^' + when '8'; '^>' + when '9'; '^>>' + end + when '5' + case to + when 'A'; 'vv>' + when '0'; 'vv' + when '1'; '' + when '4'; '<' + when '5'; '' + when '6'; '>' + when '7'; '<^' + when '8'; '^' + when '9'; '^>' + end + when '6' + case to + when 'A'; 'vv' + when '0'; '>vvv' + when '0'; '>vvv' + when '1'; 'vv' + when '2'; 'vv>' + when '3'; 'vv>>' + when '4'; 'v' + when '5'; 'v>' + when '6'; 'v>>' + when '7'; '' + when '8'; '>' + when '9'; '>>' + end + when '8' + case to + when 'A'; 'vvv>' + when '0'; 'vvv' + when '1'; '' + when '4'; '' + when '7'; '<' + when '8'; '' + when '9'; '>' + end + when '9' + case to + when 'A'; 'vvv' + when '0'; ''; 'v' + end + when '^' + case to + when 'A'; '>' + when '^'; '' + when '<'; 'v<' + when 'v'; 'v' + when '>'; 'v>' + end + when '<' + case to + when 'A'; '>>^' + when '^'; '>^' + when '<'; '' + when 'v'; '>' + when '>'; '>>' + end + when 'v' + case to + when 'A'; '^>' + when '^'; '^' + when '<'; '<' + when 'v'; '' + when '>'; '>' + end + when '>' + case to + when 'A'; '^' + when '^'; '<^' + when '<'; '<<' + when 'v'; '<' + when '>'; '' + end + end +end + +def complexity(code, presses_needed) + pp ""For code #{code}, presses needed: #{presses_needed} (len #{presses_needed.length}), complexity: #{code.to_i * presses_needed.length}"" + + code.to_i * presses_needed.length +end + +codes = File.readlines('day-21/input.txt').map(&:chomp) + +total_complexity = 0 + +codes.each do |code| + keypad_robot_position = 'A' + robot_1_presses_needed = '' + code.each_char do |char| + robot_1_presses_needed += numeric_keypad_best_path(keypad_robot_position, char) + robot_1_presses_needed += 'A' + keypad_robot_position = char + end + + prev_robot_presses_needed = robot_1_presses_needed + 2.times do + robot_position = 'A' + next_robot_presses_needed = '' + prev_robot_presses_needed.each_char do |char| + next_robot_presses_needed += arrow_keypad_best_path(robot_position, char) + next_robot_presses_needed += 'A' + robot_position = char + end + prev_robot_presses_needed = next_robot_presses_needed + end + + total_complexity += complexity(code, prev_robot_presses_needed) +end + +p total_complexity",ruby +692,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,"TEST = false +path = 'input.txt' + +codes = File.read(path).split(""\n"") + +module Direction + UP = '^'.freeze + LEFT = '<'.freeze + DOWN = 'v'.freeze + RIGHT = '>'.freeze +end + +numeric_pad = { + '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], + '0' => [3, 1], + 'A' => [3, 2], + 'panic' => [3, 0], +} + +directional_pad = { + Direction::UP => [0, 1], + Direction::LEFT => [1, 0], + Direction::DOWN => [1, 1], + Direction::RIGHT => [1, 2], + 'A' => [0, 2], + 'panic' => [0, 0], +} + +def neighbor(y, x, dir) + case dir + when Direction::UP + [y - 1, x] + when Direction::LEFT + [y, x - 1] + when Direction::DOWN + [y + 1, x] + when Direction::RIGHT + [y, x + 1] + end +end + +def path(start, finish, panic) + return [''] if start == finish + directions_needed = [] + directions_needed << Direction::UP if finish[0] < start[0] + directions_needed << Direction::LEFT if finish[1] < start[1] + directions_needed << Direction::DOWN if finish[0] > start[0] + directions_needed << Direction::RIGHT if finish[1] > start[1] + directions_needed.reduce(Array.new) do |paths, dir| + next_button = neighbor(start[0], start[1], dir) + unless next_button == panic + paths << path(next_button, finish, panic).map { dir + _1 } + end + paths + end.flatten +end + +def translate(keypad, code) + current = 'A' + paths = [''] + code.chars.each do |digit| + new_paths = path(keypad[current], keypad[digit], keypad['panic']) + paths = paths.flat_map do |path| + new_paths.map { path + _1 + 'A' } + end + current = digit + end + paths +end + +res = codes.map do |code| + sequences = [code] + p ""Translating code: #{code}"" + 3.times do |i| + keypad = i.zero? ? numeric_pad : directional_pad + sequences = sequences.flat_map { |sequence| translate(keypad, sequence) } + p ""Step #{i + 1} done"" + end + shortest = sequences.min { |a, b| a.length <=> b.length } + p ""code: #{code} translated"" + code.to_i * shortest.length +end + +puts res.sum",ruby +693,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 = [] + + (0...sequence.length - 1).each do |i| + cur = keys[sequence[i]] + target = keys[sequence[i + 1]] + next_path = [] + dirs = [] + + if cur.nil? || target.nil? + next + end + + (cur[1] - 1).downto(target[1]) do |y| + next_path << [cur[0], y] + dirs << [0, -1] + end + + (cur[0] + 1).upto(target[0]) do |x| + next_path << [x, cur[1]] + dirs << [1, 0] + end + + (cur[0] - 1).downto(target[0]) do |x| + next_path << [x, cur[1]] + dirs << [-1, 0] + end + + (cur[1] + 1).upto(target[1]) do |y| + next_path << [cur[0], y] + dirs << [0, 1] + end + + dirs.reverse! if next_path.include?(keys['']) + + path.concat(dirs.map { |d| DIR_TO_ARROW_MAP[d] } + ['A']) + end + + path.join +end + +lines = File.read('input.txt').split(""\n"") +total_complexity = 0 + +lines.each do |line| + next if line.empty? + + l1 = get_shortest(NUMS, 'A' + line) + l2 = get_shortest(ARROWS, 'A' + l1) + l3 = get_shortest(ARROWS, 'A' + l2) + + total_complexity += line[0..-2].to_i * l3.length unless l3.empty? +end + +puts total_complexity",ruby +694,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +#+---+---+---+ +#| 7 | 8 | 9 | +#+---+---+---+ +#| 4 | 5 | 6 | +#+---+---+---+ +#| 1 | 2 | 3 | +#+---+---+---+ +# | 0 | A | +# +---+---+ +def keypad_move(char, goal) + return [{position: char, move: 'A'}] if char == goal + num = char.to_i(16) + + moves = [] + + if goal == 'A' + if num > 1 && num < 10 + move = 'v' + position = (num - 3).to_s + position = 'A' if char == '3' + position = '0' if char == '2' + moves.push({position: position, move: move}) + end + + if (num % 3 != 0 || num == 0) && char != 'A' + move = '>' + position = (num + 1).to_s + position = 'A' if num == 0 + moves.push({position: position, move: move}) + end + end + + if goal == '0' + if char == 'A' || num % 3 == 0 + move = '<' + position = (num - 1).to_s + position = '0' if char == 'A' + moves.push({position: position, move: move}) + end + if num > 1 && num < 10 + move = 'v' + position = (num - 3).to_s + position = 'A' if char == '3' + position = '0' if char == '2' + moves.push({position: position, move: move}) + end + if num % 3 == 1 && char != 'A' + move = '>' + position = (num + 1).to_s + moves.push({position: position, move: move}) + end + end + + if ['1', '2', '3'].include?(goal) + if num == 0 || char == 'A' + move = '^' + position = '3' if char == 'A' + position = '2' if char == '0' + moves.push({position: position, move: move}) + end + if num > 3 && num < 10 + move = 'v' + position = (num - 3).to_s + moves.push({position: position, move: move}) + end + end + + if ['4', '5', '6'].include?(goal) + if char == 'A' || num < 4 + move = '^' + position = (num + 3).to_s + position = '3' if char == 'A' + position = '2' if char == '0' + moves.push({position: position, move: move}) + end + if num > 6 && num < 10 + move = 'v' + position = (num - 3).to_s + moves.push({position: position, move: move}) + end + end + + if ['7', '8', '9'].include?(goal) + if num < 7 || char == 'A' + move = '^' + position = (num + 3).to_s + position = '3' if char == 'A' + position = '2' if char == '0' + moves.push({position: position, move: move}) + end + end + + if ['7', '4', '1'].include?(goal) + if num != 0 && num != 7 && num != 4 && num != 1 + move = '<' + position = (num -1).to_s + position = '0' if char == 'A' + moves.push({position: position, move: move}) + end + end + + if ['8', '5', '2'].include?(goal) + if (num != 0 && num % 3 == 0) || char == 'A' + move = '<' + position = (num - 1).to_s + position = '0' if char == 'A' + moves.push({position: position, move: move}) + end + if num % 3 == 1 && num != 10 + move = '>' + position = (num + 1).to_s + moves.push({position: position, move: move}) + end + end + + if ['9', '6', '3'].include?(goal) + if num % 3 != 0 && num != 10 + move = '>' + position = (num + 1).to_s + position = 'A' if char == '0' + moves.push({position: position, move: move}) + end + end + + return moves +end + +# +---+---+ +# | ^ | A | +#+---+---+---+ +#| < | v | > | +#+---+---+---+ + +def robot_move(char, goal) + return [{position: char, move: 'A'}] if char == goal + + moves = [] + + if goal == '>' + if char == 'v' + moves.push({position: '>', move: '>'}) + end + if char == '<' + moves.push({position: 'v', move: '>'}) + end + if char == '^' + moves.push({position: 'A', move: '>'}) + moves.push({position: 'v', move: 'v'}) + end + if char == 'A' + moves.push({position: '>', move: 'v'}) + end + end + + if goal == '<' + if char == 'v' + moves.push({position: '<', move: '<'}) + end + if char == '>' + moves.push({position: 'v', move: '<'}) + end + if char == '^' + moves.push({position: 'v', move: 'v'}) + end + if char == 'A' + moves.push({position: '>', move: 'v'}) + moves.push({position: '^', move: '<'}) + end + end + + if goal == 'v' + if char == '<' + moves.push({position: 'v', move: '>'}) + end + if char == '>' + moves.push({position: 'v', move: '<'}) + end + if char == '^' + moves.push({position: 'v', move: 'v'}) + end + if char == 'A' + moves.push({position: '>', move: 'v'}) + moves.push({position: '^', move: '<'}) + end + end + + if goal == '^' + if char == '<' + moves.push({position: 'v', move: '>'}) + end + if char == '>' + moves.push({position: 'v', move: '<'}) + moves.push({position: 'A', move: '^'}) + end + if char == 'v' + moves.push({position: '^', move: '^'}) + end + if char == 'A' + moves.push({position: '^', move: '<'}) + end + end + + if goal == 'A' + if char == '<' + moves.push({position: 'v', move: '>'}) + end + if char == '>' + moves.push({position: 'A', move: '^'}) + end + if char == '^' + moves.push({position: 'A', move: '>'}) + end + if char == 'v' + moves.push({position: '^', move: '^'}) + moves.push({position: '>', move: '>'}) + end + end + + return moves + +end + +file_path = File.expand_path('input.txt', __dir__) +input = File.read(file_path).split(""\n"").map { |line| line.chars } + + +codes_numeric = input.map { |line| line.take(3).join.to_i } + + + +robot1 = [] +# robot 1 +input.each do |line| + current = 'A' + candidates = [ last: current, size: 0, moves:[]] + line.each do |char| + moves_left = true + + final_candidates = [] + while moves_left + moves_left = false + new_candidates = [] + + candidates.each do |candidate| + last = candidate[:last] + + if last == char.to_s + candidate[:size] += 1 + candidate[:moves].push('A') + final_candidates.push(candidate) + next + end + moves = keypad_move(last, char.to_s) + moves.each do |move| + new_moves = candidate[:moves].dup + new_moves.push(move[:move]) + new_size = candidate[:size] + 1 + new_candidates.push({ last: move[:position], moves: new_moves, size: new_size }) + moves_left = true + end + + end + candidates = new_candidates + end + + candidates = final_candidates + end + + min_size = candidates.map { |candidate| candidate[:size] }.min + robot1.push(candidates.select{ |candidate| candidate[:size] == min_size }.map { |candidate| candidate[:moves] }) +end + +#robot1.first.each { |robo| puts robo.join } + +#exit +robot2 = [] + +robot1.each do |robot_possible| + robot_possible_2 = [] + robot_possible.each do |robot_moves| + current = 'A' + candidates = [ last: current, size: 0, moves:[]] + robot_moves.each do |char| + moves_left = true + + final_candidates = [] + while moves_left + + moves_left = false + new_candidates = [] + + candidates.each do |candidate| + last = candidate[:last] + + if last == char + candidate[:size] += 1 + candidate[:moves].push('A') + final_candidates.push(candidate) + next + end + moves = robot_move(last, char) + moves.each do |move| + new_moves = candidate[:moves].dup + new_moves.push(move[:move]) + new_size = candidate[:size] + 1 + new_candidates.push({ last: move[:position], moves: new_moves, size: new_size }) + moves_left = true + end + + end + candidates = new_candidates + + end + + candidates = final_candidates + + end + + min_size = candidates.map { |candidate| candidate[:size] }.min + + robot_possible_2.push(candidates.select{ |candidate| candidate[:size] == min_size }.map { |candidate| candidate[:moves] }) + + end + + robot_shortest = [] + robot_possible_2.each do |robos| + robos.each do |robo| + robot_shortest.push(robo) + end + end + + min_robo = robot_shortest.map { |robo| robo.size }.min + robot2.push(robot_shortest.select { |robo| robo.size == min_robo }) + #robot2.push(robot_possible_2) +end + +sum = 0 +robot2.each_with_index do |robo, i| + sum += robo.first.nil? ? 0 : robo.first.size * codes_numeric[i] +end + +puts sum +sum = 0 +# robot 3 +robot3 = [] + +robot2.each do |robot_possible| + robot_possible_2 = [] + robot_possible.each do |robot_moves| + current = 'A' + candidates = [ last: current, size: 0, moves:[]] + robot_moves.each do |char| + moves_left = true + + final_candidates = [] + while moves_left + + moves_left = false + new_candidates = [] + + candidates.each do |candidate| + last = candidate[:last] + + if last == char + candidate[:size] += 1 + candidate[:moves].push('A') + final_candidates.push(candidate) + next + end + moves = robot_move(last, char) + moves.each do |move| + new_moves = candidate[:moves].dup + new_moves.push(move[:move]) + new_size = candidate[:size] + 1 + new_candidates.push({ last: move[:position], moves: new_moves, size: new_size }) + moves_left = true + end + + end + candidates = new_candidates + + end + + candidates = final_candidates + + end + + min_size = candidates.map { |candidate| candidate[:size] }.min + + robot_possible_2.push(candidates.select{ |candidate| candidate[:size] == min_size }.map { |candidate| candidate[:moves] }) + + end + + robot_shortest = [] + robot_possible_2.each do |robos| + robos.each do |robo| + robot_shortest.push(robo) + end + end + + min_robo = robot_shortest.map { |robo| robo.size }.min + robot3.push(robot_shortest.select { |robo| robo.size == min_robo }) + #robot2.push(robot_possible_2) +end + +sum = 0 +robot3.each_with_index do |robo, i| + sum += robo.first.nil? ? 0 : robo.first.size * codes_numeric[i] +end + +puts sum",ruby +695,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,"require 'set' + +input = File.read('21.input').split(""\n"").map(&:strip) + +# problem 1 + +def numpad_coord(c) + return [0, 0] if c == '7' + return [1, 0] if c == '8' + return [2, 0] if c == '9' + return [0, 1] if c == '4' + return [1, 1] if c == '5' + return [2, 1] if c == '6' + return [0, 2] if c == '1' + return [1, 2] if c == '2' + return [2, 2] if c == '3' + return [1, 3] if c == '0' + [2, 3] +end + +def keypad_coord(c) + return [1, 0] if c == '^' + return [2, 0] if c == 'A' + return [0, 1] if c == '<' + return [1, 1] if c == 'v' + [2, 1] +end + +@possible_paths_memo = {} + +def calc_possible_paths(a, b, depth) + @possible_paths_memo[[a, b, depth].flatten.join(',')] ||= begin + return [['A']] if a == b + + bad_spot = depth == 0 ? [0, 3] : [0, 0] + return [] if a == bad_spot + + a_x, a_y = a + b_x, b_y = b + + paths = [] + + if a_x < b_x + new_path = Array.new(b_x - a_x, '>') + calc_possible_paths([b_x, a_y], b, depth).each do |subpath| + paths.push(new_path + subpath) + end + end + if a_x > b_x + new_path = Array.new(a_x - b_x, '<') + calc_possible_paths([b_x, a_y], b, depth).each do |subpath| + paths.push(new_path + subpath) + end + end + if a_y < b_y + new_path = Array.new(b_y - a_y, 'v') + calc_possible_paths([a_x, b_y], b, depth).each do |subpath| + paths.push(new_path + subpath) + end + end + if a_y > b_y + new_path = Array.new(a_y - b_y, '^') + calc_possible_paths([a_x, b_y], b, depth).each do |subpath| + paths.push(new_path + subpath) + end + end + + paths + end +end + +def moving_cost(goal, depth, max_depth, robots_pos) + from = robots_pos[depth] + + min_path_presses, new_robots_pos = @moving_cost_memo[[from, goal, depth, robots_pos[depth]].flatten] ||= begin + x0, y0 = from + x1, y1 = goal + + possible_paths = calc_possible_paths(from, goal, depth == 0 ? 0 : 1) + + robots_pos[depth] = goal + + if depth == max_depth + [possible_paths.map { |p| p.size }.min, goal] + else + min_path_presses = nil + + possible_paths.each do |possible_path| + min_presses = 0 + + possible_path.each do |c| + new_goal = keypad_coord(c) + + presses_nr = moving_cost(new_goal, depth + 1, max_depth, robots_pos) + min_presses += presses_nr + end + + min_path_presses = min_presses if min_path_presses.nil? || min_path_presses > min_presses + end + + [min_path_presses, goal] + end + end + + robots_pos[depth] = new_robots_pos + min_path_presses +end + +robots_pos = [[2, 3], [2, 0], [2, 0]] +@moving_cost_memo = {} +total_complexity = 0 + +input.each do |code| + total_presses_nr = 0 + + code.chars.each do |c| + goal = numpad_coord(c) + + presses_nr = moving_cost(goal, 0, 2, robots_pos) + total_presses_nr += presses_nr + end + + complexity = total_presses_nr * code.slice(0, code.size - 1).to_i + total_complexity += complexity +end + +puts total_complexity + +# problem 2 + +robots_pos = [[2, 3], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0]] +@moving_cost_memo = {} +total_complexity = 0 + +input.each do |code| + total_presses_nr = 0 + + code.chars.each do |c| + goal = numpad_coord(c) + + presses_nr = moving_cost(goal, 0, 25, robots_pos) + total_presses_nr += presses_nr + end + + complexity = total_presses_nr * code.slice(0, code.size - 1).to_i + total_complexity += complexity +end + +puts total_complexity",ruby +696,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,"# I struggled with attempts at Day 21 Part 2 implementations involving precomputation and/or memoization of +# intermediate results. +# +# The ""light bulb"" moment happened for me when I realized that this could be implemented like Day 11 Part 2! +# The order of each relative pair of moves doesn't matter. We just need to keep track of, for each generation, +# how many times we're moving from each position to each other position. Each of those ""moves"" can be used to +# directly compute the set of moves for the next generation -- same as for each individual ""replicating stone"" +# from Day 11. +# +# This solution returns immediately. Much better than the projected 24+ hour runtimes of my other attempts! + +def numeric_keypad_best_path(from, to) + # The orderings of the moves here matter -- some result in cheaper solutions than others. I came up with the + # correct orderings by (1) realizing that the orderings matter by comparing my original (too expensive) + # solution from Part 1 to the problem statement's solution, and seeing that the problem's statement's solution + # had a shorter set of moves; (2) coming up with a couple of simple heuristics for correct orderings, e.g. + # don't change direction more than necessary (e.g. no '>^>' instead of '>>^'), and always move left as much + # as possible first; (3) guess-and-check by tweaking a few individual orderings and seeing if they produced + # a lower result. + case from + when 'A' + case to + when 'A'; '' + when '0'; '<' + when '1'; '^<<' + when '2'; '<^' + when '3'; '^' + when '4'; '^^<<' + when '5'; '<^^' + when '6'; '^^' + when '7'; '^^^<<' + when '8'; '<^^^' + when '9'; '^^^' + end + when '0' + case to + when 'A'; '>' + when '0'; '' + when '1'; '^<' + when '2'; '^' + when '3'; '^>' + when '4'; '^^<' + when '5'; '^^' + when '6'; '^^>' + when '7'; '^^^<' + when '8'; '^^^' + when '9'; '^^^>' + end + when '1' + case to + when 'A'; '>>v' + when '0'; '>v' + when '1'; '' + when '2'; '>' + when '3'; '>>' + when '4'; '^' + when '5'; '^>' + when '6'; '^>>' + when '7'; '^^' + when '8'; '^^>' + when '9'; '^^>>' + end + when '2' + case to + when 'A'; 'v>' + when '0'; 'v' + when '2'; '' + when '1'; 'v' + when '3'; '>' + when '4'; '<^' + when '5'; '^' + when '6'; '^>' + when '7'; '<^^' + when '8'; '^^' + when '9'; '^^>' + end + when '3' + case to + when 'A'; 'v' + when '0'; '>vv' + when '0'; '>vv' + when '1'; 'v' + when '2'; 'v>' + when '3'; 'v>>' + when '4'; '' + when '5'; '>' + when '6'; '>>' + when '7'; '^' + when '8'; '^>' + when '9'; '^>>' + end + when '5' + case to + when 'A'; 'vv>' + when '0'; 'vv' + when '1'; '' + when '4'; '<' + when '5'; '' + when '6'; '>' + when '7'; '<^' + when '8'; '^' + when '9'; '^>' + end + when '6' + case to + when 'A'; 'vv' + when '0'; '>vvv' + when '0'; '>vvv' + when '1'; 'vv' + when '2'; 'vv>' + when '3'; 'vv>>' + when '4'; 'v' + when '5'; 'v>' + when '6'; 'v>>' + when '7'; '' + when '8'; '>' + when '9'; '>>' + end + when '8' + case to + when 'A'; 'vvv>' + when '0'; 'vvv' + when '1'; '' + when '4'; '' + when '7'; '<' + when '8'; '' + when '9'; '>' + end + when '9' + case to + when 'A'; 'vvv' + when '0'; ''; 'v' + end + when '^' + case to + when 'A'; '>' + when '^'; '' + when '<'; 'v<' + when 'v'; 'v' + when '>'; 'v>' + end + when '<' + case to + when 'A'; '>>^' + when '^'; '>^' + when '<'; '' + when 'v'; '>' + when '>'; '>>' + end + when 'v' + case to + when 'A'; '^>' + when '^'; '^' + when '<'; '<' + when 'v'; '' + when '>'; '>' + end + when '>' + case to + when 'A'; '^' + when '^'; '<^' + when '<'; '<<' + when 'v'; '<' + when '>'; '' + end + end +end + +# Create a hashmap of each move (pair of ""from"" / origin, and ""to"" / destination), to the set of moves +# needed by the controlling robot to produce that movement in the robot being controlled. +def generate_key_pairs + key_pairs = {} + ['<', 'v', '>', '^', 'A'].repeated_permutation(2).each do |from, to| + # Each moves starts at position 'A'; and needs another 'A' at the end to ""submit"" the move. + key_pairs[[from, to]] = ('A' << arrow_keypad_best_path(from, to) << 'A').chars.each_cons(2).to_a + end + key_pairs +end + +def complexity(code, presses_needed) + code.to_i * (presses_needed.values.sum - 1) +end + +codes = File.readlines('day-21/input.txt').map(&:chomp) +key_pairs = generate_key_pairs +total_complexity = 0 + +codes.each do |code| + keypad_robot_position = 'A' + robot_1_presses_needed = '' + code.each_char do |char| + robot_1_presses_needed << numeric_keypad_best_path(keypad_robot_position, char) + robot_1_presses_needed << 'A' + keypad_robot_position = char + end + + prev_robot_presses_needed = Hash.new(0) + ('A' << robot_1_presses_needed << 'A').chars.each_cons(2) do |from, to| + prev_robot_presses_needed[[from, to]] += 1 + end + + 25.times do + next_robot_presses_needed = Hash.new(0) + + prev_robot_presses_needed.each do |pair, count| + key_pairs[pair].each do |to| + next_robot_presses_needed[to] += count + end + end + + prev_robot_presses_needed = next_robot_presses_needed + end + + total_complexity += complexity(code, prev_robot_presses_needed) +end + +p total_complexity",ruby +697,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 ruby +# frozen_string_literal: true +require 'json' + +#+---+---+---+ +#| 7 | 8 | 9 | +#+---+---+---+ +#| 4 | 5 | 6 | +#+---+---+---+ +#| 1 | 2 | 3 | +#+---+---+---+ +# | 0 | A | +# +---+---+ +$memo_keypad = { + 'A': {'A': 'A', '0': 'A', '0': 'A', '1': '^A', '4': '^^A', '7': '^^^A'}, + '1': {'A': '>>vA', '0': '>vA', '1': 'A', '2': '>A', '3': '>>A', '4': '^A', '5': '^>A', '6': '^>>A', '7': '^^A', '8': '^^>A', '9': '^^>>A'}, + '2': {'A': 'v>A', '0': 'vA', '1': 'A', '4': '<^A', '5': '^A', '6': '^>A', '7': '<^^A', '8': '^^A', '9': '^^>A'}, + '3': {'A': 'vA', '0': '>vvA', '0': '>vvA', '1': 'vA', '2': 'v>A', '3': 'v>>A', '4': 'A', '5': '>A', '6': '>>A', '7': '^A', '8': '^>A', '9': '^>>A'}, + '5': {'A': 'vv>A', '0': 'vvA', '1': 'A', '4': 'A', '7': '<^A', '8': '^A', '9': '^>A'}, + '6': {'A': 'vvA', '0': '>vvvA', '0': '>vvvA', '1': 'vvA', '2': 'vv>A', '3': 'vv>>A', '4': 'vA', '5': 'v>A', '6': 'v>>A', '7': 'A', '8': '>A', '9': '>>A'}, + '8': {'A': 'vvv>A', '0': 'vvvA', '1': 'A', '4': 'A', '7': 'A'}, + '9': {'A': 'vvvA', '0': ' | +#+---+---+---+ +#$memo_robot = { +# 'A'.chars => {'A'.chars => 'A'.chars, '<'.chars => 'v< ''.chars => 'vA'.chars, 'v'.chars => ' {'A'.chars => '>>^A'.chars, '<'.chars => 'A'.chars, '^'.chars => '>^A'.chars, '>'.chars => '>>A'.chars, 'v'.chars => '>A'.chars}, +# '^'.chars => {'A'.chars => '>A'.chars, '<'.chars => 'v 'A'.chars, '>'.chars => 'v>A'.chars, 'v'.chars => 'vA'.chars}, +# '>'.chars => {'A'.chars => '^A'.chars, '<'.chars => '< '<^A'.chars, '>'.chars => 'A'.chars, 'v'.chars => ' {'A'.chars => '^>A'.chars, '<'.chars => ' '^A'.chars, '>'.chars => '>A'.chars, 'v'.chars => 'A'.chars} +#} + +#>^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A + +$memo_robot = { + 'A' => {'A' => 'A', '<' => 'v< '' => 'vA', 'v' => ' {'A' => '>>^A', '<' => 'A', '^' => '>^A', '>' => '>>A', 'v' => '>A'}, + '^' => {'A' => '>A', '<' => 'v 'A', '>' => 'v>A', 'v' => 'vA'}, + '>' => {'A' => '^A', '<' => '< '<^A', '>' => 'A', 'v' => ' {'A' => '^>A', '<' => ' '^A', '>' => '>A', 'v' => 'A'} +} + +def robot_move(char, goal) + return $memo_robot[char][goal] +end + +file_path = File.expand_path('input.txt', __dir__) +input = File.read(file_path).split(""\n"").map { |line| line.chars } + +codes_numeric = input.map { |line| line.take(3).join.to_i } + +robots_cnt = 25 +codes_cnt = input.size + +sum = 0 +input.each_with_index do |line, l| + + current_line = line + + 2.times do |i| + new_line = [] + prev_char = ""A"" + (0..current_line.size-1).each do |j| + char = current_line[j] + if i == 0 + new_line.push(*keypad_move(prev_char, char).chars) + else + new_line.push(*robot_move(prev_char, char)) + end + prev_char = char + end + + current_line = new_line + end + + current_tally = current_line.tally + + + robots_cnt.times.each do |i| + new_tally = {} + + current_tally.each do |key, value| + chars = key.chars + + prev_char = ""A"" + chars.each_with_index do |char, j| + new_move = robot_move(prev_char, char) + new_tally[new_move] = 0 if new_tally[new_move].nil? + new_tally[new_move] += value + prev_char = char + end + end + + + current_tally = new_tally + end + + sum += current_tally.values.sum * codes_numeric[l] +end + +puts sum",ruby +698,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +codes = File.read(path).split(""\n"") + +module Direction + UP = '^'.freeze + LEFT = '<'.freeze + DOWN = 'v'.freeze + RIGHT = '>'.freeze +end + +NUMBER_OF_DIRECTIONAL_PADS = TEST ? 2 : 25 + +numeric_pad = { + '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], + '0' => [3, 1], + 'A' => [3, 2], + 'panic' => [3, 0], +} + +directional_pad = { + Direction::UP => [0, 1], + Direction::LEFT => [1, 0], + Direction::DOWN => [1, 1], + Direction::RIGHT => [1, 2], + 'A' => [0, 2], + 'panic' => [0, 0], +} + +def neighbor(y, x, dir) + case dir + when Direction::UP + [y - 1, x] + when Direction::LEFT + [y, x - 1] + when Direction::DOWN + [y + 1, x] + when Direction::RIGHT + [y, x + 1] + end +end + +def path(start, finish, panic) + return [''] if start == finish + directions_needed = [] + directions_needed << Direction::UP if finish[0] < start[0] + directions_needed << Direction::LEFT if finish[1] < start[1] + directions_needed << Direction::DOWN if finish[0] > start[0] + directions_needed << Direction::RIGHT if finish[1] > start[1] + directions_needed.reduce(Array.new) do |paths, dir| + next_button = neighbor(start[0], start[1], dir) + unless next_button == panic + paths << path(next_button, finish, panic).map { dir + _1 } + end + paths + end.flatten +end + +@memo = Array.new(NUMBER_OF_DIRECTIONAL_PADS + 1) { Array.new(14) { nil } } + +def memoized(pad_number, move_number, &compute_bloc) + value = @memo[pad_number][move_number] || yield + @memo[pad_number][move_number] = value + value +end + +def price(from, to, pad_number) + return 1 if pad_number.zero? + case [from, to] + when ['A', Direction::UP], [Direction::RIGHT, Direction::DOWN], [Direction::DOWN, Direction::LEFT] + memoized(pad_number, 0) { price('A', Direction::LEFT, pad_number - 1) + price(Direction::LEFT, 'A', pad_number - 1) } + when [Direction::UP, 'A'], [Direction::DOWN, Direction::RIGHT], [Direction::LEFT, Direction::DOWN] + memoized(pad_number, 1) { price('A', Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, 'A', pad_number - 1) } + when [Direction::RIGHT, Direction::LEFT] + memoized(pad_number, 2) { price('A', Direction::LEFT, pad_number - 1) + price(Direction::LEFT, Direction::LEFT, pad_number - 1) + price(Direction::LEFT, 'A', pad_number - 1) } + when [Direction::LEFT, Direction::RIGHT] + memoized(pad_number, 3) { price('A', Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, 'A', pad_number - 1) } + when [Direction::UP, Direction::DOWN], ['A', Direction::RIGHT] + memoized(pad_number, 4) { price('A', Direction::DOWN, pad_number - 1) + price(Direction::DOWN, 'A', pad_number - 1) } + when [Direction::DOWN, Direction::UP], [Direction::RIGHT, 'A'] + memoized(pad_number, 5) { price('A', Direction::UP, pad_number - 1) + price(Direction::UP, 'A', pad_number - 1) } + when [Direction::UP, Direction::LEFT] + memoized(pad_number, 6) { price('A', Direction::DOWN, pad_number - 1) + price(Direction::DOWN, Direction::LEFT, pad_number - 1) + price(Direction::LEFT, 'A', pad_number - 1) } + when [Direction::LEFT, Direction::UP] + memoized(pad_number, 7) { price('A', Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, Direction::UP, pad_number - 1) + price(Direction::UP, 'A', pad_number - 1) } + when ['A', Direction::DOWN] + memoized(pad_number, 8) do + [ + price('A', Direction::DOWN, pad_number - 1) + price(Direction::DOWN, Direction::LEFT, pad_number - 1) + price(Direction::LEFT, 'A', pad_number - 1), + price('A', Direction::LEFT, pad_number - 1) + price(Direction::LEFT, Direction::DOWN, pad_number - 1) + price(Direction::DOWN, 'A', pad_number - 1) + ].min + end + when [Direction::DOWN, 'A'] + memoized(pad_number, 9) do + [ + price('A', Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, Direction::UP, pad_number - 1) + price(Direction::UP, 'A', pad_number - 1), + price('A', Direction::UP, pad_number - 1) + price(Direction::UP, Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, 'A', pad_number - 1) + ].min + end + when [Direction::UP, Direction::RIGHT] + memoized(pad_number, 10) do + [ + price('A', Direction::DOWN, pad_number - 1) + price(Direction::DOWN, Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, 'A', pad_number - 1), + price('A', Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, Direction::DOWN, pad_number - 1) + price(Direction::DOWN, 'A', pad_number - 1) + ].min + end + when [Direction::RIGHT, Direction::UP] + memoized(pad_number, 11) do + [ + price('A', Direction::LEFT, pad_number - 1) + price(Direction::LEFT, Direction::UP, pad_number - 1) + price(Direction::UP, 'A', pad_number - 1), + price('A', Direction::UP, pad_number - 1) + price(Direction::UP, Direction::LEFT, pad_number - 1) + price(Direction::LEFT, 'A', pad_number - 1) + ].min + end + when ['A', Direction::LEFT] + memoized(pad_number, 12) do + [ + price('A', Direction::DOWN, pad_number - 1) + price(Direction::DOWN, Direction::LEFT, pad_number - 1) + price(Direction::LEFT, Direction::LEFT, pad_number - 1) + price(Direction::LEFT, 'A', pad_number - 1), + price('A', Direction::LEFT, pad_number - 1) + price(Direction::LEFT, Direction::DOWN, pad_number - 1) + price(Direction::DOWN, Direction::LEFT, pad_number - 1) + price(Direction::LEFT, 'A', pad_number - 1) + ].min + end + when [Direction::LEFT, 'A'] + memoized(pad_number, 13) do + [ + price('A', Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, Direction::UP, pad_number - 1) + price(Direction::UP, 'A', pad_number - 1), + price('A', Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, Direction::UP, pad_number - 1) + price(Direction::UP, Direction::RIGHT, pad_number - 1) + price(Direction::RIGHT, 'A', pad_number - 1) + ].min + end + else + throw Error.new(""Unexpected from: #{from} and to: #{to}"") unless from == to + 1 + end +end + +def price_code(keypad, code) + current = 'A' + paths = [''] + code.chars.each do |digit| + new_paths = path(keypad[current], keypad[digit], keypad['panic']) + paths = paths.flat_map do |path| + new_paths.map { path + _1 + 'A' } + end + current = digit + end + paths.map do |path| + buttons = path.chars + (0...buttons.count).reduce(0) do |sum, i| + from = i.zero? ? 'A' : buttons[i - 1] + to = buttons[i] + sum + price(from, to, NUMBER_OF_DIRECTIONAL_PADS) + end + end.min * code.to_i +end + +puts ""Total = #{codes.map{price_code(numeric_pad, _1)}.sum}""",ruby +699,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,"require 'set' + +day = ""21"" +file_name = ""12-#{day}-24/sampleIn.txt"" +file_name = ""12-#{day}-24/input.txt"" + +data = File.read(file_name).split(""\n"").map { |i| i.rstrip } + +def getAllShortest(start, goal, memo, locations) + + if memo[[start, goal, locations]] + return memo[[start, goal, locations]] + end + + shortest = [] + + startY = start[0] + startX = start[1] + goalY = goal[0] + goalX = goal[1] + + if startY == goalY + if startX > goalX + shortest.append(""<"" * (startX - goalX)) + elsif goalX > startX + shortest.append("">"" * (goalX - startX)) + else + shortest.append("""") + end + elsif startY > goalY + if startX > goalX + op1 = ""^"" * (startY - goalY) + ""<"" * (startX - goalX) + op2 = ""<"" * (startX - goalX) + ""^"" * (startY - goalY) + if not (goalX == 0 and startY == 3 and locations == 11) + shortest.append(op2) + end + shortest.append(op1) + elsif goalX > startX + op1 = ""^"" * (startY - goalY) + "">"" * (goalX - startX) + op2 = "">"" * (goalX - startX) + ""^"" * (startY - goalY) + if not (startX == 0 and goalY == 0 and locations == 5) + shortest.append(op1) + end + shortest.append(op2) + else + shortest.append(""^"" * (startY - goalY)) + end + else + if startX > goalX + op1 = ""v"" * (goalY - startY) + ""<"" * (startX - goalX) + op2 = ""<"" * (startX - goalX) + ""v"" * (goalY - startY) + if not (goalX == 0 and startY == 0 and locations == 5) + shortest.append(op2) + end + shortest.append(op1) + elsif goalX > startX + op1 = ""v"" * (goalY - startY) + "">"" * (goalX - startX) + op2 = "">"" * (goalX - startX) + ""v"" * (goalY - startY) + if not (startX == 0 and goalY == 3 and locations == 11) + shortest.append(op1) + end + shortest.append(op2) + else + shortest.append(""v"" * (goalY - startY)) + end + end + + memo[[start, goal, locations]] = shortest.map { |i| i + ""A""} + return shortest.map { |i| i + ""A""} + +end + +def getBestPaths(toTry, locMap, locs, memo1) + nextBP = [] + + for path in toTry + + bestPaths = [""""] + path = ""A"" + path + for c in 0...(path.length - 1) + char = path[c] + if /\d/.match? char + char = char.to_i + end + nextChar = path[c + 1] + if /\d/.match? nextChar + nextChar = nextChar.to_i + end + + paths = getAllShortest(locMap[char], locMap[nextChar], memo1, locs.size) + + newPaths = [] + for b in bestPaths + for p in paths + newPaths.append(b + p) + end + end + bestPaths = newPaths + end + nextBP += bestPaths + end + + minLen = nextBP.min { |i, j| i.length <=> j.length }.length + nextBP.delete_if { |i| i.length != minLen } + return nextBP +end + +def decoder(start, path, locs) + message = """" + for i in path.split("""") + if i == ""<"" + start[1] -= 1 + end + if i == "">"" + start[1] += 1 + end + if i == ""v"" + start[0] += 1 + end + if i == ""^"" + start[0] -= 1 + end + if i == ""A"" + message += locs[start].to_s + end + end + return message +end + + +def part1(input) + keypad = { + [0, 0] => 7, + [0, 1] => 8, + [0, 2] => 9, + [1, 0] => 4, + [1, 1] => 5, + [1, 2] => 6, + [2, 0] => 1, + [2, 1] => 2, + [2, 2] => 3, + [3, 1] => 0, + [3, 2] => ""A"", + } + + reverseKeypad = {} + for i in keypad.keys + reverseKeypad[keypad[i]] = i + end + + keypadSet = keypad.keys.to_set + + directions = { + [0, 1] => ""^"", + [0, 2] => ""A"", + [1, 0] => ""<"", + [1, 1] => ""v"", + [1, 2] => "">"", + } + + reverseDirections = {} + + for i in directions.keys + reverseDirections[directions[i]] = i + end + + directionSet = directions.keys.to_set + + + memo1 = {} + + total = 0 + + for line in input + num = line.to_i + + toTry = [line] + + toTry = getBestPaths(toTry, reverseKeypad, keypadSet, memo1) + + + toTry = getBestPaths(toTry, reverseDirections, directionSet, memo1) + + toTry = getBestPaths(toTry, reverseDirections, directionSet, memo1) + + total += toTry[0].length * num + + end + + return total +end + +def getAShortestPath(start, goal, depth, memo, m1, reverseDirections) + if memo[[start, goal, depth]] + return memo[[start, goal, depth]] + end + if depth == 1 + possible = getAllShortest(start, goal, m1, 5) + memo[[start, goal, depth]] = possible[0].length + return possible[0].length + end + + options = getAllShortest(start, goal, m1, 5) + bestLen = Float::INFINITY + for path in options + thisLen = 0 + path = ""A"" + path + for c in 0...(path.length - 1) + char = path[c] + if /\d/.match? char + char = char.to_i + end + nextChar = path[c + 1] + if /\d/.match? nextChar + nextChar = nextChar.to_i + end + thisLen += getAShortestPath(reverseDirections[char], reverseDirections[nextChar], depth - 1, memo, m1, reverseDirections) + end + + bestLen = [thisLen, bestLen].min + end + + memo[[start, goal, depth]] = bestLen + return bestLen +end + +def part2(input) + keypad = { + [0, 0] => 7, + [0, 1] => 8, + [0, 2] => 9, + [1, 0] => 4, + [1, 1] => 5, + [1, 2] => 6, + [2, 0] => 1, + [2, 1] => 2, + [2, 2] => 3, + [3, 1] => 0, + [3, 2] => ""A"", + } + + reverseKeypad = {} + for i in keypad.keys + reverseKeypad[keypad[i]] = i + end + + keypadSet = keypad.keys.to_set + + directions = { + [0, 1] => ""^"", + [0, 2] => ""A"", + [1, 0] => ""<"", + [1, 1] => ""v"", + [1, 2] => "">"", + } + + reverseDirections = {} + + for i in directions.keys + reverseDirections[directions[i]] = i + end + + + memo1 = {} + + recurseMemo = {} + + total = 0 + + depth = 25 + + for line in input + num = line.to_i + + toTry = [line] + + firstBest = getBestPaths(toTry, reverseKeypad, keypadSet, memo1) + + bestLen = Float::INFINITY + for path in firstBest + thisLen = 0 + path = ""A"" + path + for c in 0...(path.length - 1) + char = path[c] + if /\d/.match? char + char = char.to_i + end + nextChar = path[c + 1] + if /\d/.match? nextChar + nextChar = nextChar.to_i + end + thisLen += getAShortestPath(reverseDirections[char], reverseDirections[nextChar], depth, recurseMemo, memo1, reverseDirections) + end + bestLen = [thisLen, bestLen].min + end + + total += bestLen * num + + end + + return total +end + +puts part1(data) +puts part2(data)",ruby +700,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,"#! /usr/bin/env ruby + +class RandomGenerator + def initialize(seed) + @seed = seed + end + + def next + a = @seed * 64 + mix(a) + prune! + + b = @seed / 32 + mix(b) + prune! + + c = @seed * 2048 + mix(c) + prune! + + @seed + end + + def mix(a) + @seed = @seed ^ a + end + + def prune! + @seed = @seed % 16_777_216 + end +end + +#--------------------------------------------------------------------------------- +input_file = ""input.txt"" +seeds = File.readlines(input_file).map(&:strip).reject(&:empty?).map(&:to_i) + +sum_of_secrets = 0 +seeds.each do |seed| + puts ""Seed: #{seed}"" + random_generator = RandomGenerator.new(seed) + 1999.times { random_generator.next } + secret_number = random_generator.next + puts ""#{seed}: 2000th random number: #{secret_number}"" + sum_of_secrets += secret_number +end + +puts ""Sum of secrets: #{sum_of_secrets}""",ruby +701,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,"#!/usr/bin/env ruby + +# Login to https://adventofcode.com/2024/day/22/input to download 'input.txt'. + +# lines = readlines +# lines = File.readlines('sample1.txt', chomp: true) # Answer: 37327623 (in 56 ms) +lines = File.readlines('input.txt', chomp: true) # Answer: 17612566393 (in 792 ms) + +initial_numbers = lines.map(&:to_i) + +puts 'Initial Numbers' +puts '---------------' +puts initial_numbers +puts + +def next_secret_number(secret_number) + secret_number = mix_and_prune(secret_number, secret_number << 6) # Multiply by 64, or shift left by 6 bits + secret_number = mix_and_prune(secret_number, secret_number >> 5) # Divide by 32, or shift right by 5 bits + secret_number = mix_and_prune(secret_number, secret_number << 11) # Multiply by 2048, or shift left by 11 bits +end + +def mix_and_prune(n, mixin) + # mix: XOR together + # prune: modulo 16777216 (keep the lowest 24 bits, or AND with 16777215 (all 1's)) + (n ^ mixin) & 16777215 +end + +next_2000_secret_numbers = initial_numbers.map do |secret_number| + 2000.times.reduce(secret_number) { |acc, _| next_secret_number(acc) } +end + +puts '2000th Numbers' +puts '--------------' +puts next_2000_secret_numbers +puts + +answer = next_2000_secret_numbers.sum + +puts ""Answer: #{answer}""",ruby +702,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,"input_array = ARGV + +def next_secret_number(secret_number) + secret_number = ((secret_number * 64) ^ secret_number) % 16777216 + secret_number = ((secret_number / 32).floor ^ secret_number) % 16777216 + secret_number = ((secret_number * 2048) ^ secret_number) % 16777216 +end + +def process(file_name, debug=false) + secret_numbers = [] + File.foreach(ARGV[0]).with_index do |line, index| + row = line.strip.to_i + secret_numbers.push(row) + end + + secret_total = 0 + secret_numbers.each do |secret_number| + initial_secret_number = secret_number + 2000.times do + secret_number = next_secret_number(secret_number) + end + puts ""#{initial_secret_number}: #{secret_number}"" if debug + secret_total += secret_number + end + + puts ""Secret total: #{secret_total}"" +end + + +process(input_array[0], !input_array.at(1).nil?)",ruby +703,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,"secret_sum = 0 +num_iterations = 2000 +mul_by_64_shift = 6 +div_by_32_shift = 5 +mul_by_2048_shift = 11 +mod_val = 0x1000000 - 1 +File.readlines(""day_22_input.txt"").each do |line| + n = line.strip.to_i + num_iterations.times do + n = (n ^ (n << mul_by_64_shift)) & mod_val # multiply by 64, XOR with original value, mod 16777216 + n = (n ^ (n >> div_by_32_shift)) & mod_val # divide by 32, XOR with original value, mod 16777216 + n = (n ^ (n << mul_by_2048_shift)) & mod_val # multiply by 2048, XOR with original value, mod 16777216 + end + secret_sum += n +end +puts ""Part 1 Answer: #{secret_sum}""",ruby +704,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +PRUNE_MASK = 0b111111111111111111111111 + +codes = File.read(path).split(""\n"").map(&:to_i) + +def next_code(code) + tmp = code << 6 + code = code ^ tmp + code = code & PRUNE_MASK + tmp = code >> 5 + code = code ^ tmp + code = code & PRUNE_MASK + tmp = code << 11 + code = code ^ tmp + code & PRUNE_MASK +end + +res = codes.map do |code| + 2000.times do + code = next_code(code) + end + code +end + +puts res.sum",ruby +705,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,"#! /usr/bin/env ruby + +class RandomGenerator + def initialize(seed) + @seed = seed + end + + def next + mix_and_prune(@seed * 64) + mix_and_prune(@seed / 32) + mix_and_prune(@seed * 2048) + + @seed + end + + def mix_and_prune(a) + @seed = (@seed ^ a) % 16_777_216 + end +end + +#--------------------------------------------------------------------------------- +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo2.txt"" +seeds = File.readlines(input_file).map(&:strip).reject(&:empty?).map(&:to_i) + +shared_ngrams = Hash.new(0) + +seeds.each do |seed| + random_generator = RandomGenerator.new(seed) + previous_price = seed % 10 + price_diff_pairs = [] + + 2000.times do + price = random_generator.next % 10 + diff = price - previous_price + previous_price = price + price_diff_pairs << { price: , diff: } + end + + # generate all price n-grams of length 4 and record each n-gram with the price at the end of the n-gram + seen_ngrams = Set.new + price_diff_pairs.each_cons(4) do |window| + price = window.last[:price] + ngram = window.map { |p| p[:diff] } + next unless seen_ngrams.add?(ngram) + + shared_ngrams[ngram] += price + end +end + +ngram, price = shared_ngrams.max_by { |ngram, price| price } +puts ""Best ngram: #{ngram.join(',')} -> #{price}""",ruby +706,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,"TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + +PRUNE_MASK = 0b111111111111111111111111 +PRUNE_MODULO = 16777216 + +codes = File.read(path).split(""\n"").map(&:to_i) + +def next_code(code) + tmp = code << 6 + code = code ^ tmp + code = code & PRUNE_MASK + tmp = code >> 5 + code = code ^ tmp + code = code & PRUNE_MASK + tmp = code << 11 + code = code ^ tmp + code & PRUNE_MASK +end + +def compute_codes(code, times) + codes = Array.new(times) + codes[0] = code + (1...codes.count).each do |i| + previous_code = i.zero? ? code : codes[i - 1] + codes[i] = next_code(previous_code) + end + codes +end + +def compute_price_diffs(codes) + prices = codes.map { _1 % 10 } + diffs = prices.map.with_index { |price, i| i.zero? ? nil : price - prices[i - 1] } + [prices, diffs] +end + +def compute_sequences(prices, diffs) + sequences = Hash.new + (4...prices.count).each do |i| + key = ""#{diffs[i-3]}#{diffs[i-2]}#{diffs[i-1]}#{diffs[i]}"" + sequences[key] = prices[i] unless sequences.key?(key) + end + sequences +end + +puts ""Computing sequences..."" + +sequences = codes.map do |code| + new_codes = compute_codes(code, 2001) + prices, diffs = compute_price_diffs(new_codes) + compute_sequences(prices, diffs) +end + +puts ""Sequences computed"" + +all_keys = sequences.flat_map(&:keys).uniq + +puts ""#{all_keys.count} keys to try..."" + +values = all_keys.map do |key| + sequences.reduce(0) do |sum, sequences_hash| + sequences_hash.key?(key) ? sum + sequences_hash[key] : sum + end +end + +puts ""Done"" + +puts values.max",ruby +707,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,"input_array = ARGV + +def next_secret_number(secret_number) + secret_number = ((secret_number * 64) ^ secret_number) % 16777216 + secret_number = ((secret_number / 32).floor ^ secret_number) % 16777216 + secret_number = ((secret_number * 2048) ^ secret_number) % 16777216 +end + +def process(file_name, debug=false) + secret_numbers = [] + File.foreach(ARGV[0]).with_index do |line, index| + row = line.strip.to_i + secret_numbers.push(row) + end + + secret_total = 0 + sequences = [] + secret_numbers.each do |secret_number| + initial_secret_number = secret_number + sequence_to_price = {} + sequence = [] + previous_price = nil + 2000.times do + bananas = secret_number % 10 + sequence.push(bananas - previous_price) if !previous_price.nil? + previous_price = bananas + if sequence.length == 4 + sequence_to_price[sequence.join("","")] = bananas if sequence_to_price[sequence.join("","")].nil? + sequence.shift + end + secret_number = next_secret_number(secret_number) + end + sequences.push(sequence_to_price) + puts ""#{initial_secret_number}: #{secret_number}"" if debug + puts ""Sequences:\n#{sequences}"" if debug + secret_total += secret_number + end + + max_sequence = nil + max_sequence_amount = 0 + all_sequences = sequences.map { |s| s.keys }.flatten.uniq + all_sequences.each do |sequence| + sequence_amount = sequences.map { |s| s[sequence] }.compact.sum + if sequence_amount > max_sequence_amount + max_sequence = sequence + max_sequence_amount = sequence_amount + end + end + + puts ""Max sequence: #{max_sequence}, bananas: #{max_sequence_amount}"" + puts ""Secret total: #{secret_total}"" +end + + +process(input_array[0], !input_array.at(1).nil?)",ruby +708,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,"#!/usr/bin/env ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +$cache_1 = {} +def generate_secret_number(secret_number) + return $cache_1[secret_number] if $cache_1.has_key?(secret_number) + + start = secret_number + + result = secret_number * 64 + secret_number ^= result + secret_number %= 16777216 + + result = secret_number / 32 + secret_number ^= result + secret_number %= 16777216 + + result = secret_number * 2048 + secret_number ^= result + secret_number %= 16777216 + + $cache_1[start] = secret_number + + return secret_number +end + + +$sequences = {} +def generate_nth_secret_number(secret_number, n) + start = secret_number + prev_price = secret_number % 10 + prices = [prev_price] + diffs = [] + customer_sequences = {} + + n.times do |i| + secret_number = generate_secret_number(secret_number) + price = secret_number % 10 + diff = price - prev_price + prev_price = price + diffs << diff + prices << price + + if i > 3 + seq = diffs[i-3..i].join(',') + next if customer_sequences.has_key?(seq) + customer_sequences[seq] = prices[i+1] + end + end + + customer_sequences.each do |seq, price| + $sequences[seq] ||= [] + $sequences[seq] << price + end + return secret_number +end + +input = File.read(file_path).split(""\n"").map(&:to_i) + + +sum = 0 +input.each do |secret_number| + sum += generate_nth_secret_number(secret_number, 2000) +end + + +puts $sequences.map { |seq, prices| prices.sum }.max",ruby +709,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,"#!/usr/bin/env ruby + +# Login to https://adventofcode.com/2024/day/22/input to download 'input.txt'. + +# lines = readlines +# lines = File.readlines('sample2.txt', chomp: true) # Answer: 23 (in 73 ms) +lines = File.readlines('input.txt', chomp: true) # Answer: 1968 (in 21,706 ms) + +initial_numbers = lines.map(&:to_i) + +puts 'Initial Numbers' +puts '---------------' +puts initial_numbers +puts + +def next_secret_number(secret_number) + secret_number = mix_and_prune(secret_number, secret_number << 6) # Multiply by 64, or shift left by 6 bits + secret_number = mix_and_prune(secret_number, secret_number >> 5) # Divide by 32, or shift right by 5 bits + secret_number = mix_and_prune(secret_number, secret_number << 11) # Multiply by 2048, or shift left by 11 bits +end + +def mix_and_prune(n, mixin) + # mix: XOR together + # prune: modulo 16777216 (keep the lowest 24 bits, or AND with 16777215 (all 1's)) + (n ^ mixin) & 16777215 +end + +def price(secret_number) + secret_number % 10 +end + +sequences = initial_numbers.map do |n| + first_frame = { secret_number: n, price: price(n), delta: nil } + + 2000.times.reduce([first_frame]) do |acc, _| + previous = acc.last + + secret_number = next_secret_number(previous[:secret_number]) + price = price(secret_number) + + acc << { + secret_number:, + price:, + delta: price - previous[:price], + } + end +end + +puts 'Sequences' +puts '---------' +sequences.each do |sequence| + puts sequence.take(10) + puts '...' + puts +end + +pattern_sets = sequences.map do |sequence| + pattern = [] + + sequence.reduce(Hash.new(0)) do |hash, frame| + pattern << frame[:delta] unless frame[:delta].nil? + pattern.shift if pattern.size > 4 + + if pattern.size == 4 + key = pattern.join(',') + hash[key] = frame[:price] unless hash.key?(key) + end + + hash + end +end + +puts 'Pattern Sets' +puts '------------' +pattern_sets.each do |patterns| + patterns.take(10).each do |pattern, price| + puts ""#{pattern}: #{price}"" + end + puts '...' + puts +end + +patterns = pattern_sets.map(&:keys).flatten.uniq + +puts 'Patterns' +puts '--------' +puts patterns.take(10) +puts '...' +puts + +patterns_and_prices = patterns.reduce({}) do |hash, pattern| + hash[pattern] = pattern_sets.map { |set| set[pattern] } + hash +end + +puts 'Patterns w/ Prices' +puts '------------------' +puts patterns_and_prices.take(10).to_h +puts '...' +puts + +answer = patterns_and_prices.map { |_, prices| prices.sum }.max + +puts ""Answer: #{answer}""",ruby +710,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,"class Day23 + def initialize() + @network = Hash.new + end + + def read_process_input + File.open(""""Day23\\input23"".txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + computers = line.gsub(""\n"","""").split(""-"") + + if !@network.key?(computers[0]) + @network[computers[0]] = [] + end + + if !@network.key?(computers[1]) + @network[computers[1]] = [] + end + + @network[computers[0]].push(computers[1]) + @network[computers[1]].push(computers[0]) + end + end + end + + def find_groups + relevant_grops = Set.new + visited = [] + + for key in @network.keys + if !visited.include?(key) + other_computers = @network[key] + visited.push(key) + if other_computers.length >= 2 + for i in 0..other_computers.length-1 + other_computer_network = @network[other_computers[i]] + common_computers = other_computers & other_computer_network + if common_computers.length > 0 + for j in 0..common_computers.length-1 + last_computer_network = @network[common_computers[j]] + if last_computer_network.include?(key) && + last_computer_network.include?(other_computers[i]) + if key.start_with?(""t"") || common_computers[j].start_with?(""t"") || + other_computers[i].start_with?(""t"") + relevant_grops.add([key, other_computers[i], common_computers[j]].sort) + end + end + end + end + end + end + end + end + return relevant_grops.length + end +end + + +day23 = Day23.new() +day23.read_process_input +puts day23.find_groups",ruby +711,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 ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n"").map{ |line| line.split('-') } + +temp_groups = [] +groups = [] + +(input.size).times do |i| + + x1 = input[i][0] + x2 = input[i][1] + + (input.size).times do |j| + next if i == j + y1 = input[j][0] + y2 = input[j][1] + + if (x1 == x2 || x1 == y2 || y1 == x2 || y1 == y2) + temp_groups << [input[i], input[j]] + end + end + +end + + + +temp_groups = temp_groups.map { |group| group.sort } + +temp_groups.each do |group| + (input.size).times do |i| + x1 = input[i][0] + x2 = input[i][1] + + non_overlapping = group.flatten(1).tally.select { |k, v| v == 1 }.keys + c1 = non_overlapping[0] + c2 = non_overlapping[1] + + + if (x1 == c1 && x2 == c2) || (x1 == c2 && x2 == c1) + new_group = group.concat([input[i]]) + groups << new_group + end + end +end + +groups = groups.map { |group| group.flatten.uniq.sort }.uniq + +puts groups.select { |group| group.any? { |comp| comp[0] == ""t""} }.size",ruby +712,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,"# 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? +input_array = ARGV + +def find_three_connected_computers(adjacency_list) + three_connected_computers = [] + adjacency_list.each do |computer, connections| + next if !computer.start_with?('t') && !connections.any? {|connection| connection.start_with?('t')} + connections.each do |connection| + adjacency_list[connection].each do |connection2| + if connections.include?(connection2) + connected_computers = [computer, connection, connection2].sort + three_connected_computers.push(connected_computers) unless three_connected_computers.include?(connected_computers) + end + end + end + end + three_connected_computers +end + +def process(file_name, debug=false) + adjacency_list = {} + File.foreach(ARGV[0]).with_index do |line, index| + row = line.strip.split('-') + node1 = row[0] + node2 = row[1] + adjacency_list[node1] = [] if adjacency_list[node1].nil? + adjacency_list[node1].push(node2) + adjacency_list[node2] = [] if adjacency_list[node2].nil? + adjacency_list[node2].push(node1) + end + + puts ""Adjacency list: #{adjacency_list}"" if debug + + three_connected_computers = find_three_connected_computers(adjacency_list) + puts ""Three connected computers: #{three_connected_computers}"" if debug + t_networks = three_connected_computers.select {|network| network.any? {|computer| computer.start_with?('t')}} + puts ""Three connected computers count with 't': #{t_networks.length}"" +end + + +process(input_array[0], !input_array.at(1).nil?)",ruby +713,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,"require 'set' + +input = File.readlines('day-23/input.txt').map(&:chomp) + +computers = Hash.new { |h, k| h[k] = Set.new } +input.each do |line| + computer_names = line.split('-') + computers[computer_names[0]].add(computer_names[1]) + computers[computer_names[1]].add(computer_names[0]) +end + +triangles = Set[] +computers.each do |computer, connected_computers| + connected_computers.to_a.combination(2).each do |combination| + triangles.add(Set[computer, combination[0], combination[1]]) if computers[combination[0]].include?(combination[1]) + end +end + +pp triangles.select { |triangle| triangle.any? { |computer| computer[0] == 't'} }.size",ruby +714,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 ruby + +# Login to https://adventofcode.com/2024/day/23/input to download 'input.txt'. + +# lines = readlines +# lines = File.readlines('sample.txt', chomp: true) # Answer: 7 (in 54 ms) +lines = File.readlines('input.txt', chomp: true) # Answer: 1423 (in 60 ms) + +network = lines + .map { |line| line.split('-') } + .reduce(Hash.new { |hash, key| hash[key] = [] }) { |hash, pair| hash[pair[0]] << pair[1]; hash[pair[1]] << pair[0]; hash } + +puts ""Network (#{network.size})"" +puts '-------' +network.sort.select { |computer, _| computer.start_with?('t') }.each do |computer, connections| + puts ""#{computer} is connected to #{connections.sort} (#{connections.size})"" +end +puts + +triplets = network + .select { |computer, _| computer.start_with?('t') } + .collect do |computer, connections| + connections.collect do |connection| + connections + .intersection(network[connection]) + .collect { |third| [computer, connection, third] } + .map(&:sort) + .map { |triplet| triplet.join(',') } + end + end + .flatten + .uniq + +puts ""Triplets (#{triplets.size})"" +puts '-------' +puts triplets.sort +puts + +answer = triplets.size + +puts ""Answer: #{answer}""",ruby +715,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,qc,rn,so,tm,wf,yl,ys,ze,zr","#!/usr/bin/env ruby + +# Login to https://adventofcode.com/2024/day/23/input to download 'input.txt'. + +# lines = readlines +# lines = File.readlines('sample.txt', chomp: true) # Answer: co,de,ka,ta (in 61 ms) +lines = File.readlines('input.txt', chomp: true) # Answer: gt,ha,ir,jn,jq,kb,lr,lt,nl,oj,pp,qh,vy (in 74 ms) + +network = lines + .map { |line| line.split('-') } + .reduce(Hash.new { |hash, key| hash[key] = [] }) { |hash, pair| hash[pair[0]] << pair[1]; hash[pair[1]] << pair[0]; hash } + +puts ""Network (#{network.select { |computer, _| computer.start_with?('t') }.size} / #{network.size})"" +puts '-------' +network.sort.select { |computer, _| computer.start_with?('t') }.each do |computer, connections| + puts ""#{computer} is connected to #{connections.sort} (#{connections.size})"" +end +puts + +def cannon(c1, c2) + c1 < c2 ? ""#{c1}-#{c2}"" : ""#{c2}-#{c1}"" +end + +cannonical_connections = lines + .map { |line| line.split('-') } + .map { |c1, c2| cannon(c1, c2) } + .to_set + +puts ""Cannonical Connections (#{cannonical_connections.size})"" +puts '----------------------' +puts '...' +puts + +lan_parties = network + # .select { |computer, _| computer.start_with?('t') } # Assumption: the largest LAN party will include a computer starting with 't' + .collect do |computer, connections| + lan_party = [computer] + connections.each do |c1| + if lan_party.all? { |c2| cannonical_connections.include?(cannon(c1, c2)) } + lan_party << c1 + end + end + + lan_party + end + +sorted_lan_parties = lan_parties + .map(&:sort) + .map { |lan_party| lan_party.join(',') } + .uniq + .sort_by(&:size) + +puts +puts ""LAN Parties (#{lan_parties.size})"" +puts '-----------' +puts sorted_lan_parties.take(5) +puts '...' +puts sorted_lan_parties.reverse.take(5).reverse +puts + +puts ""Answer: #{sorted_lan_parties.last}""",ruby +716,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,qc,rn,so,tm,wf,yl,ys,ze,zr","TEST = false +path = TEST ? 'example_input.txt' : 'input.txt' + + +connections = File.read(path).split(""\n"").map { _1.split('-') } + +class Computer + attr_accessor :name + attr_accessor :connected_computers + + def initialize(name) + @name = name + @connected_computers = Set.new + end + + def ==(other) + other.is_a? Computer and @name == other.name + end + + def eql?(other) + other.is_a? Computer and @name.eql? other.name + end + + def hash + @name.hash + end + + def connect_to(computer) + @connected_computers << computer + end + + def to_s + ""Computer #{@name}; connected to #{@connected_computers.map(&:name).join(', ')}."" + end + + def connected_groups(res_set, verified = Set[], unverified = connected_computers + Set[self]) + new_verified = verified + Set[self] + new_unverified = unverified & connected_computers + if new_unverified.empty? + res_set << new_verified + return + end + new_unverified.each { |comp| comp.connected_groups(res_set, new_verified, new_unverified) } + end + + def self.connect(comp1, comp2) + comp1.connect_to(comp2) + comp2.connect_to(comp1) + end + + def self.password_by_building_sets(sets, computers) + puts ""#{sets.count} sets of #{sets.first.count}"" + return sets.first.map(&:name).sort.join(',') if sets.count == 1 + return 'FUCK' if sets.empty? + bigger_sets = Set[] + sets.each do |set| + computers.each do |computer| + bigger_sets << set + Set[computer] if set.subset?(computer.connected_computers) + end + end + password_by_building_sets(bigger_sets, computers) + end +end + +def build(connections) + computers = Hash.new + connections.each do |connection| + name1 = connection[0] + comp1 = computers[name1] || Computer.new(name1) + computers[name1] = comp1 + name2 = connection[1] + comp2 = computers[name2] || Computer.new(name2) + computers[name2] = comp2 + Computer.connect(comp1, comp2) + end + computers.values +end + +def sets_of_three(computers) + sets = Set.new + computers.each do |computer| + computer.connected_computers.each do |comp2| + comp2.connected_computers.each do |comp3| + sets << Set[computer, comp2, comp3] if comp3.connected_computers.include?(computer) + end + end + end + sets +end + +computers = build(connections) + +sets = sets_of_three(computers) + +p ""Password: #{Computer.password_by_building_sets(sets, computers)}""",ruby +717,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,qc,rn,so,tm,wf,yl,ys,ze,zr","# 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? +input_array = ARGV + +def find_largest_lan_party(adjacency_list) + largest_lan_party = [] + + adjacency_list.each do |computer, connections| + lan_party = [computer] + connections.each do |connection| + all_connected = lan_party.all? { |lan_party_computer| adjacency_list[connection].include?(lan_party_computer) } + lan_party.push(connection) if all_connected + end + largest_lan_party = lan_party if lan_party.length > largest_lan_party.length + end + + puts ""Largest LAN party: #{largest_lan_party}"" + password = largest_lan_party.sort.join(',') + puts ""Password: #{password}"" +end + +def process(file_name, debug=false) + adjacency_list = {} + File.foreach(ARGV[0]).with_index do |line, index| + row = line.strip.split('-') + node1 = row[0] + node2 = row[1] + adjacency_list[node1] = [] if adjacency_list[node1].nil? + adjacency_list[node1].push(node2) + adjacency_list[node2] = [] if adjacency_list[node2].nil? + adjacency_list[node2].push(node1) + end + + puts ""Adjacency list: #{adjacency_list}"" if debug + + find_largest_lan_party(adjacency_list) +end + + +process(input_array[0], !input_array.at(1).nil?)",ruby +718,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,qc,rn,so,tm,wf,yl,ys,ze,zr","#! /usr/bin/env ruby + +class CliqueFinder + attr_reader :maximal_clique, :network + + def initialize(network) + @network = network + @maximal_clique = Set.new + end + + def bron_kerbosch(current: Set.new, candidates:, excluded: Set.new) + if candidates.empty? && excluded.empty? + @maximal_clique = current.to_a.sort if current.size > maximal_clique.size + return @maximal_clique + end + + pivot = candidates.first # Pick a pivot node (makes it a lot faster) + non_neighbors = candidates - network[pivot] + + non_neighbors.each do |v| + current.add(v) + next_p = candidates & network[v] + next_x = excluded & network[v] + bron_kerbosch(current: current, candidates: next_p, excluded: next_x) + current.delete(v) + excluded.add(v) + end + + maximal_clique + end +end + +network = Hash.new { |h, k| h[k] = Set.new } +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file).map(&:strip).reject(&:empty?) + +lines.each do |line| + from, to = line.split('-') + network[from].add(to) + network[to].add(from) +end + +clique_finder = CliqueFinder.new(network) +result = clique_finder.bron_kerbosch(candidates: Set.new(network.keys)) +puts ""result: #{result.join(',')}"" + +# am,au,be,cm,fo,ha,hh,im,nt,os,qz,rr,so - good +",ruby +719,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,qc,rn,so,tm,wf,yl,ys,ze,zr","#!/usr/bin/env ruby +# frozen_string_literal: true +require 'set' + +largest_cluster = [] + +def expand_nodes(r, p, x, graph, largest_cluster) + if p.empty? && x.empty? + largest_cluster.replace(r) if r.size > largest_cluster.size + return + end + + pivot = (p + x).first + + (p - graph[pivot]).each do |v| + expand_nodes( + r + [v], + p & graph[v], + x & graph[v], + graph, + largest_cluster + ) + p.delete(v) + x.add(v) + end +end + + +file_path = File.expand_path('input.txt', __dir__) + +groups = File.read(file_path).split(""\n"").map{ |line| line.split('-') } + +connections = {} + +groups.each do |group| + connections[group[0]] ||= [] + connections[group[0]] << group[1] + connections[group[1]] ||= [] + connections[group[1]] << group[0] +end + +graph = connections.transform_values { |neighbors| neighbors.to_set } +nodes = graph.keys.sort_by { |node| graph[node].size } + + +expand_nodes([], nodes.to_set, Set.new, graph, largest_cluster) +puts largest_cluster.sort.join(',')",ruby +720,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,"GateInput = Struct.new(:a, :b, :out, :operator) + +class Gates + def initialize(filename) + @outputs = Hash.new + inputs = [] + File.readlines(filename).each do |line| + if line.include?("":"") + match = line.match(/([\w\d]+):\s*(1|0)/) + @outputs[match[1]] = match[2].to_i + elsif line.include?(""->"") + match = line.match(/([\w\d]+)\s*([\w\d]+)\s*([\w\d]+)\s*->\s*([\w\d]+)/) + inputs.append(GateInput.new(match[1], match[3], match[4], match[2])) + end + end + + # Convert inputs into outputs + while !inputs.empty? do + input_to_convert_index = -1 + inputs.each_with_index do |input, index| + if !@outputs.key?(input.a) || !@outputs.key?(input.b) + next + end + + input_to_convert_index = index + break + end + + if input_to_convert_index == -1 + puts ""Error: Couldn't find input to convert!"" + break + end + + input = inputs[input_to_convert_index] + case input.operator + when ""AND"" + @outputs[input.out] = (@outputs[input.a] == 1) && (@outputs[input.b] == 1) ? 1 : 0 + when ""OR"" + @outputs[input.out] = (@outputs[input.a] == 1) || (@outputs[input.b] == 1) ? 1 : 0 + when ""XOR"" + @outputs[input.out] = (@outputs[input.a] != @outputs[input.b]) ? 1 : 0 + end + inputs.delete_at(input_to_convert_index) + end + + #p @outputs.to_a.sort + end + + def solve_part_1 + final_output = 0 + @outputs.each do |k, v| + if k[0] != ""z"" || v == 0 + next + end + + bit_place = k.delete(""z"").to_i + final_output |= (1 << bit_place) + end + puts ""Part 1 Answer: #{final_output}"" + end +end + +gates = Gates.new(""day_24_input.txt"") +gates.solve_part_1",ruby +721,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,"require 'set' + +class Gate + attr_accessor :input_wires, :operation, :output_wire + + def initialize(input_wires, operation, output_wire, wires) + @input_wires = input_wires + @operation = operation + @output_wire = output_wire + @wires = wires + end + + def execute! + return unless @wires[@output_wire].nil? + return if @wires[@input_wires[0]].nil? + return if @wires[@input_wires[1]].nil? + + if @operation == 'AND' + @wires[output_wire] = @wires[@input_wires[0]] & @wires[@input_wires[1]] + elsif @operation == 'OR' + @wires[output_wire] = @wires[@input_wires[0]] | @wires[@input_wires[1]] + else # XOR + @wires[output_wire] = @wires[@input_wires[0]] ^ @wires[@input_wires[1]] + end + end +end + +def execute(gates) + while @wires.select { |key, _| key[0] == 'z' }.any? { |_, value| value.nil? } + gates.each(&:execute!) + end + + result = 0 + @wires.keys.select { |key| key[0] == 'z' }.sort.reverse_each do |key| + result <<= 1 + result += @wires[key] + end + result +end + +lines = File.readlines('day-24/input.txt').map(&:chomp) + +@wires = Hash.new(nil) +gates = Set[] +lines.reverse_each do |line| + if line.include?('->') + split_line = line.split(' ') + @wires[split_line[0]] = nil + @wires[split_line[2]] = nil + @wires[split_line[4]] = nil + gates.add(Gate.new([split_line[0], split_line[2]], split_line[1], split_line[4], @wires)) + elsif line.include?(':') + split_line = line.split(': ') + @wires[split_line[0]] = split_line[1].to_i + end +end + +pp execute(gates)",ruby +722,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,"class Day24 + def initialize() + @inputs = Hash.new + @operators_queue = [] # (var, op, var, output) + end + + def read_process_input + File.open(""Day24\\input24.txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + if line.include?("":"") + line = line.split("":"") + @inputs[line[0]] = line[1].strip.to_i + elsif !line.strip.empty? + if line.include?(""AND"") + op = line.split(""AND"") + tmp = op[1].split(""->"") + @operators_queue.push([op[0].strip, ""AND"", tmp[0].strip, tmp[1].strip]) + elsif line.include?(""XOR"") + op = line.split(""XOR"") + tmp = op[1].split(""->"") + @operators_queue.push([op[0].strip, ""XOR"", tmp[0].strip, tmp[1].strip]) + elsif line.include?(""OR"") + op = line.split(""OR"") + tmp = op[1].split(""->"") + @operators_queue.push([op[0].strip, ""OR"", tmp[0].strip, tmp[1].strip]) + end + end + end + end + end + + def calculate + @operators_queue.each { |op_combination| + var1 = op_combination[0] + op = op_combination[1] + var2 = op_combination[2] + output = op_combination[3] + + if @inputs.key?(var1) && @inputs.key?(var2) + if op == ""AND"" + @inputs[output] = @inputs[var1] & @inputs[var2] + elsif op == ""OR"" + @inputs[output] = @inputs[var1] | @inputs[var2] + elsif op == ""XOR"" + @inputs[output] = @inputs[var1] ^ @inputs[var2] + end + else + @operators_queue.push([var1, op, var2, output]) + end + } + + first_output = @inputs[""z00""] + incr = 0 + res = """" + while first_output != nil + res += first_output.to_s + incr += 1 + incr_string = incr.to_s + if incr_string.size == 1 + incr_string = ""0"" + incr_string + end + incr_string = ""z"" + incr_string + first_output = @inputs[incr_string] + end + + return res.reverse!.to_i(2) + end +end + + +day24 = Day24.new() +day24.read_process_input +puts day24.calculate",ruby +723,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 ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n\n"") + +inputs = input[0].split(""\n"").map do |line| + l = line.split(': ') + [l[0], l[1].to_i] +end.to_h + +gates = input[1].split(""\n"").map do |line| + l = line.scan(/(\w+) (\w+) (\w+) -> (\w+)/).flatten + + { + gate1: l[0], + gate2: l[2], + operation: l[1], + output: l[3] + } +end + + +while gates.size > 0 do + gates.each_with_index do |gate, index| + if inputs.has_key?(gate[:gate1]) && inputs.has_key?(gate[:gate2]) + if gate[:operation] == 'AND' + inputs[gate[:output]] = inputs[gate[:gate1]] & inputs[gate[:gate2]] + gates.delete_at(index) + elsif gate[:operation] == 'OR' + inputs[gate[:output]] = inputs[gate[:gate1]] | inputs[gate[:gate2]] + gates.delete_at(index) + else + inputs[gate[:output]] = inputs[gate[:gate1]] ^ inputs[gate[:gate2]] + gates.delete_at(index) + end + end + end +end + +puts inputs.select { |k, v| k[0] == 'z' }.sort.reverse.map { |k, v| v.to_s }.join.to_i(2).to_s(10)",ruby +724,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 ruby + +def calculate(wires, wire) + return wires[wire] unless wires[wire].is_a?(Hash) + + a, op, b = wires[wire].values_at(:a, :op, :b) + a = calculate(wires, a) + b = calculate(wires, b) + + wires[wire] = case op + when ""AND"" + a & b + when ""OR"" + a | b + when ""XOR"" + a ^ b + end + + wires[wire] +end + +input_file = ENV['REAL'] ? ""input.txt"" : ""input-demo.txt"" +lines = File.readlines(input_file) + +wires = {} +while line = lines.shift + break if line.strip.empty? + name, value = line.strip.split("":"").map(&:strip) + wires[name] = value.to_i == 1 +end + +while line = lines.shift + eq, output = line.strip.split(""->"").map(&:strip) + a, op, b = eq.split("" "") + wires[output] = { a:, op: , b: } +end + +z_wires = wires.keys.select { |k| k.start_with?(""z"") } +z_bits = '' + +z_wires.sort.each do |wire| + bit = calculate(wires, wire) ? 1 : 0 + z_bits << bit.to_s +end + +z_bits = z_bits.reverse.to_i(2) +puts z_bits.inspect",ruby +725,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,tqr,vmv,z07,z20,z28","require 'set' + +def test_input_1 + _input = """"""x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02"""""".strip.split(""\n"") + + raise unless part_1(_input) == 4 +end + +def test_input_2 + _input = """"""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"""""".strip.split(""\n"") + + raise unless part_1(_input) == 2024 +end + +def read_input(path) + File.readlines(path).map(&:strip) +end + +def get_variables_and_gates(input_data) + variables = {} + gates = [] + + input_data.each do |line| + if line.include?(':') + variable, value = line.split(': ') + variables[variable] = value.to_i + elsif line.include?('->') + a, op, b, _, c = line.split + gates << [a, op, b, c] + end + end + + [variables, gates] +end + +def try_solve(variables, gate) + a, op, b, c = gate + av = variables[a] + bv = variables[b] + + return false if av.nil? || bv.nil? + + case op + when 'AND' + variables[c] = av & bv + when 'OR' + variables[c] = av | bv + when 'XOR' + variables[c] = av ^ bv + end + + true +end + +class Graph + def initialize + @nodes = {} + end + + def add_node(node) + @nodes[node] ||= {} + end + + def add_edge(node1, node2, description = """") + add_node(node1) + add_node(node2) + @nodes[node1][node2] = description + @nodes[node2][node1] = description + end + + def nodes + @nodes + end +end + +def part_1(input_data) + variables, gates = get_variables_and_gates(input_data) + queue = gates.dup + + until queue.empty? + gate = queue.shift + unless try_solve(variables, gate) + queue.push(gate) + end + end + + variables.keys.select { |key| key.start_with?('z') } + .sort + .map { |key| variables[key].to_s } + .join + .to_i(2) +end + +def part_2(input_data) + _, gates = get_variables_and_gates(input_data) + g = Graph.new + + gates.each do |gate| + a, op, b, c = gate + g.add_edge(c, a, op) + g.add_edge(c, b, op) + end + + swaps = Set.new + (1..44).each do |i| + x = format(""x%02d"", i) + y = format(""y%02d"", i) + z = format(""z%02d"", i) + + xors = g.nodes[x].key('XOR') + next unless xors + + next_xor = g.nodes[xors].select { |k, v| v == 'XOR' }.keys + + unless next_xor.include?(z) + if next_xor.size == 3 + next_xor.each do |n| + if n != x && n != y + swaps.add(z) + swaps.add(n) + break + end + end + else + swaps.add(g.nodes[x].keys[0]) + swaps.add(g.nodes[x].keys[1]) + end + end + end + + swaps.to_a.sort.join(',') +end + +def main + input_data = read_input(ARGV[0]) + puts ""Part 1: #{part_1(input_data)}"" + puts ""Part 2: #{part_2(input_data)}"" +end + +if __FILE__ == $0 + main +end",ruby +726,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,tqr,vmv,z07,z20,z28","def parse_values(input) + value_hash = {} + input.split(""\n\n"")[0].lines.each do |ln| + key, val = ln.strip.split(':') + value_hash[key] = val.to_i + end + + value_hash +end + +def parse_gates(input) + gate_hash = {} + + input.split(""\n\n"")[1].lines.each do |ln| + gate, res = ln.strip.split(' -> ') + if gate.include?(' AND ') + opr1, opr2 = gate.split(' AND ') + op = 'AND' + elsif gate.include?(' XOR ') + opr1, opr2 = gate.split(' XOR ') + op = 'XOR' + elsif gate.include?(' OR ') + opr1, opr2 = gate.split(' OR ') + op = 'OR' + end + + gate_hash[res] = [opr1, op, opr2] + end + + gate_hash +end + +def parse_input(file) + input = File.read(File.join(File.dirname(__FILE__), file)) + + values = parse_values(input) + gate_hash = parse_gates(input) + + dependencies = build_dependencies(values, gate_hash) + operations = sort_operations(gate_hash, dependencies) + + [values, operations] +end + +def build_dependencies(value_hash, gate_hash) + dependencies = {} + + gate_hash.each do |gate, ops| + dependencies[gate] = [] + + dependencies[gate].append(ops[0]) if !value_hash.keys.include?(ops[0]) && gate_hash.keys.include?(ops[0]) + + dependencies[gate].append(ops[2]) if !value_hash.keys.include?(ops[2]) && gate_hash.keys.include?(ops[2]) + end + + dependencies +end + +def sort_operations(gate_hash, dependencies) + in_degree = {} + + dependencies.each { |val, deps| in_degree[val] = deps.length } + + queue = in_degree.select { |_k, v| v.zero? }.keys + sorted_operations = [] + + until queue.empty? + current = queue.shift + + sorted_operations.append([current, gate_hash[current]].flatten) + + gate_hash.each do |res, ops| + if ops[0] == current || ops[2] == current + in_degree[res] -= 1 + queue.append(res) if (in_degree[res]).zero? + end + end + end + + sorted_operations +end + +def gate_operation(opr1, op, opr2) + case op + when 'AND' then opr1 & opr2 + when 'XOR' then opr1 ^ opr2 + when 'OR' then opr1 | opr2 + end +end + +def crossed_wires(file) + values, operations = parse_input(file) + + operations.each do |op| + result, opr1, op, opr2 = op + values[result] = gate_operation(values[opr1], op, values[opr2]) + end + + values.select { |k, _v| k.chars.first == 'z' }.sort.reverse.map { |z| z[1] }.join.to_i(2) +end + +def operation_valid?(op, operations) + result, opr1, op, opr2 = op + + return false if result.chars.first == 'z' && op != 'XOR' && !result.include?('45') + + if result.chars.first != 'z' && op == 'XOR' + return false if [opr1, opr2].none? { |o| o.chars.first.include?('x') || o.chars.first.include?('y') } + end + + if [opr1, opr2].all? { |o| o.chars.first.include?('x') || o.chars.first.include?('y') } && op == 'XOR' + if [opr1, opr2].none? { |o| o.include?('00') } + return false if operations.none? { |op| op[1..].include?(result) && op[2] == 'XOR' } + end + end + + if [opr1, opr2].all? { |o| o.chars.first.include?('x') || o.chars.first.include?('y') } && op == 'AND' + if [opr1, opr2].none? { |o| o.include?('00') } + return false if operations.none? { |op| op[1..].include?(result) && op[2] == 'OR' } + end + end + + true +end + +def faulty_wires(file) + _, operations = parse_input(file) + faulty = [] + + operations.each do |op| + faulty.append(op) unless operation_valid?(op, operations) + end + + faulty.map(&:first).sort.join(',') +end + +input_file = 'day24-input.txt' + +# Part 1 +puts crossed_wires(input_file) + +# Part 2 +puts faulty_wires(input_file)",ruby +727,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,tqr,vmv,z07,z20,z28","require 'set' + +def parse_input(file) + wire_values = {} + gates = [] + + File.readlines(file).each do |line| + if line.include?(""->"") + expr, wire = line.strip.split("" -> "") + left, operator, right = expr.split("" "") + + gates << { left: left, operator: operator, right: right, result: wire } + wire_values[wire] = nil # Initialize result wire with nil + elsif line.include?("":"") + wire, value = line.strip.split("": "") + wire_values[wire] = value.to_i + end + end + + [wire_values, gates] +end + +def is_input?(operand) + operand.start_with?('x', 'y') +end + +def build_usage_map(gates) + # Create a usage map of gates for operands + usage_map = Hash.new { |hash, key| hash[key] = [] } + + gates.each do |gate| + usage_map[gate[:left]] << gate + usage_map[gate[:right]] << gate + end + + usage_map +end + +def xor_conditions_met?(left, right, result, usage_map) + if is_input?(left) + return true if !is_input?(right) || (result[0] == 'z' && result != 'z00') + + used_ops = usage_map[result].map { |gate| gate[:operator] } + return result != 'z00' && used_ops.sort != ['AND', 'XOR'] + elsif result[0] != 'z' + return true + end + false +end + +def and_conditions_met?(left, right, result, usage_map) + if is_input?(left) && !is_input?(right) + return true + end + used_ops = usage_map[result].map { |gate| gate[:operator] } + used_ops != ['OR'] +end + +def or_conditions_met?(left, right, result, usage_map) + if is_input?(left) || is_input?(right) + return true + end + used_ops = usage_map[result].map { |gate| gate[:operator] } + used_ops.sort != ['AND', 'XOR'] +end + +def identify_swapped_wires(wire_values, gates) + usage_map = build_usage_map(gates) + swapped_wires = Set.new + + gates.each do |gate| + left, op, right, result = gate[:left], gate[:operator], gate[:right], gate[:result] + next if result == 'z45' || left == 'x00' + + case op + when 'XOR' + swapped_wires.add(result) if xor_conditions_met?(left, right, result, usage_map) + when 'AND' + swapped_wires.add(result) if and_conditions_met?(left, right, result, usage_map) + when 'OR' + swapped_wires.add(result) if or_conditions_met?(left, right, result, usage_map) + else + puts ""Unknown operation: #{op} for gate #{gate}"" + end + end + + swapped_wires.to_a.sort +end + +# Main Execution +wire_values, gates = parse_input('input.txt') +swapped_wires = identify_swapped_wires(wire_values, gates) +puts swapped_wires.join(',')",ruby +728,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,tqr,vmv,z07,z20,z28","require 'set' + +def parse_input(file) + wire_values = {} + gates = [] + + File.readlines(file).each do |line| + if line.include?(""->"") + # Parse gate operation like: ""x0 AND y1 -> z45"" + expr, wire = line.split("" -> "") + left, op, right = expr.split("" "") + + # Store the gate operation in the gates list + gates << ""#{left} #{op} #{right} -> #{wire}"" + # Initialize wire values with nil as we don't know them yet + wire_values[wire] = nil + elsif line.include?("":"") + # Parse initial wire values like: ""x00: 1"" + wire, value = line.split("": "") + wire_values[wire] = value.to_i + end + end + + [wire_values, gates] +end + +def collect_outputs(wire_values, prefix) + # Collects and returns a list of output values from a dictionary of wire values + # where the keys start with a given prefix. + wire_values.select { |key, _| key.start_with?(prefix) } + .sort + .map { |_key, value| value } +end + +def is_input(operand) + # Checks if the given operand is an input variable. + operand[0] == 'x' || operand[0] == 'y' +end + +def get_usage_map(gates) + # Generates a usage map from a list of gate strings. + usage_map = Hash.new { |hash, key| hash[key] = [] } + gates.each do |gate| + parts = gate.split(' ') + usage_map[parts[0]] << gate + usage_map[parts[2]] << gate + end + usage_map +end + +def check_xor_conditions(left, right, result, usage_map) + # Checks if the given conditions for XOR operations are met. + if is_input(left) + if !is_input(right) || (result[0] == 'z' && result != 'z00') + return true + end + usage_ops = usage_map[result].map { |op| op.split(' ')[1] } + return result != 'z00' && usage_ops.sort != ['AND', 'XOR'] + elsif result[0] != 'z' + return true + end + false +end + +def check_and_conditions(left, right, result, usage_map) + # Checks specific conditions based on the provided inputs and usage map. + if is_input(left) && !is_input(right) + return true + end + usage_ops = usage_map[result].map { |op| op.split(' ')[1] } + usage_ops != ['OR'] +end + +def check_or_conditions(left, right, result, usage_map) + # Checks if the given conditions involving 'left', 'right', and 'result' meet certain criteria. + if is_input(left) || is_input(right) + return true + end + usage_ops = usage_map[result].map { |op| op.split(' ')[1] } + usage_ops.sort != ['AND', 'XOR'] +end + +def find_swapped_wires(wire_values, gates) + # Identifies and returns a list of swapped wires based on the provided wire values and gate operations. + usage_map = get_usage_map(gates) + swapped_wires = Set.new + + gates.each do |gate| + left, op, right, _, result = gate.split(' ') + next if result == 'z45' || left == 'x00' + + case op + when 'XOR' + swapped_wires.add(result) if check_xor_conditions(left, right, result, usage_map) + when 'AND' + swapped_wires.add(result) if check_and_conditions(left, right, result, usage_map) + when 'OR' + swapped_wires.add(result) if check_or_conditions(left, right, result, usage_map) + else + puts ""#{gate} unknown op"" + end + end + + swapped_wires.to_a.sort +end + +# Assuming input is in a file 'input.txt' +wire_values, gates = parse_input('input.txt') +swapped_wires = find_swapped_wires(wire_values, gates) +result = swapped_wires.join(',') +puts result",ruby +729,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,tqr,vmv,z07,z20,z28","require 'set' + +class Gate + attr_accessor :input_wires, :operation, :output_wire + + def initialize(input_wires, operation, output_wire, wires) + @input_wires = input_wires + @operation = operation + @output_wire = output_wire + @wires = wires + end + + def execute! + return unless @wires[@output_wire].nil? + return if @wires[@input_wires[0]].nil? + return if @wires[@input_wires[1]].nil? + + if @operation == 'AND' + @wires[output_wire] = @wires[@input_wires[0]] & @wires[@input_wires[1]] + elsif @operation == 'OR' + @wires[output_wire] = @wires[@input_wires[0]] | @wires[@input_wires[1]] + else # XOR + @wires[output_wire] = @wires[@input_wires[0]] ^ @wires[@input_wires[1]] + end + end +end + +def execute(gates) + while @wires.select { |key, _| key[0] == 'z' }.any? { |_, value| value.nil? } + gates.each(&:execute!) + end + + result = 0 + @wires.keys.select { |key| key[0] == 'z' }.sort.reverse_each do |key| + result <<= 1 + result += @wires[key] + end + result +end + +lines = File.readlines('day-24/input.txt').map(&:chomp) + +gates_by_output_wire = {} + +@wires = Hash.new(nil) +gates = Set[] +lines.reverse_each do |line| + if line.include?('->') + split_line = line.split(' ') + @wires[split_line[0]] = nil + @wires[split_line[2]] = nil + @wires[split_line[4]] = nil + gate = Gate.new([split_line[0], split_line[2]], split_line[1], split_line[4], @wires) + gates.add(gate) + gates_by_output_wire[split_line[4]] = gate + elsif line.include?(':') + split_line = line.split(': ') + @wires[split_line[0]] = split_line[1].to_i + end +end + +execute(gates) + +# Patterns in my input: +# X0 AND Y0 => A(kqn) +# X1 XOR Y1 => B(knr) +# A XOR B => Z1 +# A AND B => C(fhg) + +# C OR D => E(mkg) +# X1 AND Y1 => D(stk) +# X2 XOR Y2 => F(sbv) +# E XOR F => Z2 +# E AND F => G(wwd) + +# G OR H => I(gfq) +# X2 AND Y2 => H(mrq) +# X3 XOR Y3 => J(kfr) +# I XOR J => Z3 +# I AND J => K(fdc) + +# I'm assuming that this observed pattern is how the machine is ""supposed"" to be built, i.e. that there +# are no variances in the design as the bit count increases. (And more generally, that the machine isn't +# ""spaghetti code"".) + +# (Therefore, this is not a ""general solution"" to the problem statement. But it does solve the problem +# for my input, at least!) + +# So, every ""level"" except 0, 1, and the final one should have a pattern of 5 gates like the above two blocks +# (X==2 in this example): +# +# XN XOR YN => F +# E XOR F => ZN +# E AND F => G +# XN AND YN => H +# G OR H => I +# X(N+1) XOR Y(N+1) => J +# I XOR J => Z(N+1) + +swap_gates = [] +max_z = @wires.keys.select { |key| key[0] == 'z' }.map { |key| key[1..-1].to_i }.max +(2..(max_z - 2)).each do |bit| + xn = ""x#{format('%02d', bit)}"" + yn = ""y#{format('%02d', bit)}"" + zn = ""z#{format('%02d', bit)}"" + xn_plus_one = ""x#{format('%02d', bit + 1)}"" + yn_plus_one = ""y#{format('%02d', bit + 1)}"" + zn_plus_one = ""z#{format('%02d', bit + 1)}"" + + gate_f = gates.find { |gate| gate.input_wires.tally == [xn, yn].tally && gate.operation == 'XOR' } + + gate_z_n = gates.find { |gate| gate.input_wires.include?(gate_f.output_wire) && gate.operation == 'XOR' && gate.output_wire == zn } + next if gate_z_n.nil? + + gate_g = gates.find { |gate| gate.input_wires.include?(gate_f.output_wire) && gate.operation == 'AND' } + gate_h = gates.find { |gate| gate.input_wires.tally == [xn, yn].tally && gate.operation == 'AND' } + gate_i = gates.find { |gate| gate.input_wires.tally == [gate_g.output_wire, gate_h.output_wire].tally && gate.operation == 'OR' } + gate_j = gates.find { |gate| gate.input_wires.tally == [xn_plus_one, yn_plus_one].tally && gate.operation == 'XOR' } + + gate_z_n_plus_one = gates.find { |gate| gate.input_wires.tally == [gate_i.output_wire, gate_j.output_wire].tally && gate.operation == 'XOR' && gate.output_wire == zn_plus_one } + next unless gate_z_n_plus_one.nil? + + swap_gate = gates.find { |gate| gate.input_wires.tally == [gate_i.output_wire, gate_j.output_wire].tally && gate.operation == 'XOR' } + if swap_gate + swap_gates << swap_gate.output_wire + swap_gates << zn_plus_one + else + swap_gates << gate_j.output_wire + other_swap_gate = gates.find { |gate| gate.input_wires.include?(gate_i.output_wire) && gate.operation == 'XOR' } + swap_gates << other_swap_gate.input_wires.find { |wire| wire != gate_i.output_wire } + end +end + +p swap_gates.sort.join(',')",ruby +730,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 ruby + +# Login to https://adventofcode.com/2024/day/25/input to download 'input.txt'. + +# lines = readlines +# lines = File.readlines('sample.txt', chomp: true) # Answer: 3 (in 61 ms) +lines = File.readlines('input.txt', chomp: true) # Answer: 2950 (in 103 ms) + +separators = lines.map.with_index { |line, i| line.empty? ? i : nil }.compact + +schematic_ranges = ([-1] + separators + [lines.size]).each_cons(2).map { |pair| (pair.first + 1)...(pair.last) } + +locks = schematic_ranges + .map { |range| lines[range] } + .select { |schematic| schematic[0].match(/^#+$/) && schematic[-1].match(/^\.+$/) } + .map do |schematic| + schematic[1...-1].map { |row| row.split('').map {|cell| cell == '#' ? 1 : 0 } } + end + .map do |positions| + (0...(positions.first.size)).collect { |col| positions.collect { |row| row[col] }.sum } + end + +puts ""Locks (#{locks.size})"" +puts '-----' +locks.each { |lock| puts lock.inspect } +puts + +keys = schematic_ranges + .map { |range| lines[range] } + .select { |schematic| schematic[0].match(/^\.+$/) && schematic[-1].match(/^#+$/) } + .map do |schematic| + schematic[1...-1].map { |row| row.split('').map {|cell| cell == '#' ? 1 : 0 } } + end + .map do |positions| + (0...(positions.first.size)).collect { |col| positions.collect { |row| row[col] }.sum } + end + +puts ""Keys (#{keys.size})"" +puts '----' +keys.each { |key| puts key.inspect } +puts + +answer = locks.product(keys).count do |lock, key| + lock.zip(key).map { |pair| pair.sum }.all? { |sum| sum <= 5 } +end + +puts ""Answer: #{answer}""",ruby +731,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,"class Day25 + def initialize() + @keys = [] + @locks = [] + @size = 7 + end + + def read_file + is_key = false + is_on_going = false + curr_line = 0 + curr = [0,0,0,0,0] + read_lines = 1 + File.open(""Day25\\input25.txt"", ""r"") do |f| + f.each_line.with_index do |line, i| + + if !is_on_going && line.strip == ""#####"" + is_on_going = true + is_key = false # is lock + elsif is_on_going && read_lines == @size + is_on_going = false + + if is_key + @keys.push(curr) + else + @locks.push(curr) + end + + curr = [0,0,0,0,0] + read_lines = 1 + elsif !is_on_going && line.strip == ""....."" + is_on_going = true + is_key = true # is key + end + + if is_on_going + chars = line.strip.chars.map { |c| if c == ""#"" then 1 else 0 end} + curr = [curr[0] + chars[0], curr[1] + chars[1], curr[2] + chars[2], curr[3] + chars[3], curr[4] + chars[4]] + read_lines += 1 + end + end + end + end + + def get_matching_pairs + matches = 0 + for i in 0..@keys.length-1 + key = @keys[i] + for j in 0..@locks.length-1 + lock = @locks[j] + matched_validations = 0 + for k in 0..4 + matched_validations += 1 if key[k] + lock[k] < @size + end + matches += 1 if matched_validations == 5 + end + end + return matches + end +end + +day25 = Day25.new() +day25.read_file +puts day25.get_matching_pairs",ruby +732,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,"require 'matrix' + +def parse_input(file) + input = File.read(File.join(File.dirname(__FILE__), file)) + locks = [] + keys = [] + + input.split(""\n\n"").each do |blk| + lk = Vector[0, 0, 0, 0, 0] + lock = blk[0] == '#' + + rows = blk.lines[1..-2].map(&:strip) + + rows.each do |row| + row.chars.each_with_index { |chr, idx| lk[idx] += 1 if chr == '#' } + end + + if lock + locks.append(lk) + else + keys.append(lk) + end + end + + [locks, keys] +end + +def count_matches(file) + locks, keys = parse_input(file) + matches = 0 + keys.each do |key| + locks.each do |lock| + matches += 1 unless (lock + key).any? { |pin| pin > 5 } + end + end + + matches +end + +puts count_matches('day25-input.txt')",ruby +733,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 = File.read(""Day25.txt"").split(""\n\n"").map{|lock| lock.split(""\n"").map(&:chars).transpose}.group_by{|x| x[0][0]}.values +depth = locks[0][0].size +locks = locks.map{|lock|lock.map{|line| line.count('#')}} +keys = keys.map{|lock|lock.map{|line| line.count('#')}} + +p locks.map{|lock| keys.map{|key| key.zip(lock).map{_1.inject(:+)}.all?{|x| x<=depth}}}.flatten.count(true)",ruby +734,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 ruby +# frozen_string_literal: true + +file_path = File.expand_path('input.txt', __dir__) + +input = File.read(file_path).split(""\n\n"").map { |line| line.split(""\n"").map(&:chars) } + + +keys = input.select { |line| line.first.all?{ |f| f == ""."" } && line.last.all?{ |f| f == ""#"" } }.map { |line| line.first(6).transpose.map { |line| line.count { |l| l == ""#""} } } +locks = input.select { |line| line.first.all?{ |f| f == ""#"" } && line.last.all?{ |f| f == ""."" } }.map { |line| line.last(6).transpose.map { |line| line.count { |l| l == ""#""} } } + +cnt = 0 + +keys.each do |key| + locks.each do |lock| + match = true + key.each_with_index do |line, i| + if line + lock[i] > 5 + match = false + break + end + end + + cnt += 1 if match + end +end + +puts cnt",ruby