,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. 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 parseInput(): input = [] with open('input.txt', 'r') as file: tmp = file.read().splitlines() tmp2 = [i.split(' ') for i in tmp] for item in tmp2: input.append([int(i) for i in item]) return input if __name__ == ""__main__"": input = parseInput() safe = 0 for item in input: tmpSafe = True increasing = item[1] >= item[0] for i in range(len(item) - 1): diff = item[i + 1] - item[i] if increasing and diff <= 0: tmpSafe = False break if not increasing and diff >= 0: tmpSafe = False break if 0 < abs(diff) > 3: tmpSafe = False break if tmpSafe: safe += 1 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. 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,"import sys input_path = sys.argv[1] if len(sys.argv) > 1 else ""input.txt"" def solve(input): with open(input) as f: lines = f.read().splitlines() L = [list(map(int, line.split("" ""))) for line in lines] # L = [[int(l) for l in line.split("" "")] for line in lines] counter = 0 for l in L: print(f""Evaluating {l}"") skip = False # decreasing if l[0] > l[1]: for i in range(len(l) - 1): if l[i] - l[i + 1] > 3 or l[i] < l[i + 1] or l[i] == l[i + 1]: skip = True break # increasing elif l[0] < l[1]: for i in range(len(l) - 1): if l[i + 1] - l[i] > 3 or l[i] > l[i + 1] or l[i] == l[i + 1]: skip = True break else: continue if skip: continue print(""Safe"") counter += 1 print(counter) 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. 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,"l = [list(map(int,x.split())) for x in open(""i.txt"")] print(sum(any(all(d 1 else ""input.txt"" def solve(input): with open(input) as f: lines = f.read().splitlines() L = [list(map(int, line.split("" ""))) for line in lines] counter = 0 for l in L: inc_dec = l == sorted(l) or l == sorted(l, reverse=True) size_ok = True for i in range(len(l) - 1): if not 0 < abs(l[i] - l[i + 1]) <= 3: size_ok = False if inc_dec and size_ok: counter += 1 print(counter) solve(input_path)",python 4,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,"with open('input.txt', 'r') as file: lines = file.readlines() sum = 0 for line in lines: A = [int(x) for x in line.split()] ascending = False valid = True if A[0] < A[1]: ascending = True for i in range(len(A) - 1): if ascending: difference = A[i + 1] - A[i] else: difference = A[i] - A[i + 1] if difference > 3 or difference <= 0: valid = False if valid: sum += 1 print(sum)",python 5,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_safe(levels: list[int]) -> bool: # Calculate the difference between each report differences = [first - second for first, second in zip(levels, levels[1:])] max_difference = 3 return (all(0 < difference <= max_difference for difference in differences) or all(-max_difference <= difference < 0 for difference in differences)) def part1(): with open(""input.txt"") as levels: safe_reports = 0 for level in levels: if is_safe(list(map(int, level.split()))): safe_reports += 1 print(safe_reports) def part2(): with open(""input.txt"") as levels: safe_reports = 0 for level in levels: level = list(map(int, level.split())) for i in range(len(level)): if is_safe(level[:i] + level[i + 1:]): print(level[:i] + level[i + 1:]) safe_reports += 1 break print(safe_reports) part2()",python 6,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): result = all(y < z for y,z in zip(x, x[1:])) return result def if_dsc(x): result = all (y > z for y,z in zip(x, x[1:])) return result def if_asc_morethan3(x): result = all(y > z - 4 for y,z in zip(x,x[1:])) return result def if_dsc_morethan3(x): result = all(y < z + 4 for y, z in zip(x, x[1:])) return result input = [list(map(int,x.split("" ""))) for x in open(""input2.txt"", ""r"").read().splitlines()] safe = 0 for x in input: 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 if dsc: dsc3 = if_dsc_morethan3(x) if dsc3: safe+=1 is_safe +=1 if is_safe == 0: list_safe = 0 for i in range(len(x)): list = x[:i] + x[i+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 elif list_dsc: list_dsc3 = if_dsc_morethan3(list) if list_dsc3: list_safe +=1 if list_safe > 0: safe+=1 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. 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,"import sys import logging # logging.basicConfig(,level=sys.argv[2]) input_path = sys.argv[1] if len(sys.argv) > 1 else ""input.txt"" def is_ok(lst): inc_dec = lst == sorted(lst) or lst == sorted(lst, reverse=True) size_ok = True for i in range(len(lst) - 1): if not 0 < abs(lst[i] - lst[i + 1]) <= 3: size_ok = False if inc_dec and size_ok: return True def solve(input_path: str): with open(input_path) as f: lines = f.read().splitlines() L = [list(map(int, line.split("" ""))) for line in lines] counter = 0 for idx, l in enumerate(L): logging.info(f""Evaluating {l}"") logging.error(f""there was an error {idx}: {l}"") if is_ok(l): counter += 1 else: for i in range(len(l)): tmp = l.copy() tmp.pop(i) if is_ok(tmp): counter += 1 break print(counter) 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. 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,"count = 0 def safe(levels): # Check if the sequence is either all increasing or all decreasing if all(levels[i] < levels[i + 1] for i in range(len(levels) - 1)): # Increasing diffs = [levels[i + 1] - levels[i] for i in range(len(levels) - 1)] elif all(levels[i] > levels[i + 1] for i in range(len(levels) - 1)): # Decreasing diffs = [levels[i] - levels[i + 1] for i in range(len(levels) - 1)] else: return False # Mixed increasing and decreasing, not allowed return all(1 <= x <= 3 for x in diffs) # Check if diffs are between 1 and 3 # Open and process the input file with open('input.txt', 'r') as file: for report in file: levels = list(map(int, report.split())) # Check if the report is safe without modification if safe(levels): count += 1 continue # Try removing one level and check if the modified report is safe for index in range(len(levels)): modified_levels = levels[:index] + levels[index+1:] if safe(modified_levels): count += 1 break 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. 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 check_sequence(numbers): nums = [int(x) for x in numbers.split()] # First check if sequence is valid as is if is_valid_sequence(nums): return True # Try removing one number at a time for i in range(len(nums)): test_nums = nums[:i] + nums[i+1:] if is_valid_sequence(test_nums): return True return False def is_valid_sequence(nums): if len(nums) < 2: return True diffs = [nums[i+1] - nums[i] for i in range(len(nums)-1)] # Check if all differences are within -3 to 3 if any(abs(d) > 3 for d in diffs): return False # Check if sequence is strictly increasing or decreasing return all(d > 0 for d in diffs) or all(d < 0 for d in diffs) # Read the file and count valid sequences valid_count = 0 with open('02.input', 'r') as file: for line in file: line = line.strip() if check_sequence(line): print(line) valid_count += 1 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. 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 parseInput(): left = [] right = [] with open('input.txt', 'r') as file: input = file.read().splitlines() for line in input: split = line.split("" "") left.append(int(split[0])) right.append(int(split[1])) return left, right def sort(arr: list): for i in range(len(arr)): for j in range(i, len(arr)): if arr[j] < arr[i]: arr[i], arr[j] = arr[j], arr[i] return arr if __name__ == ""__main__"": left, right = parseInput() left = sort(left) right = sort(right) # print(left) # print(right) 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 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. 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 = sorted(a) sorted_b = sorted(b) d = 0 for i in range(len(sorted_a)): d += abs(sorted_a[i] - sorted_b[i]) return d def read_input_file(file_name): a = [] b = [] with open(file_name, ""r"") as file: for line in file: values = line.strip().split() if len(values) == 2: a.append(int(values[0])) b.append(int(values[1])) return a, b def main(): d = 0 a, b = read_input_file('input2.txt') print(find_min_diff(a, b)) 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. 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,"input = open(""day_01\input.txt"", ""r"") distance = 0 left_list = [] right_list = [] for line in input: values = [x for x in line.strip().split()] left_list += [int(values[0])] right_list += [int(values[1])] left_list.sort() 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 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. 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 read_input(file_path: str) -> list[tuple[int, int]]: """""" Reads a file and returns its contents as a list of tuples of integers. Args: file_path (str): The path to the input file. Returns: list of tuple of int: A list where each element is a tuple of integers representing a line in the file. """""" with open(file_path) as f: return [tuple(map(int, line.split())) for line in f] def calculate_sum_of_differences(pairs: list[tuple[int, int]]) -> int: """""" Calculate the sum of absolute differences between corresponding elements of two lists derived from pairs of numbers. Args: pairs (list of tuple): A list of tuples where each tuple contains two numbers. Returns: int: The sum of absolute differences between corresponding elements of the two sorted lists derived from the input pairs. """""" list1, list2 = zip(*pairs) list1, list2 = sorted(list1), sorted(list2) return sum(abs(a - b) for a, b in zip(list1, list2)) if __name__ == ""__main__"": input_file = 'input.txt' pairs = read_input(input_file) result = calculate_sum_of_differences(pairs) 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. 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,"with open(""AdventOfCode D-1 input.txt"", ""r"") as file: content = file.read() lines = content.splitlines() liste_1 = [] liste_2 = [] for i in range(len(lines)): mots = lines[i].split() liste_1.append(int(mots[0])) liste_2.append(int(mots[1])) liste_paires = [] index = 0 while liste_1 != []: liste_paires.append([]) minimum1 = min(liste_1) liste_paires[index].append(minimum1) minimum2 = min(liste_2) liste_paires[index].append(minimum2) liste_1.remove(minimum1) liste_2.remove(minimum2) index += 1 total = 0 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 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. 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 for left_element in left: score += left_element * num_times_in_list(left_element, right) return score def num_times_in_list(number, right_list): num_times = 0 for element in right_list: if number == element: num_times += 1 return num_times def build_lists(contents): left = [] right = [] for line in contents.split('\n'): if line: le, re = line.split() left.append(int(le)) right.append(int(re)) return left, right if __name__ == '__main__': with open('1/day_1_input.txt', 'r') as f: contents = f.read() left, right = build_lists(contents) score = calculate_similarity_score(left, right) 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. 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,"leftNums, rightNums = [], [] with open('input.txt') as input: while line := input.readline().strip(): left, right = line.split() leftNums.append(int(left.strip())) rightNums.append(int(right.strip())) total = 0 for i in range(len(leftNums)): total += leftNums[i] * rightNums.count(leftNums[i]) 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. 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,"import re import heapq from collections import Counter f = open('day1.txt', 'r') list1 = [] list2 = [] for line in f: splitLine = re.split(r""\s+"", line.strip()) list1.append(int(splitLine[0])) list2.append(int(splitLine[1])) list2Count = Counter(list2) similarityScore = 0 for num in list1: if num in list2Count: similarityScore += num * list2Count[num] 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. 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,"from collections import defaultdict with open(""day_01.in"") as fin: data = fin.read() ans = 0 a = [] b = [] for line in data.strip().split(""\n""): nums = [int(i) for i in line.split("" "")] a.append(nums[0]) b.append(nums[1]) counts = defaultdict(int) for x in b: counts[x] += 1 for x in a: ans += x * counts[x] 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. 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,"input = open(""Day 1\input.txt"", ""r"") list1 = [] list2 = [] for line in input: nums = line.split("" "") list1.append(int(nums[0])) list2.append(int(nums[-1])) list1.sort() list2.sort() total = 0 for i in range(len(list1)): num1 = list1[i] simscore = 0 for j in range(len(list2)): num2 = list2[j] if num2 == num1: simscore+=1 if num2 > num1: break total+= (num1*simscore) 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. 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,"import re def runOps(ops: str) -> int: # I am not proud of this ew = ops[4:-1].split(',') return int(ew[0]) * int(ew[1]) def part1(): with open(""./input.txt"") as f: pattern = re.compile(""mul\\(\\d+,\\d+\\)"") ops = re.findall(pattern, f.read()) sum: int = 0 for o in ops: sum += runOps(o) print(sum) def part2(): with open(""./input.txt"") as f: pattern = re.compile(""do\\(\\)|don't\\(\\)|mul\\(\\d+,\\d+\\)"") ops = re.findall(pattern, f.read()) do: bool = True sum: int = 0 for op in ops: if op == ""don't()"": do = False continue elif op == 'do()': do = True continue if do: sum += runOps(op) print(sum) 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. 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/python3 import re with open(""input.txt"") as file: instructions_cor = file.read() instructions = re.findall(r""mul\(([0-9]+,[0-9]+)\)"", instructions_cor) 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 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. 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,"import re def read_input_file(file_name): a = [] with open(file_name, ""r"") as file: for line in file: values = line.strip().split() a.append(values) return a def main(): max = 0 text = read_input_file('input.txt') pattern = r""mul\((\d+),(\d+)\)"" for line in text: matches = re.findall(pattern, ''.join(line)) # print(''.join(line)) for match in matches: max = max + (int(match[0]) * int(match[1])) print(""max"", max) 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. 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,"import re with open('input.txt', 'r') as file: input = file.read() pattern = r""mul\(\d{1,3},\d{1,3}\)"" matches = re.findall(pattern, input) sum = 0 for match in matches: sum += eval(match.replace(""mul("", """").replace("")"", """").replace("","", ""*"")) 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. 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,"import re import sys input_path = sys.argv[1] if len(sys.argv) > 1 else ""input.txt"" with open(input_path) as f: text = f.read() pattern = r""mul\(\d+,\d+\)"" matches = re.findall(pattern, text) p2 = r""\d+"" # print(matches) result = 0 for match in matches: nums = re.findall(p2, match) result += int(nums[0]) * int(nums[1]) 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. 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,"import re with open(""day3.txt"", ""r"") as f: data = f.read().splitlines() pattern = r""mul\((\d+),(\d+)\)|do\(\)|don't\(\)"" sum = 0 current = 1 for row in data: match = re.finditer( pattern, row, ) for mul in match: command = mul.group(0) if command == ""do()"": current = 1 elif command == ""don't()"": current = 0 else: sum += int(mul.group(1)) * int(mul.group(2)) * current 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. 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,"from re import findall with open(""input.txt"") as input_file: input_text = input_file.read() total = 0 do = True for res in findall(r""mul\((\d+),(\d+)\)|(don't\(\))|(do\(\))"", input_text): if do and res[0]: total += int(res[0]) * int(res[1]) elif do and res[2]: do = False elif (not do) and res[3]: do = True 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. 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,"import re def sumInstructions(instructions): return sum([int(x) * int(y) for x, y in instructions]) def getTuples(instructions): return re.findall(r'mul\(([0-9]{1,3}),([0-9]{1,3})\)', instructions) def main(): total = 0 with open('input.txt') as input: line = input.read() split = re.split(r'don\'t\(\)', line) print(len(split)) # always starts enabled total += sumInstructions(getTuples(split.pop(0))) for block in split: instructions = re.split(r'do\(\)', block) # ignore the don't block instructions.pop(0) for i in instructions: total += sumInstructions(getTuples(i)) print(f""total: {total}"") if __name__ == ""__main__"": 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. 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,"import re from functools import reduce pattern = r'mul\(\d{1,3},\d{1,3}\)|do\(\)|don\'t\(\)' num_pattern = r'\d{1,3}' with open('input.txt', 'r') as f: data = f.read() print(data) matches = re.findall(pattern, data) res = 0 doCompute = True for match in matches: print(match) if match.startswith('don'): doCompute = False print(""Disabled"") elif match.startswith('do'): doCompute = True print(""Enabled"") else: if doCompute: nums = re.findall(num_pattern, match) res += reduce(lambda x, y: int(x) * int(y), nums) 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. 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,"import re with open('input.txt', 'r') as file: input = file.read() do_pattern = r""do\(\)"" dont_pattern = r""don't\(\)"" do_matches = re.finditer(do_pattern, input) dont_matches = re.finditer(dont_pattern, input) do_indexes = [x.start() for x in do_matches] dont_indexes = [x.start() for x in dont_matches] do_indexes.append(0) mul_pattern = r""mul\(\d{1,3},\d{1,3}\)"" mul_matches = re.finditer(mul_pattern, input) sum = 0 for match in mul_matches: mul_start = match.start() largest_do = 0 largest_dont = 0 for do_index in do_indexes: if do_index < mul_start and do_index > largest_do: largest_do = do_index for dont_index in dont_indexes: if dont_index < mul_start and dont_index > largest_dont: largest_dont = dont_index if largest_do >= largest_dont: sum += eval(match.group().replace(""mul("", """").replace("")"", """").replace("","", ""*"")) 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! 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): count = 0 for dx, dy in DIRECTIONS: if all( 0 <= x + i * dx < width and 0 <= y + i * dy < height and words[x + i * dx][y + i * dy] == letter for i, letter in enumerate(""MAS"", start=1) ): count += 1 return count def main(): result = 0 for x in range(width): for y in range(height): if words[x][y] == 'X': result += count_xmas(x, y) print(f'{result=}') with open(""04_input.txt"", ""r"") as f: words = [list(c) for c in [line.strip() for line in f.readlines()]] width = len(words[0]) height = len(words) 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! 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,"from typing import List import pprint INPUT_FILE: str = ""input.txt"" def readInput() -> List[List[str]]: with open(INPUT_FILE, 'r') as f: lines = f.readlines() return [list(line.strip()) for line in lines] def search2D(grid, row, col, word): # Directions: right, down, left, up, diagonal down-right, diagonal down-left, diagonal up-right, diagonal up-left x = [0, 1, 0, -1, 1, 1, -1, -1] y = [1, 0, -1, 0, 1, -1, 1, -1] lenWord = len(word) count = 0 for dir in range(8): k = 0 currX, currY = row, col while k < lenWord: if (0 <= currX < len(grid)) and (0 <= currY < len(grid[0])) and (grid[currX][currY] == word[k]): currX += x[dir] currY += y[dir] k += 1 else: break if k == lenWord: count += 1 return count def searchWord(grid, word): m = len(grid) n = len(grid[0]) total_count = 0 for row in range(m): for col in range(n): total_count += search2D(grid, row, col, word) return total_count def main(): input = readInput() word = ""XMAS"" # pprint.pprint(input) result = searchWord(input, word) pprint.pprint(result) if __name__ == ""__main__"": 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! 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,"with open(""./day_04.in"") as fin: lines = fin.read().strip().split(""\n"") n = len(lines) m = len(lines[0]) # Generate all directions dd = [] for dx in range(-1, 2): for dy in range(-1, 2): if dx != 0 or dy != 0: dd.append((dx, dy)) # dd = [(-1, -1), (-1, 0), (-1, 1), # (0, -1), (0, 1), # (1, -1), (1, 0), (1, 1)] def has_xmas(i, j, d): dx, dy = d for k, x in enumerate(""XMAS""): ii = i + k * dx jj = j + k * dy if not (0 <= ii < n and 0 <= jj < m): return False if lines[ii][jj] != x: return False return True # Count up every cell and every direction ans = 0 for i in range(n): for j in range(m): for d in dd: ans += has_xmas(i, j, d) 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! 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,"import time def solve_part_1(text: str): word = ""XMAS"" matrix = [ [x for x in line.strip()] for line in text.splitlines() if line.strip() != """" ] rows, cols = len(matrix), len(matrix[0]) word_length = len(word) directions = [ (0, 1), # Right (1, 0), # Down (0, -1), # Left (-1, 0), # Up (1, 1), # Diagonal down-right (1, -1), # Diagonal down-left (-1, 1), # Diagonal up-right (-1, -1), # Diagonal up-left ] def is_word_at(x, y, dx, dy): for i in range(word_length): nx, ny = x + i * dx, y + i * dy if not (0 <= nx < rows and 0 <= ny < cols) or matrix[nx][ny] != word[i]: return False return True count = 0 for x in range(rows): for y in range(cols): for dx, dy in directions: if is_word_at(x, y, dx, dy): count += 1 return count def solve_part_2(text: str): matrix = [ [x for x in line.strip()] for line in text.splitlines() if line.strip() != """" ] rows, cols = len(matrix), len(matrix[0]) count = 0 def is_valid_combination(x, y): if y < 1 or y > cols - 2 or x < 1 or x >= rows - 2: return False tl = matrix[x - 1][y - 1] tr = matrix[x - 1][y + 1] bl = matrix[x + 1][y - 1] br = matrix[x + 1][y + 1] tl_br_valid = tl in {""M"", ""S""} and br in {""M"", ""S""} and tl != br tr_bl_valid = tr in {""M"", ""S""} and bl in {""M"", ""S""} and tr != bl return tl_br_valid and tr_bl_valid count = 0 for x in range(rows): for y in range(cols): if matrix[x][y] == ""A"": # Only check around 'A' if is_valid_combination(x, y): count += 1 return count if __name__ == ""__main__"": with open(""input.txt"", ""r"") as f: quiz_input = f.read() start = time.time() p_1_solution = int(solve_part_1(quiz_input)) middle = time.time() print(f""Part 1: {p_1_solution} (took {(middle - start) * 1000:.3f}ms)"") p_2_solution = int(solve_part_2(quiz_input)) end = time.time() print(f""Part 2: {p_2_solution} (took {(end - middle) * 1000:.3f}ms)"")",python 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! 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,"from re import findall with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() num_rows = len(input_text) num_cols = len(input_text[0]) total = 0 # Rows for row in input_text: total += len(findall(r""XMAS"", row)) total += len(findall(r""XMAS"", row[::-1])) # Columns for col_idx in range(num_cols): col = """".join([input_text[row_idx][col_idx] for row_idx in range(num_rows)]) total += len(findall(r""XMAS"", col)) total += len(findall(r""XMAS"", col[::-1])) # NE/SW Diagonals for idx_sum in range(num_rows + num_cols - 1): diagonal = """".join( [ input_text[row_idx][idx_sum - row_idx] for row_idx in range( max(0, idx_sum - num_cols + 1), min(num_rows, idx_sum + 1) ) ] ) total += len(findall(r""XMAS"", diagonal)) total += len(findall(r""XMAS"", diagonal[::-1])) # NW/SE Diagonals for idx_diff in range(-num_cols + 1, num_rows): diagonal = """".join( [ input_text[row_idx][row_idx - idx_diff] for row_idx in range(max(0, idx_diff), min(num_rows, num_cols + idx_diff)) ] ) total += len(findall(r""XMAS"", diagonal)) total += len(findall(r""XMAS"", diagonal[::-1])) 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! 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 = ""data.txt"" WORD = ""MMASS"" def main(): matrix = file_to_matrix(FNAME) print(count_word(matrix, WORD)) def file_to_matrix(fname: str) -> list[list]: out = [] fopen = open(fname, ""r"") for line in fopen: out.append([c for c in line if c != ""\n""]) return out def count_word(matrix: list[list], word) -> int: count = 0 len_matrix = len(matrix) for i in range(len_matrix): for j in range(len_matrix): count += count_word_for_pos(matrix, (i,j), word) return count def count_word_for_pos(matrix: list[list], pos: tuple[int, int], word: str) -> int: count = 0 if pos[0] < 1 or pos[0] > len(matrix)-2 or pos[1] < 1 or pos[1] > len(matrix)-2: return 0 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)],] for pattern in patterns: s = """".join([matrix[pos[0]+p[0]][pos[1]+p[1]] for p in pattern]) if s == word: return 1 return count if __name__ == ""__main__"": 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! 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,"template = [ ""S..S..S"", "".A.A.A."", ""..MMM.."" ""SAMXMAS"", ""..MMM.."" "".A.A.A."", ""S..S..S"", ] def find_xmas(lines: str) -> int: total = 0 for row in range(len(lines)): for col in range(len(lines[row])): if lines[row][col] == ""X"": # Horizontal if col + 1 < len(lines[row]) and col + 2 < len(lines[row]) and col + 3 < len(lines[row]): total += lines[row][col+1] == ""M"" and lines[row][col+2] == ""A"" and lines[row][col+3] == ""S"" # Horizontal reverse if col - 1 >= 0 and col - 2 >= 0 and col - 3 >= 0: total += lines[row][col-1] == ""M"" and lines[row][col-2] == ""A"" and lines[row][col-3] == ""S"" # Vertical if row + 1 < len(lines) and row + 2 < len(lines) and row + 3 < len(lines): total += lines[row+1][col] == ""M"" and lines[row+2][col] == ""A"" and lines[row+3][col] == ""S"" # Vertical reverse if row - 1 >= 0 and row - 2 >= 0 and row - 3 >= 0: total += lines[row-1][col] == ""M"" and lines[row-2][col] == ""A"" and lines[row-3][col] == ""S"" # Diagonal if row + 1 < len(lines) and row + 2 < len(lines) and row + 3 < len(lines) and col + 1 < len(lines[row]) and col + 2 < len(lines[row]) and col + 3 < len(lines[row]): total += lines[row+1][col+1] == ""M"" and lines[row+2][col+2] == ""A"" and lines[row+3][col+3] == ""S"" # Diagonal reverse if row - 1 >= 0 and row - 2 >= 0 and row - 3 >= 0 and col - 1 >= 0 and col - 2 >= 0 and col - 3 >= 0: total += lines[row-1][col-1] == ""M"" and lines[row-2][col-2] == ""A"" and lines[row-3][col-3] == ""S"" # Diagonal reverse if row - 1 >= 0 and row - 2 >= 0 and row - 3 >= 0 and col + 1 < len(lines[row]) and col + 2 < len(lines[row]) and col + 3 < len(lines[row]): total += lines[row-1][col+1] == ""M"" and lines[row-2][col+2] == ""A"" and lines[row-3][col+3] == ""S"" # Diagonal reverse if row + 1 < len(lines) and row + 2 < len(lines) and row + 3 < len(lines) and col - 1 >= 0 and col - 2 >= 0 and col - 3 >= 0: total += lines[row+1][col-1] == ""M"" and lines[row+2][col-2] == ""A"" and lines[row+3][col-3] == ""S"" return total def find_x_mas(lines: str) -> int: total = 0 for row in range(len(lines)): for col in range(len(lines[row])): if lines[row][col] == ""A"": # Diagonal if row + 1 < len(lines) and row - 1 >= 0 and col + 1 < len(lines[row]) and col - 1 >= 0: total += (((lines[row+1][col+1] == ""M"" and lines[row-1][col-1] == ""S"") or (lines[row+1][col+1] == ""S"" and lines[row-1][col-1] == ""M"")) and ((lines[row+1][col-1] == ""M"" and lines[row-1][col+1] == ""S"") or (lines[row+1][col-1] == ""S"" and lines[row-1][col+1] == ""M""))) return total def part1(): input = """" with open(""input.txt"") as f: input = f.readlines() total = find_xmas(input) print(total) def part2(): input = """" with open(""input.txt"") as f: input = f.readlines() total = find_x_mas(input) print(total) 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! 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,"# PROMPT # ----------------------------------------------------------------------------- # 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 # 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. # .......... # Results in 18 X-MASes. # ----------------------------------------------------------------------------- # SOLUTION # ----------------------------------------------------------------------------- def check_xmas_pattern(grid, row, col): """"""Check if there's an X-MAS pattern starting at the given position"""""" rows = len(grid) cols = len(grid[0]) # Check bounds for a 3x3 grid if row + 2 >= rows or col + 2 >= cols: return False # Check both MAS sequences (can be forwards or backwards) def is_mas(a, b, c): return (a == 'M' and b == 'A' and c == 'S') or (a == 'S' and b == 'A' and c == 'M') try: # Check diagonal patterns more safely top_left_to_bottom_right = is_mas( grid[row][col], grid[row+1][col+1], grid[row+2][col+2] ) top_right_to_bottom_left = is_mas( grid[row][col+2], grid[row+1][col+1], grid[row+2][col] ) return top_left_to_bottom_right and top_right_to_bottom_left except IndexError: # If we somehow still get an index error, return False return False def count_xmas_patterns(grid): rows = len(grid) cols = len(grid[0]) count = 0 for r in range(rows-2): # -2 to leave room for 3x3 pattern for c in range(cols-2): if check_xmas_pattern(grid, r, c): count += 1 return count def main(): with open('input.txt', 'r') as f: # Convert each line into a list of characters grid = [list(line.strip()) for line in f.readlines()] result = count_xmas_patterns(grid) print(f""Found {result} X-MAS patterns"") if __name__ == ""__main__"": main() # -----------------------------------------------------------------------------",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! 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,"import re def get_grids_3x3(grid, grid_len): subgrids = [] for row_start in range(grid_len - 2): for col_start in range(grid_len - 2): subgrid = [row[col_start:col_start + 3] for row in grid[row_start:row_start + 3]] subgrids.append(subgrid) return subgrids input = [line.strip() for line in open(""input.txt"", ""r"")] count = 0 grids_3x3 = get_grids_3x3(input, len(input)) for grid in grids_3x3: if re.match(r"".A."", grid[1]): if (re.match(r""M.M"", grid[0]) and re.match(r""S.S"", grid[2])) or \ (re.match(r""S.S"", grid[0]) and re.match(r""M.M"", grid[2])) or \ (re.match(r""S.M"", grid[0]) and re.match(r""S.M"", grid[2])) or \ (re.match(r""M.S"", grid[0]) and re.match(r""M.S"", grid[2])): count+=1 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! 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 = [list(i.strip()) for i in open(""day4input.txt"").readlines()] def get_neighbors(matrix, x, y): rows = len(matrix) cols = len(matrix[0]) neighbors = [] directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0,0), (0, 1), (1, -1), (1, 0), (1, 1)] for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < rows and 0 <= ny < cols: neighbors.append(matrix[nx][ny]) return neighbors def check(matrix): ret = 0 m = matrix.copy() mas = [""MAS"", ""SAM""] d = ''.join([m[0][0], m[1][1], m[2][2]]) a = ''.join([m[0][2], m[1][1], m[2][0]]) ret += 1 if (d in mas and a in mas) else 0 return ret t = 0 for x in range(len(cont)): for y in range(len(cont[x])): if x in [0, 139] or y in [0, 139]: continue if cont[x][y] == ""A"": neighbours = get_neighbors(cont, x,y) matrix = [neighbours[:3], neighbours[3:6], neighbours[6:]] t += check(matrix) 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. 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() def read_puzzle_input(): with open('puzzle-input.txt', 'r') as puzzle_input: for line in puzzle_input: if ""|"" in line: page_pair = line.strip().split(""|"") if page_pair[0] not in page_pairs: page_pairs[page_pair[0]] = [] page_pairs[page_pair[0]].append(page_pair[1]) elif "","" in line: page_updates.append(line.strip().split("","")) def check_page_updates(): total_sum = 0 for page_update in page_updates: middle_number = correct_order(page_update) if middle_number: total_sum += int(middle_number) print(total_sum) def correct_order(page_update): print() print(page_update) for page_index in range(len(page_update)-1, 0, -1): print(page_update[page_index], page_pairs[page_update[page_index]]) for page in page_pairs[page_update[page_index]]: if page in page_update[:page_index]: print(""Error:"", page) return False return page_update[int((len(page_update) - 1) / 2)] if __name__ == ""__main__"": 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. 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,"#!/usr/bin/python3 input_file = ""./sample_input_1.txt"" #input_file = ""./input_1.txt"" # Sample input """""" 47|53 97|13 97|61 ... 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 """""" with open(input_file, ""r"") as data: lines = data.readlines() rules =[] updates = [] for line in lines: # Look for rules then updates if ""|"" in line: rules.append(line.rstrip().split(""|"")) elif "","" in line: updates.append(line.rstrip().split("","")) #print(f""Rules: {rules}"") #print(f""Updates: {updates}"") # Loop through updates correct_updates = [] for update in updates: correct = True # I don't expect it, but the following code fails if any page number is # repeated in an update. Give it a quick check. for page in update: count = update.count(page) if count != 1: print(f""WARNING: update {update} has repeated page {page}"") # Same with updates with even numbers of pages if len(update) %2 == 0: print(f""WARNING: update {update} has an even number ({len(update)}) of pages"") # Identify relevant rules relevant_rules = [] for rule in rules: # I love sets if set(rule) <= set(update): relevant_rules.append(rule) # Check that each rule is obeyed for rule in relevant_rules: if update.index(rule[0]) > update.index(rule[1]): correct = False break # If all rules are obeyed, add the update to the list of correct updates if correct: correct_updates.append(update) print(f""Correct update: {update}"") print(f"" Relevant rules: {relevant_rules}"") print('') # Now go through correct_updates[] and find the middle element tally = [] for update in correct_updates: # All updates should have odd numbers of pages mid_index = (len(update)-1)//2 tally.append(int(update[mid_index])) print(f""Tally: {tally}"") total = sum(tally) 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. 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,"with open('input.txt', 'r') as file: rules = [] lists = [] lines = file.readlines() i = 0 #Write the rule list while len(lines[i]) > 1: rules.append(lines[i].strip().split('|')) i += 1 i += 1 #Write the ""update"" list while i < len(lines): lists.append(lines[i].strip().split(',')) i += 1 rDict = {} #Store all rules per key for key, val in rules: if key not in rDict: rDict[key] = [] rDict[key].append(val) result = [] for x in lists: overlap = [] #Create an unaltered copy of ""update"" x j = x[:] #Create a list of length len(x), which stores the amount of overlap between the rules applied to a key, and each value in the list # # Intuition : If there is a single solution to each update, the value with the most overlap between its ruleset and the ""update"" line must be the first in the solution # Then, delete the value with the most overlap and go through each element in the list # # for i in x: overlap.append(len(set(rDict[i]) & set(x))) outList = [] #Find the index of the value with the most overlap, add that corresponding value to the output list, then remove them from both the overlap list and the input list (the ""update"") for i in range(len(x)): index = overlap.index(max(overlap)) outList.append(x[index]) del overlap[index] del x[index] #If the ordered list is the same as the initial list, the initial list was ordered if j == outList: result.append(outList) #Make a list of the middle numbers midNums = [int(x[len(x)//2]) for x in result] 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. 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,"# PROMPT # ----------------------------------------------------------------------------- # 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. # ----------------------------------------------------------------------------- # SOLUTION # ----------------------------------------------------------------------------- def parse_input(filename): """"""Parse input file into rules and updates."""""" with open(filename) as f: content = f.read().strip().split('\n\n') # Parse rules into a set of tuples (before, after) rules = set() for line in content[0].split('\n'): before, after = map(int, line.split('|')) rules.add((before, after)) # Parse updates into lists of integers updates = [] for line in content[1].split('\n'): update = list(map(int, line.split(','))) updates.append(update) return rules, updates def is_valid_order(update, rules): """"""Check if an update follows all applicable rules."""""" # For each pair of numbers in the update for i in range(len(update)): for j in range(i + 1, len(update)): x, y = update[i], update[j] # If there's a rule saying y should come before x, the order is invalid if (y, x) in rules: return False return True def get_middle_number(update): """"""Get the middle number of an update."""""" return update[len(update) // 2] def main(): rules, updates = parse_input('input.txt') # Find valid updates and their middle numbers middle_sum = 0 for update in updates: if is_valid_order(update, rules): middle_num = get_middle_number(update) middle_sum += middle_num print(f""Valid update: {update}, middle number: {middle_num}"") print(f""\nSum of middle numbers: {middle_sum}"") if __name__ == ""__main__"": main() # -----------------------------------------------------------------------------",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. 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 checkValid(beforeDict, update): for i in range(len(update)): # for each number num = update[i] for j in range(i + 1, len(update)): # for each number after current number if not num in beforeDict: return False val = update[j] # print(f"" -> checking: {beforeDict[num]} <- {val}"") if val not in beforeDict[num]: # if the number is supposed to be before # print("" -> False"") return False # print("" |-> True"") return True with open(""input.txt"", ""r"") as f: lines = f.read().splitlines() updates = [] beforeDict = {} one = True for line in lines: if (line == """"): one = False continue if (one): k,val = line.split(""|"") value = int(val) key = int(k) if not key in beforeDict: beforeDict[key] = [value] else: beforeDict[key].append(value) else: updates.append([int(x) for x in line.split("","")]) for key in beforeDict: beforeDict[key].sort() # print(beforeDict) # print(updates) # verify total = 0 for update in updates: # print(f""Update: {update}"") if checkValid(beforeDict, update): total += update[len(update) // 2] 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. 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,"from collections import defaultdict with open(""./day_05.in"") as fin: raw_rules, updates = fin.read().strip().split(""\n\n"") rules = [] for line in raw_rules.split(""\n""): a, b = line.split(""|"") rules.append((int(a), int(b))) updates = [list(map(int, line.split("",""))) for line in updates.split(""\n"")] def follows_rules(update): idx = {} for i, num in enumerate(update): idx[num] = i for a, b in rules: if a in idx and b in idx and not idx[a] < idx[b]: return False, 0 return True, update[len(update) // 2] # Topological sort, I guess def sort_correctly(update): my_rules = [] for a, b in rules: if not (a in update and b in update): continue my_rules.append((a, b)) indeg = defaultdict(int) for a, b in my_rules: indeg[b] += 1 ans = [] while len(ans) < len(update): for x in update: if x in ans: continue if indeg[x] <= 0: ans.append(x) for a, b in my_rules: if a == x: indeg[b] -= 1 return ans ans = 0 for update in updates: if follows_rules(update)[0]: continue seq = sort_correctly(update) ans += seq[len(seq) // 2] 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. 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,"import math from functools import cmp_to_key def compare(item1, item2): for r in rules: if (item1, item2) == (r[0], r[1]): return -1 if (item2, item1) == (r[0], r[1]): return 1 return 0 rules = [] with open(""05_input.txt"", ""r"") as f: for line in f: if line == '\n': break rules.append([int(i) for i in line.strip().split('|')]) result = 0 for line in f: updates = [int(i) for i in line.strip().split(',')] for u, update in enumerate(updates): for rule in rules: if rule[0] == update: if rule[1] in updates and updates.index(rule[1]) <= u: updates = sorted(updates, key=cmp_to_key(compare)) result += updates[(len(updates) // 2)] break else: continue break 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. 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,"fopen = open(""data.txt"", ""r"") order = dict() updates = [] def fix_update(order, update) -> list[int]: valid = True restricted = [] for i in range(len(update)): for record in restricted: if update[i] in record[1]: valid = False update[i], update[record[0]] = update[record[0]], update[i] break if update[i] in order: restricted.append((i, order[update[i]])) if not valid: update = fix_update(order, update) return update read_mode = 0 for line in fopen: if line == ""\n"": read_mode = 1 continue if read_mode == 0: parts = line.split(""|"") key = int(parts[1]) value = int(parts[0]) if key not in order: order[key] = set() order[key].add(value) if read_mode == 1: parts = line.split("","") updates.append([int(part) for part in parts]) total = 0 for update in updates: valid = True restricted = [] for i in range(len(update)): for record in restricted: if update[i] in record[1]: valid = False break if update[i] in order: restricted.append((i, order[update[i]])) if not valid: update = fix_update(order, update) total += update[len(update)//2] 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. 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,"import functools def is_valid(update, rules): all_pages = set(update) seen_pages = set() for cur in update: if cur in rules: for n in rules[cur]: if n in all_pages and not n in seen_pages: return False seen_pages.add(cur) return True def compare(x, y, rules): if y in rules and x in rules[y]: return -1 if x in rules and y in rules[x]: return 1 return 0 def fix(update, rules): return sorted(update, key=functools.cmp_to_key(lambda x, y: compare(x, y, rules))) with open('input.txt') as f: lines = f.read().splitlines() rules = {} updates = [] for line in lines: if ""|"" in line: x, y = map(int, line.split(""|"")) if not y in rules: rules[y] = [] rules[y] += [x] elif len(line) > 0: updates.append(list(map(int, line.split("","")))) total = 0 for update in updates: if not is_valid(update, rules): fixed = fix(update, rules) total += fixed[len(fixed) // 2] 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. 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,"x = open(""i.txt"").read().split(""\n\n"") d = {} for n in x[0].splitlines(): x1, x2 = map(int, n.split(""|"")) if x1 in d: d[x1].append(x2) else: d[x1] = [x2] updates = [list(map(int, n.split("",""))) for n in x[1].splitlines()] def is_valid(nums): for i, n in enumerate(nums): if n in d: for must_after in d[n]: if must_after in nums: if nums.index(must_after) <= i: return False return True def fix_order(nums): result = list(nums) changed = True while changed: changed = False for i in range(len(result)): if result[i] in d.keys(): for must_after in d[result[i]]: if must_after in result: j = result.index(must_after) if j < i: print(result[i], result[j]) result[i], result[j] = result[j], result[i] changed = True break return result total = 0 for update in updates: if not is_valid(update): print(update) fixed = fix_order(update) print(fixed) middle = fixed[len(fixed)//2] total += middle 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. 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 = len(grid) m = len(grid[0]) guard = (0, 0) dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)] dirIndex = 0 for i in range(n): for j in range(m): if grid[i][j] == ""^"": guard = (i, j) dirIndex = 0 elif grid[i][j] == "">"": guard = (i, j) dirIndex = 1 elif grid[i][j] == ""v"": guard = (i, j) dirIndex = 2 elif grid[i][j] == ""<"": guard = (i, j) dirIndex = 3 next_pos = guard uniquePositions = 0 while next_pos[0] >= 0 and next_pos[0] < n and next_pos[1] >= 0 and next_pos[1] < m: next_pos = (guard[0] + dirs[dirIndex][0], guard[1] + dirs[dirIndex][1]) if next_pos[0] < 0 or next_pos[0] >= n or next_pos[1] < 0 or next_pos[1] >= m: break if grid[guard[0]][guard[1]] != ""X"": uniquePositions += 1 grid[guard[0]] = grid[guard[0]][:guard[1]] + ""X"" + grid[guard[0]][guard[1] + 1:] if grid[next_pos[0]][next_pos[1]] == ""#"": dirIndex = (dirIndex + 1) % 4 next_pos = (guard[0] + dirs[dirIndex][0], guard[1] + dirs[dirIndex][1]) guard = next_pos uniquePositions += 1 grid[guard[0]] = grid[guard[0]][:guard[1]] + ""X"" + grid[guard[0]][guard[1] + 1:] return uniquePositions if __name__ == ""__main__"": # Open file 'day6-1.txt' in read mode with open('day6-1.txt', 'r') as f: # Read each line of the file grid = [] for line in f: grid.append(line.strip()) 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. 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 main(): fopen = open(""data.txt"", ""r"") obstacles = set() visited = set() direction = 0 pos = (0, 0) i = -1 for line in fopen: i += 1 line = line.strip() j = -1 for c in line: j += 1 if c == ""#"": obstacles.add((i, j)) continue if c == ""^"": pos = (i, j) visited.add(pos) max_pos = i while True: if (pos[0] + DIRECTIONS[direction][0], pos[1] + DIRECTIONS[direction][1]) in obstacles: direction = turn_right(direction) pos = (pos[0] + DIRECTIONS[direction][0], pos[1] + DIRECTIONS[direction][1]) if pos[0] < 0 or pos[0] > max_pos or pos[1] < 0 or pos[1] > max_pos: break visited.add(pos) print(len(visited)) def turn_right(x: int) -> int: return (x + 1) % 4 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. 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): if direction == 'v': return (pos[0] + 1, pos[1]) elif direction == '^': return (pos[0] - 1, pos[1]) elif direction == '<': return (pos[0], pos[1] - 1) else: return (pos[0], pos[1] + 1) def get_next_direction(direction): if direction == 'v': return '<' elif direction == '<': return '^' elif direction == '^': return '>' else: return 'v' with open('input.txt') as f: grid = [[c for c in line] for line in f.read().splitlines()] visited = set() n_rows = len(grid) n_cols = len(grid[0]) for i in range(n_rows): for j in range(n_cols): if grid[i][j] in set(['v', '^', '<', '>']): pos = (i, j) direction = grid[i][j] break while 0 <= pos[0] < n_rows and 0 <= pos[1] < n_cols: visited.add(pos) next_pos = get_next_pos(pos, direction) if 0 <= next_pos[0] < n_rows and 0 <= next_pos[1] < n_cols: if grid[next_pos[0]][next_pos[1]] == '#': direction = get_next_direction(direction) next_pos = pos pos = next_pos 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. 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,"from enum import Enum class Direction(Enum): UP = (""^"", (-1, 0)) DOWN = (""v"", (1, 0)) LEFT = (""<"", (0, -1)) RIGHT = ("">"", (0, 1)) def next(self): if self == Direction.UP: return Direction.RIGHT if self == Direction.RIGHT: return Direction.DOWN if self == Direction.DOWN: return Direction.LEFT if self == Direction.LEFT: return Direction.UP def next_pos(self, pos): return (pos[0] + self.value[1][0], pos[1] + self.value[1][1]) def pretty_print(matrix, visited, pos, direction): for i in range(len(matrix)): row = matrix[i] for j in range(len(row)): if (i,j) == pos: print(direction.value[0], end="""") elif (i,j) in visited: print(""X"", end="""") elif row[j]: print(""#"", end="""") else: print(""."", end="""") print() def in_bounds(pos, matrix): return pos[0] >= 0 and pos[0] < len(matrix) and pos[1] >= 0 and pos[1] < len(matrix[0]) with open(""input.txt"", ""r"") as f: lines = f.read().splitlines() matrix = [] visited = set() pos = (0,0) direction = Direction.UP for i in range(len(lines)): line = lines[i] matrix.append([c == ""#"" for c in line]) for j in range(len(line)): if line[j] == ""^"": pos = (i,j) break pretty_print(matrix, visited, pos, direction) while (in_bounds(pos, matrix)): visited.add(pos) next = direction.next_pos(pos) if (not in_bounds(next, matrix)): # if out of bounds, exit break if (matrix[next[0]][next[1]]): # wall direction = direction.next() next = direction.next_pos(pos) pos = next 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. 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,"l = open(""i.txt"").read().strip().splitlines() cord= () for i,x in enumerate(l): for j,c in enumerate(x): if c == ""^"": cord = (i,j) l = [list(line) for line in l] l[cord[0]][cord[1]] = '.' def in_bounds(grid, r, c): return 0 <= r < len(grid) and 0 <= c < len(grid[0]) DIRECTIONS = [(0, 1),(1, 0),(0, -1),(-1, 0)] DIR = 3 visited = [] res = 0 visited.append(cord) res += 1 while True: newx = cord[0] + DIRECTIONS[DIR][0] newy = cord[1] + DIRECTIONS[DIR][1] if not in_bounds(l, newx, newy): break if l[newx][newy] == ""."": if (newx,newy) not in visited: visited.append((newx,newy)) res += 1 elif l[newx][newy] == ""#"": DIR = (DIR + 1) % 4 newx = cord[0] + DIRECTIONS[DIR][0] newy = cord[1] + DIRECTIONS[DIR][1] if l[newx][newy] == ""."" and (newx,newy) not in visited: visited.append((newx,newy)) res += 1 cord = (newx,newy) 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. 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,"import time l = open(""i.txt"").read().strip().splitlines() cord= () for i,x in enumerate(l): for j,c in enumerate(x): if c == ""^"": cord = (i,j) l = [list(line) for line in l] l[cord[0]][cord[1]] = '.' def in_bounds(grid, r, c): return 0 <= r < len(grid) and 0 <= c < len(grid[0]) DIRECTIONS = [(0, 1),(1, 0),(0, -1),(-1, 0)] DIR = 3 visited = [] res = 0 visited.append(cord) res += 1 def simulate_path(grid, cord, DIR): pos = cord dir = DIR visited_states = set() positions = set() while True: state = (pos, dir) if state in visited_states: return True, positions visited_states.add(state) positions.add(pos) newx = pos[0] + DIRECTIONS[dir][0] newy = pos[1] + DIRECTIONS[dir][1] if not in_bounds(grid, newx, newy): return False, positions if grid[newx][newy] == ""#"": dir = (dir + 1) % 4 else: pos = (newx, newy) start_time = time.time() valid_positions = [] for i in range(len(l)): for j in range(len(l[0])): if l[i][j] == ""."" and (i,j) != cord: l[i][j] = ""#"" is_loop, _ = simulate_path(l, cord, DIR) if is_loop: valid_positions.append((i,j)) l[i][j] = ""."" result = len(valid_positions) execution_time = time.time() - start_time print(result) 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. 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,"from enum import IntEnum, auto from dataclasses import dataclass, field in_date = """" with open(""input.txt"") as f: in_date = f.read() class Direction(IntEnum): Up = auto() Right = auto() Down = auto() Left = auto() @dataclass class Position: x: int y: int @dataclass class Guardian: Pos: Position Dir: Direction Walks: set = field(default_factory=lambda: set()) CurrentWalk: list = field(default_factory=lambda: list()) RepeatedWalks: int = 0 LastSteps: list = field(default_factory=lambda: list()) def turn_right(self): if self.Dir == Direction.Up: self.Dir = Direction.Right elif self.Dir == Direction.Right: self.Dir = Direction.Down elif self.Dir == Direction.Down: self.Dir = Direction.Left elif self.Dir == Direction.Left: self.Dir = Direction.Up walk = tuple(self.CurrentWalk) self.CurrentWalk = [] if walk in self.Walks: self.RepeatedWalks += 1 if walk: # to not add empty walks self.Walks.add(walk) def take_step(self): if self.Dir == Direction.Up: self.Pos.x -= 1 elif self.Dir == Direction.Right: self.Pos.y += 1 elif self.Dir == Direction.Down: self.Pos.x += 1 elif self.Dir == Direction.Left: self.Pos.y -= 1 self.CurrentWalk.append((self.Pos.x, self.Pos.y)) return self.Pos def next_pos(self): posable_pos = Position(self.Pos.x, self.Pos.y) if self.Dir == Direction.Up: posable_pos.x -= 1 elif self.Dir == Direction.Right: posable_pos.y += 1 elif self.Dir == Direction.Down: posable_pos.x += 1 elif self.Dir == Direction.Left: posable_pos.y -= 1 return posable_pos def add_step(self, step: str): if len(self.LastSteps) > 99: self.LastSteps = self.LastSteps[1:] self.LastSteps.append(step) class Action(IntEnum): Turn = auto() Step = auto() Out = auto() class Map: def __init__(self, matrix: str): self.map = matrix self.guardian = self.find_guardian() def find_guardian(self): for i, row in enumerate(self.map): for j, col in enumerate(row): if col == ""^"": self.map[i][j] = ""X"" return Guardian(Position(i, j), Direction.Up) def is_open(self, pos: Position): if not self.on_map(pos): return False, Action.Out if self.map[pos.x][pos.y] in {""."", ""X""}: return True, Action.Step else: return False, Action.Turn def on_map(self, pos: Position): return 0 <= pos.x < len(self.map) and 0 <= pos.y < len(self.map[0]) def mark_visited(self, pos: Position): self.map[pos.x][pos.y] = ""X"" def count_visited(self): return sum([1 for row in self.map for col in row if col == ""X""]) def get_spot(self, pos: Position): return self.map[pos.x][pos.y] def __str__(self): return ""\n"".join(["""".join(row) for row in self.map]) def check_loop(m: Map, iter: int, total: int): go_on = True last_action = [] loop_detected = False reason = """" while go_on: curr_pos = m.guardian.Pos next_pos = m.guardian.next_pos() is_open, action = m.is_open(next_pos) if is_open: m.guardian.take_step() m.mark_visited(curr_pos) elif action == Action.Turn: m.guardian.turn_right() elif action == Action.Out: go_on = False if last_action.count(action) > 2: last_action = last_action[1:] last_action.append(action) # does guardian stuck in an infinite loop? if m.guardian.RepeatedWalks >= 2: go_on = False loop_detected = True reason = ""2 repeated walks"" if last_action == [Action.Turn, Action.Turn, Action.Turn]: go_on = False loop_detected = True reason = ""3 turns in a row"" print(f""Iteration {iter}/{total}"") return loop_detected raw_map = in_date.strip().split(""\n"") matrixed = [list(row.strip()) for row in raw_map] possible_obstacles = [] for i in range(len(matrixed)): for j in range(len(matrixed[i])): if matrixed[i][j] == ""."": possible_obstacles.append((i, j)) cont = 0 for i, obs in enumerate(possible_obstacles): matrixed = [list(row.strip()) for row in raw_map] matrixed[obs[0]][obs[1]] = ""#"" m = Map(matrixed) if m.guardian is None: continue if check_loop(m, i + 1, len(possible_obstacles)): cont += 1 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. 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 print_grid(grid): for row in grid: for val in row: print(val, end=' ') print() def get_possible_obstacles(grid): n = len(grid) m = len(grid[0]) gr = 0 gc = 0 dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)] dirIndex = 0 for i in range(n): for j in range(m): if grid[i][j] == ""^"": gr = i gc = j dirIndex = 0 elif grid[i][j] == "">"": gr = i gc = j dirIndex = 1 elif grid[i][j] == ""v"": gr = i gc = j dirIndex = 2 elif grid[i][j] == ""<"": gr = i gc = j dirIndex = 3 numObstacles = 0 for i in range(n): for j in range(m): r, c = gr, gc dirIndex = 0 visited = set() while True: if (r, c, dirIndex) in visited: numObstacles += 1 break visited.add((r, c, dirIndex)) r += dirs[dirIndex][0] c += dirs[dirIndex][1] if not (0<=r# .......... ..#....... .......#.. .......... .#........ ........#. #......... ......#... 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: list[list[str]]) -> set[tuple[int, int]]: """""" Return all positions (row and column indexes) that guard will visit before going out of bounds. """""" # First value signifies row, second value signifies column, # negative values move up/left, and positive down/right directions = [ [-1, 0], [0, 1], [1, 0], [0, -1] ] direction_idx = 0 positions = set() curr_pos = None for row_idx, row in enumerate(data): try: col_idx = row.index(""^"") curr_pos = (row_idx, col_idx) except: pass total_steps = 0 while True: next_row, next_col = curr_pos[0] + directions[direction_idx][0], curr_pos[1] + directions[direction_idx][1] if (next_row < 0 or next_row >= len(data)) or (next_col < 0 or next_col >= len(data[0])): break if data[next_row][next_col] == ""#"": direction_idx = (direction_idx + 1) % 4 continue # Check if guard is stuck in a loop. if total_steps >= 15_000: return set() # TODO: find better way to detect loops # because right now it takes too much time # and with comically huge inputs it may be wrong curr_pos = (next_row, next_col) positions.add(curr_pos) total_steps += 1 return positions def get_obstructions(data: list[list[str]]) -> int: """""" Return amount of positions where obstructions could be put, so that they create a loop. """""" obstructions = 0 for row_idx in range(len(data)): for col_idx in range(len(data[0])): if data[row_idx][col_idx] == ""^"" or data[row_idx][col_idx] == ""#"": continue data[row_idx][col_idx] = ""#"" if len(get_positions(data)) == 0: obstructions += 1 data[row_idx][col_idx] = ""."" return obstructions def main(): puzzle = [] with open(""data.txt"", ""r"", encoding=""UTF-8"") as file: data = file.read() for line in data.split(""\n""): if line == """": break puzzle.append(list(line)) print(f""Amount of distinct positions: {len(get_positions(puzzle))}"") print(f""Amount of possible places for obstructions to put guard in a loop: {get_obstructions(puzzle)}"") if __name__ == ""__main__"": 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. 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): if direction == 'v': return (pos[0] + 1, pos[1]) elif direction == '^': return (pos[0] - 1, pos[1]) elif direction == '<': return (pos[0], pos[1] - 1) else: return (pos[0], pos[1] + 1) def get_next_direction(direction): if direction == 'v': return '<' elif direction == '<': return '^' elif direction == '^': return '>' else: return 'v' def is_loop(grid, pos, direction): n_rows = len(grid) n_cols = len(grid[0]) visited_with_dir = set() while 0 <= pos[0] < n_rows and 0 <= pos[1] < n_cols: if (pos, direction) in visited_with_dir: return True visited_with_dir.add((pos, direction)) next_pos = get_next_pos(pos, direction) if 0 <= next_pos[0] < n_rows and 0 <= next_pos[1] < n_cols: if grid[next_pos[0]][next_pos[1]] == '#': direction = get_next_direction(direction) next_pos = pos pos = next_pos return False with open('input.txt') as f: grid = [[c for c in line] for line in f.read().splitlines()] n_rows = len(grid) n_cols = len(grid[0]) for i in range(n_rows): for j in range(n_cols): if grid[i][j] in set(['v', '^', '<', '>']): pos = (i, j) direction = grid[i][j] break loop_ct = 0 for i in range(n_rows): for j in range(n_cols): if grid[i][j] == '.': grid[i][j] = '#' if is_loop(grid, pos, direction): loop_ct += 1 grid[i][j] = '.' 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? 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,"import math from itertools import product class Solution: def calibration_result(self) ->int: result = 0 dict = {} with open(""test.txt"", 'r') as fd: for line in fd: line_parsed = line.strip().split("":"") key = int(line_parsed[0]) values = list(map(int, line_parsed[1].strip().split())) dict[key] = values for key in dict: result += self.check_calculation(key, dict[key]) return result def check_calculation(self, key: int, values: list[int]) ->int: operators = [""+"", ""*""] result = 0 if sum(values) == key: return key if math.prod(values) == key: return key else: nr_combinations = len(values) - 1 combinations = list(product(operators, repeat=nr_combinations)) for combination in combinations: equation = f""{values[0]}"" for num, op in zip(values[1:], combination): equation += f"" {op} {num}"" result = self.evaluate_left_to_right(equation) if result == key: return key return 0 def evaluate_left_to_right(self, equation) ->int: tokens = equation.split() result = int(tokens[0]) for i in range(1, len(tokens), 2): next_nr = int(tokens[i + 1]) if (tokens[i] == ""+""): result += next_nr if (tokens[i] == ""*""): result *= next_nr return result solution = Solution() 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? 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,"data = [] with open(""i.txt"") as f: for line in f: key, values = line.strip().split("":"") key = int(key) values = [int(x) for x in values.strip().split()] data.append((key,values)) p1 = 0 for res,nums in data: sv = nums[0] def solve(numbers, operators): result = numbers[0] for i in range(len(operators)): if operators[i] == '+': result += numbers[i + 1] else: # '*' result *= numbers[i + 1] return result def gen(numbers): n = len(numbers) - 1 for i in range(2 ** n): operators = [] for j in range(n): operators.append('+' if (i & (1 << j)) else '*') result = solve(numbers, operators) if result == res: return res return 0 p1 += gen(nums) 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? 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 main(): result = 0 with open('input.txt') as infile: for line in infile: answer, terms = line.split(': ') answer = int(answer) terms = [int(x) for x in terms.split(' ')] if find_solution(answer, terms): result += answer print(result) def find_solution(answer, terms): if len(terms) == 2: return (terms[0]+terms[1] == answer) or (terms[0]*terms[1] == answer) return find_solution(answer, [terms[0]+terms[1]]+terms[2:]) \ or find_solution(answer, [terms[0]*terms[1]]+terms[2:]) 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? 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,"f = open(""day7.txt"") def findEquation(numbers, curr_value, curr_index, test_value): if curr_value == test_value and curr_index == len(numbers): return True if curr_index >= len(numbers): return False first = findEquation(numbers, curr_value + numbers[curr_index], curr_index + 1, test_value) second = False if curr_index != 0: second = findEquation(numbers, curr_value * numbers[curr_index], curr_index + 1, test_value) return first or second total = 0 for line in f: split_line = line.split("":"") test_value = int(split_line[0]) numbers = [int(item) for item in split_line[1].strip().split("" "")] if findEquation(numbers, 0, 0, test_value): total += test_value 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? 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(target, sum_so_far, vals): if len(vals) == 0: return target == sum_so_far return is_valid(target, sum_so_far + vals[0], vals[1:]) or is_valid(target, sum_so_far * vals[0], vals[1:]) with open('input.txt') as f: lines = f.read().splitlines() total = 0 for line in lines: test_val = int(line.split("": "")[0]) vals = list(map(int, line.split("": "")[1].split())) if is_valid(test_val, 0, vals): total += test_val 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? 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,"from itertools import product def eval_expr(operations, numbers): numbers = numbers.split("" "") equation = """" for i in range(len(numbers)): equation += numbers[i] if i < len(numbers) - 1: # Add an operator between numbers equation += operations[i % len(operations)] numbers = [int(x) for x in numbers] result = numbers[0] for i in range(len(operations)): operator = operations[i] next_num = numbers[i+1] if operator == '+': result += next_num elif operator == '*': result *= next_num elif operator == ""|"": result = int(str(result)+str(next_num)) return equation, result def generate_operation_list(available_ops, total_ops): return list(product(available_ops,repeat=total_ops)) def satisfy_eq(result, numbers, available_ops): tokens = numbers.split("" "") op_list = generate_operation_list(available_ops, len(tokens)-1) equations = [] #print(tokens) eqn = """" for operations in op_list: equation, curr_res = eval_expr(operations,numbers) #print(f""Equation: {equation}"") #print(f""curr_res: {curr_res}"") if curr_res == int(result): print(equation, result) return 1 return 0 def part1(data): sat = 0 total_sum = 0 for line in data: result = int(line.split("":"")[0]) equation = line.split("":"")[1].strip() #print(equation) if satisfy_eq(result, equation, ""+*""): sat += 1 total_sum += result print(sat) print(total_sum) return def part2(data): sat = 0 total_sum = 0 for line in data: result = int(line.split("":"")[0]) equation = line.split("":"")[1].strip() #print(equation) if satisfy_eq(result, equation, ""+*|""): sat += 1 total_sum += result print(sat) print(total_sum) return if __name__ == ""__main__"": with open(""input.txt"") as f: data = f.readlines() data = [line.strip() for line in data] #part1(data) 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? 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 = [] with open(""i.txt"") as f: for line in f: key, values = line.strip().split("":"") key = int(key) values = [int(x) for x in values.strip().split()] data.append((key,values)) p2 = 0 for res, nums in data: def solve(numbers, operators): result = numbers[0] i = 0 while i < len(operators): if operators[i] == '||': result = int(str(result) + str(numbers[i + 1])) elif operators[i] == '+': result += numbers[i + 1] else: # '*' result *= numbers[i + 1] i += 1 return result def gen(numbers): n = len(numbers) - 1 for i in range(3 ** n): operators = [] temp = i for _ in range(n): op = temp % 3 operators.append('+' if op == 0 else '*' if op == 1 else '||') temp //= 3 result = solve(numbers, operators) if result == res: return res return 0 p2 += gen(nums) 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? 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,"from typing import List, Tuple from part1 import read_input, sum_valid_expressions if __name__ == ""__main__"": expressions = read_input('input.txt') 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? 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/python3 from array import array import sys def calc(operator,ans,target,x): if len(x)>0: #print(f""Calc ({operator},{ans},{target},{x}"") #print(f""{len(x)}: "",end='') if operator=='+': ans = ans + x[0] #print(f""Adding got {ans}"") elif operator=='*': ans = ans * x[0] #print(f""Multiplying got {ans}"") elif operator=='|': ans = int(str(ans) + str(x[0])) #print(f""Concat got {ans}"") else: return ans a1 = calc(""+"",ans,target,x[1:]) a2 = calc(""*"",ans,target,x[1:]) a3 = calc(""|"",ans,target,x[1:]) if (a1==target): return a1 elif (a2==target): return a2 elif (a3==target): return a3 return -1 if len(sys.argv) > 1: # Read filename from CLI if provided input=sys.argv[1] else: input=""input.txt"" height=0 total=0 with open(input,'r') as f: for line in f.readlines(): items=line.split(' ') items[0]=items[0].replace(':','') items = [int(item) for item in items] a1=calc(""+"",items[1],items[0],items[2:]) a2=calc(""*"",items[1],items[0],items[2:]) a3=calc(""|"",items[1],items[0],items[2:]) #print(f""a1 = {a1}"") #print(f""a2 = {a2}"") #print(f""a3 = {a3}"") if (a1 == items[0]): total=total+a1 elif (a2 == items[0]): total=total+a2 elif (a3 == items[0]): total=total+a3 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? 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,"from itertools import product with open(""./day_07.in"") as fin: lines = fin.read().strip().split(""\n"") ans = 0 for i, line in enumerate(lines): parts = line.split() value = int(parts[0][:-1]) nums = list(map(int, parts[1:])) def test(combo): ans = nums[0] for i in range(1, len(nums)): if combo[i-1] == ""+"": ans += nums[i] elif combo[i-1] == ""|"": ans = int(f""{ans}{nums[i]}"") else: ans *= nums[i] return ans for combo in product(""*+|"", repeat=len(nums)-1): if test(combo) == value: print(f""[{i:02}/{len(lines)}] WORKS"", combo, value) ans += value break print(ans)",python 70,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,"import math def main(): antennas = {} grid_width = 0 grid_height = 0 with open('input.txt') as infile: y = 0 for line in infile: x = 0 for c in line.rstrip('\n'): if c != '.': if c in antennas: antennas[c].append((y, x)) else: antennas[c] = [(y, x)] x += 1 y += 1 grid_height = y grid_width = x antinodes = {} for locations in antennas.values(): for i in range(len(locations)-1): for j in range(i+1, len(locations)): y = 2*locations[i][0] - locations[j][0] x = 2*locations[i][1] - locations[j][1] if -1 < y < grid_height and -1 < x < grid_width: antinodes[(y, x)] = True y = 2*locations[j][0] - locations[i][0] x = 2*locations[j][1] - locations[i][1] if -1 < y < grid_height and -1 < x < grid_width: antinodes[(y, x)] = True print(len(antinodes)) main()",python 71,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,"from collections import defaultdict from itertools import combinations with open(""./day_08.in"") as fin: grid = fin.read().strip().split(""\n"") n = len(grid) def in_bounds(x, y): return 0 <= x < n and 0 <= y < n def get_antinodes(a, b): ax, ay = a bx, by = b cx, cy = ax - (bx - ax), ay - (by - ay) dx, dy = bx + (bx - ax), by + (by - ay) if in_bounds(cx, cy): yield (cx, cy) if in_bounds(dx, dy): yield (dx, dy) antinodes = set() all_locs = defaultdict(list) for i in range(n): for j in range(n): if grid[i][j] != ""."": all_locs[grid[i][j]].append((i, j)) for freq in all_locs: locs = all_locs[freq] for a, b in combinations(locs, r=2): for antinode in get_antinodes(a, b): antinodes.add(antinode) 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. 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,"import re from itertools import combinations contents = open(""day08.txt"").readlines() # Part 1 pattern = ""[^.]"" antennas = {} antinodes = [] for i in range(len(contents)): line = contents[i].strip() while re.search(pattern, line): match = re.search(pattern, line) line = line[:match.span()[0]] + '.' + line[match.span()[1]:] try: antennas[match.group()].append([i, match.span()[0]]) except KeyError: antennas[match.group()] = [[i, match.span()[0]]] for key, coordinates in antennas.items(): for start, end in combinations(coordinates, 2): distance = [abs(end[0] - start[0]), abs(end[1] - start[1])] if start[0] < end[0] and start[1] <= end[1]: # Start is above and left (or directly above) relative to End antinode = [start[0] - distance[0], start[1] - distance[1]] antinode2 = [end[0] + distance[0], end[1] + distance[1]] elif start[0] >= end[0] and start[1] <= end[1]: # Start is below and left (or directly below) relative to End antinode = [end[0] - distance[0], end[1] + distance[1]] antinode2 = [start[0] + distance[0], start[1] - distance[1]] elif start[0] >= end[0] and start[1] > end[1]: # Start is below and right relative to End antinode = [end[0] - distance[0], end[1] - distance[1]] antinode2 = [start[0] + distance[0], start[1] + distance[1]] elif start[0] < end[0] and start[1] > end[1]: # Start is above and right relative to End antinode = [start[0] - distance[0], start[1] + distance[1]] antinode2 = [end[0] + distance[0], end[1] - distance[1]] else: # Default catch-all case for any unhandled scenarios antinode = [end[0] + distance[0], end[1] + distance[1]] antinode2 = [start[0] - distance[0], start[1] - distance[1]] for node in [antinode, antinode2]: if 0 <= node[0] < len(contents) and 0 <= node[1] < len(contents[0].strip()): if node not in antinodes: antinodes.append(node) 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. 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(""day_08\input.txt"", ""r"").read().splitlines() column_length = len(input) row_length = len(input[0]) antenna_map = {} antinodes = set() for i in range(column_length): for j in range(row_length): if not input[i][j] == ""."": try: antenna_map[input[i][j]] += [(i, j)] except: antenna_map[input[i][j]] = [(i, j)] for frequency in antenna_map: antennas = antenna_map[frequency] while len(antennas) > 1: test_antenna = antennas[0] for antenna in antennas[1:]: dy = test_antenna[0] - antenna[0] dx = test_antenna[1] - antenna[1] possible_antinodes = [(test_antenna[0] + dy, test_antenna[1] + dx), (antenna[0] - dy, antenna[1] - dx)] for antinode in possible_antinodes: if all(0 <= antinode[i] < dim for i, dim in enumerate([column_length, row_length])): antinodes.add(antinode) del antennas[0] 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. 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,"EMPTY_CELL = '.' ANTINODE_CELL = '#' class Grid: def __init__(self, cells): self.cells = cells self.height = len(cells) self.width = len(cells[0]) if self.height > 0 else 0 self.antinode_locations = set() def __str__(self): return '\n'.join(''.join(row) for row in self.cells) def __repr__(self): return self.__str__() def append_row(self, row): self.cells.append(row) self.height += 1 self.width = len(row) def get_cell(self, row, col): return self.cells[row][col] def is_location_in_grid(self, row, col): return 0 <= row < self.height and 0 <= col < self.width def add_antinode_location(self, row, col): if self.is_location_in_grid(row, col): self.antinode_locations.add((row, col)) if self.cells[row][col] == EMPTY_CELL: self.cells[row][col] = ANTINODE_CELL def read_file(file_path): with open(file_path, 'r') as file: grid = Grid([]) unique_frequencies = set() frequency_locations = {} for line in file: grid.append_row(list(line.strip())) for i, cell in enumerate(grid.cells[-1]): if cell != EMPTY_CELL: unique_frequencies.add(cell) if cell not in frequency_locations: frequency_locations[cell] = [] frequency_locations[cell].append((len(grid.cells) - 1, i)) return grid, unique_frequencies, frequency_locations grid, unique_frequencies, frequency_locations = read_file('input.txt') for frequency in unique_frequencies: for location in frequency_locations[frequency]: for sister_location in frequency_locations[frequency]: if sister_location == location: continue direction_between_locations = (sister_location[0] - location[0], sister_location[1] - location[1]) first_antinode_location = (sister_location[0] + direction_between_locations[0], sister_location[1] + direction_between_locations[1]) second_antinode_location = (location[0] - direction_between_locations[0], location[1] - direction_between_locations[1]) grid.add_antinode_location(first_antinode_location[0], first_antinode_location[1]) grid.add_antinode_location(second_antinode_location[0], second_antinode_location[1]) print(grid) 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. 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,"from itertools import combinations from typing import Set, Tuple import re with open(""day8.input"", ""r"") as file: s = file.read().strip() ans = 0 g = [list(r) for r in s.split(""\n"")] height, width = len(g), len(g[0]) def check(coord: Tuple[int, int]) -> bool: y, x = coord return 0 <= y < height and 0 <= x < width r = r""[a-zA-z0-9]"" uniq: Set[str] = set(re.findall(r, s)) nodes = set() for a in uniq: pos: list[Tuple[int, int]] = [] for y in range(height): for x in range(width): if g[y][x] == a: pos.append((y, x)) pairs = list(combinations(pos, 2)) for (ay, ax), (by, bx) in pairs: node_a = (ay, ax) for i in range(height): node_a = (node_a[0] - (ay - by), node_a[1] - (ax - bx)) if check(node_a) and node_a not in nodes: ans += 1 nodes.add(node_a) node_b = (by, bx) for i in range(width): node_b = (node_b[0] - (by - ay), node_b[1] - (bx - ax)) if check(node_b) and node_b not in nodes: ans += 1 nodes.add(node_b) print(ans)",python 76,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,"EMPTY_CELL = '.' ANTINODE_CELL = '#' class Grid: def __init__(self, cells): self.cells = cells self.height = len(cells) self.width = len(cells[0]) if self.height > 0 else 0 self.antinode_locations = set() def __str__(self): return '\n'.join(''.join(row) for row in self.cells) def __repr__(self): return self.__str__() def append_row(self, row): self.cells.append(row) self.height += 1 self.width = len(row) def get_cell(self, row, col): return self.cells[row][col] def is_location_in_grid(self, row, col): return 0 <= row < self.height and 0 <= col < self.width def add_antinode_location(self, row, col): if self.is_location_in_grid(row, col): self.antinode_locations.add((row, col)) if self.cells[row][col] == EMPTY_CELL: self.cells[row][col] = ANTINODE_CELL def read_file(file_path): with open(file_path, 'r') as file: grid = Grid([]) unique_frequencies = set() frequency_locations = {} for line in file: grid.append_row(list(line.strip())) for i, cell in enumerate(grid.cells[-1]): if cell != EMPTY_CELL: unique_frequencies.add(cell) if cell not in frequency_locations: frequency_locations[cell] = [] frequency_locations[cell].append((len(grid.cells) - 1, i)) return grid, unique_frequencies, frequency_locations grid, unique_frequencies, frequency_locations = read_file('input.txt') for frequency in unique_frequencies: for location in frequency_locations[frequency]: for sister_location in frequency_locations[frequency]: if sister_location == location: continue direction_between_locations = (sister_location[0] - location[0], sister_location[1] - location[1]) antinode_location = (sister_location[0] + direction_between_locations[0], sister_location[1] + direction_between_locations[1]) while grid.is_location_in_grid(*antinode_location): grid.add_antinode_location(*antinode_location) antinode_location = (antinode_location[0] + direction_between_locations[0], antinode_location[1] + direction_between_locations[1]) antinode_location = (location[0] - direction_between_locations[0], location[1] - direction_between_locations[1]) while grid.is_location_in_grid(*antinode_location): grid.add_antinode_location(*antinode_location) antinode_location = (antinode_location[0] - direction_between_locations[0], antinode_location[1] - direction_between_locations[1]) grid.add_antinode_location(*location) print(grid) 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. 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,"f = open(""input.txt"", ""r"") space =[[elem for elem in line.strip()] for line in f.readlines()] dictionary = {} for i in range(0, len(space[0])): for j in range(0, len(space)): if space[j][i] == ""."": continue if space[j][i] in dictionary: dictionary[space[j][i]].append((j, i)) else: dictionary[space[j][i]] = [(j, i)] anti_nodes = set() def add_antinodes(arr): global anti_nodes for i in range(len(arr)): for j in range(i+1, len(arr)): d_lines = arr[i][0] - arr[j][0] d_colones = arr[i][1] - arr[j][1] pos1 = (arr[i][0], arr[i][1]) pos2 = (arr[j][0], arr[j][1]) while not(pos1[0] < 0 or pos1[0] >= len(space) or pos1[1] < 0 or pos1[1] >= len(space[0])): anti_nodes.add(pos1) print(f""added {pos1}"") pos1 = (pos1[0] + d_lines, pos1[1] + d_colones) while not(pos2[0] < 0 or pos2[0] >= len(space) or pos2[1] < 0 or pos2[1] >= len(space[0])): anti_nodes.add(pos2) print(f""added {pos2}"") pos2 = (pos2[0] - d_lines, pos2[1] - d_colones) for frequencies in dictionary.values(): print(frequencies) add_antinodes(frequencies) 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. 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,"from collections import defaultdict file = open(""day8.txt"", ""r"") char_to_coord_map = defaultdict(list) i = 0 for line in file: line = line.strip() j = 0 for c in line: if c != '.' and not c.isspace(): char_to_coord_map[c].append((i, j)) j += 1 i += 1 m = i n = j def check_bounds(coord, n, m): x, y = coord if x >= 0 and x < m and y >= 0 and y < n: return True return False def find_antennas(top, bottom, antinodes): if top[0] > bottom[0] or (top[0] == bottom[0] and top[1] < bottom[1]): top, bottom = bottom, top x1, y1 = top x2, y2 = bottom x_diff = x2 - x1 y_diff = y1 - y2 slope = -1 if not y_diff == 0: slope = x_diff / y_diff x_diff = abs(x_diff) y_diff = abs(y_diff) coord1 = None coord2 = None if slope >= 0: coord1 = (x1 - x_diff, y1 + y_diff) while check_bounds(coord1, m, n): antinodes.add(coord1) coord1 = (coord1[0] - x_diff, coord1[1] + y_diff) coord2 = (x2 + x_diff, y2 - y_diff) while check_bounds(coord2, m, n): antinodes.add(coord2) coord2 = (coord2[0] + x_diff, coord2[1] - y_diff) else: coord1 = (x1 - x_diff, y1 - y_diff) while check_bounds(coord1, m, n): antinodes.add(coord1) coord1 = (coord1[0] - x_diff, coord1[1] - y_diff) coord2 = (x2 + x_diff, y2 + y_diff) while check_bounds(coord2, m, n): antinodes.add(coord2) coord2 = (coord2[0] + x_diff, coord2[1] + y_diff) antinodes = set() for key in char_to_coord_map.keys(): coord_list = char_to_coord_map[key] length = len(coord_list) if length > 1: antinodes.update(coord_list) for i in range(length): for j in range(i + 1, length): find_antennas(coord_list[i], coord_list[j], antinodes) print(len(antinodes)) # print(antinodes)",python 79,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,"def read_input(filename): with open(filename, 'r') as f: return [line.strip() for line in f.readlines()] def find_antennas(grid): antennas = {} for y in range(len(grid)): for x in range(len(grid[y])): char = grid[y][x] if char != '.': if char not in antennas: antennas[char] = [] antennas[char].append((x, y)) return antennas antinodes = set() def antinode(an1, an2,n,m): x1, y1 = an1 x2, y2 = an2 newx = x2 + (x2 - x1) newy = y2 + (y2 - y1) antinodes.add((x2,y2)) while newx >= 0 and newx < n and newy >= 0 and newy < m: antinodes.add((newx,newy)) newx += (x2 - x1) newy += (y2 - y1) def solve(filename): grid = read_input(filename) antennas = find_antennas(grid) for a in antennas: antenna = antennas[a] for i in range(len(antenna)): for j in range(i): node1 = antenna[i] node2 = antenna[j] antinode(node1, node2,len(grid),len(grid[0])) antinode(node2, node1,len(grid),len(grid[0])) for i,x in enumerate(grid): for j,c in enumerate(x): if (i,j) in antinodes: print(""#"", end="""") else: print(c,end='') print() return len(antinodes) if __name__ == ""__main__"": res = solve(""i.txt"") 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. 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,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() file_structure = [ (i // 2 if not i % 2 else -1, int(x)) for i, x in enumerate(input_text[0]) ] # File ID -1 means free space buffer = None total = 0 current_index = 0 while file_structure: file_id, length = file_structure.pop(0) if file_id == -1: while length: if not buffer: while file_structure and file_structure[-1][0] == -1: file_structure.pop(-1) if file_structure: buffer = file_structure.pop(-1) else: break if length >= buffer[1]: total += int( buffer[0] * buffer[1] * (current_index + (buffer[1] - 1) / 2) ) current_index += buffer[1] length -= buffer[1] buffer = None else: total += int(buffer[0] * length * (current_index + (length - 1) / 2)) current_index += length buffer = (buffer[0], buffer[1] - length) length = 0 else: total += int(file_id * length * (current_index + (length - 1) / 2)) current_index += length if buffer: total += int(buffer[0] * buffer[1] * (current_index + (buffer[1] - 1) / 2)) 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. 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,"from typing import List from pprint import pprint as pprint def readInput() -> List[List[str]]: with open(""input.txt"", 'r') as f: lines = f.readlines() return [int(n) for n in list(lines[0].strip())] def parseInput(input) -> List: parsed = [] inc = 0 free = False for i in input: for _ in range(i): if free: parsed.append('.') else: parsed.append(inc) if not free: inc += 1 free = not free return parsed def sortInput(input: List) -> List: i, j = 0, len(input) - 1 while i < j: if input[i] != '.': i += 1 continue if input[j] == '.': j -= 1 continue input[i], input[j] = input[j], input[i] i += 1 j -= 1 return input def checksum(input: List) -> int: sum = 0 for idx, i in enumerate(input): if i != ""."": sum += idx * i return sum def main(): input = readInput() parsed_input = parseInput(input) sorted_input = sortInput(parsed_input) print(f'Result: {checksum(sorted_input)}') if __name__ == ""__main__"": 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. 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,"in_date = """" with open(""input.txt"") as f: in_date = f.read() def map_to_blocks(array): blocks = [] for idx, num in enumerate(array): sub_blocks = [] if not idx % 2: # data block sub_blocks = [idx // 2 for _ in range(num)] else: # free block sub_blocks = [None for _ in range(num)] blocks.extend(sub_blocks) return blocks def compress(array): l_idx = 0 r_idx = len(array) - 1 go_on = True while go_on: if l_idx >= r_idx: go_on = False l = array[l_idx] r = array[r_idx] if r == None: r_idx -= 1 continue if l is not None: l_idx += 1 continue array[l_idx], array[r_idx] = array[r_idx], array[l_idx] return array def compute_checksum(array): total = 0 for idx, num in enumerate(array): if num: total += idx * num return total 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 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. 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,"with open(""./day_09.in"") as fin: line = fin.read().strip() def make_filesystem(diskmap): blocks = [] is_file = True id = 0 for x in diskmap: x = int(x) if is_file: blocks += [id] * x id += 1 is_file = False else: blocks += [None] * x is_file = True return blocks filesystem = make_filesystem(line) def move(arr): first_free = 0 while arr[first_free] != None: first_free += 1 i = len(arr) - 1 while arr[i] == None: i -= 1 while i > first_free: arr[first_free] = arr[i] arr[i] = None while arr[i] == None: i -= 1 while arr[first_free] != None: first_free += 1 return arr def checksum(arr): ans = 0 for i, x in enumerate(arr): if x != None: ans += i * x return ans ans = checksum(move(filesystem)) 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. 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,"f = open(""input.txt"", ""r"") data = f.readlines()[0].strip() f.close() def createFile(line): result = [] counter = 0 for i in range(0, len(line)): if i%2 == 0: txt = [] for j in range(0, int(line[i])): txt.append(str(counter)) result.append(txt) counter += 1 else: txt = [] for j in range(0, int(line[i])): txt.append('.') result.append(txt) return result def compressFile(file): right = len(file)-1 left = 0 while left < right: if file[right] != '.': while file[left] != '.': left += 1 if left == right: return file file[left] = file[right] file[right] = '.' right -= 1 return file def calculateCheckSum(compressed): sum = 0 for i in range(len(compressed)): if compressed[i] != ""."": sum += i * int(compressed[i]) return sum # print(data) result = createFile(data) result = [item for sublist in result for item in sublist] # print("""".join(result)) compressed = compressFile(result) # print("""".join(compressed)) 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. 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,"from typing import List from pprint import pprint as pprint class Block: def __init__(self, size: int, num: int, free: bool) -> None: self.size = size self.num = num self.free = free def __str__(self) -> str: if self.free: return f""[Size: {self.size}, Free: {self.free}]"" return f""[Size: {self.size}, ID: {self.num}]"" def readInput() -> List[List[str]]: with open(""input.txt"", 'r') as f: lines = f.readlines() return [int(n) for n in list(lines[0].strip())] def parseInput(input) -> List[Block]: parsed = [] inc = 0 free = False for i in input: parsed.append(Block(i, inc, free)) if not free: inc += 1 free = not free return parsed def sortInput(input: List[Block]) -> List[Block]: i, j = 0, len(input) - 1 while 0 <= j: if not i < j: i = 0 j -= 1 if input[j].free: j -= 1 continue if not input[i].free: i += 1 continue if input[j].size <= input[i].size: if input[j].size == input[i].size: input[i], input[j] = input[j], input[i] else: temp1 = Block(input[i].size - input[j].size, input[i].num, True) temp2 = Block(input[j].size, input[i].num, True) input = input[:i] + [input[j]] + [temp1] + input[i+1:j] + [temp2] + input[j+1:] else: i += 1 continue j -= 1 i = 0 return input def blocksToList(input: List[Block]) -> List: parsed = [] for i in input: for _ in range(i.size): if i.free: parsed.append(""."") else: parsed.append(i.num) return parsed def checksum(input: List) -> int: sum = 0 for idx, i in enumerate(input): if i != ""."": sum += idx * i return sum def main(): input = readInput() parsed_input = parseInput(input) sorted_input = sortInput(parsed_input) list_input = blocksToList(sorted_input) print(f'Result: {checksum(list_input)}') if __name__ == ""__main__"": 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. 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,"def defrag(layout): for index in range(len(layout)-1, -1, -1): item = layout[index] if item[""fileId""] == ""."": continue for s in range(0, index): if layout[s][""fileId""] == ""."": if layout[s][""length""] > item[""length""]: remaining = layout[s][""length""] - item[""length""] layout[index] = layout[s] layout[s] = item layout[index][""length""] = item[""length""] layout.insert(s+1, {""fileId"": ""."", ""length"": remaining}) break elif layout[s][""length""] == item[""length""]: layout[index] = layout[s] layout[s] = item break def checksum(layout) -> int: result = 0 index = 0 for item in layout: if item[""fileId""] != ""."": result += sum((index+i) * item[""fileId""] for i in range(item[""length""])) index += item[""length""] return result def main(): with open(""09_input.txt"", ""r"") as f: disk = list(map(int, f.readline().strip())) layout = [] fileId = 0 isFile = True for d in disk: if isFile: layout.append({""fileId"": fileId, ""length"": d}) fileId += 1 else: layout.append({""fileId"": ""."", ""length"": d}) isFile = not isFile defrag(layout) print(checksum(layout)) if __name__ == ""__main__"": 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. 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,"in_date = """" with open(""input.txt"") as f: in_date = f.read() def map_to_blocks(array): blocks = [] for idx, num in enumerate(array): sub_blocks = [] if not idx % 2: # data block sub_blocks = [idx // 2 for _ in range(num)] else: # free block sub_blocks = [None for _ in range(num)] blocks.extend(sub_blocks) return blocks def find_files(array): files = {} start = 0 for i, item in enumerate(array): if item is None: continue if item not in files: start = i files[item] = ((i + 1 - start), (start, i + 1)) return files def find_free_spaces(array, l_needed, rightest_pos): # sub_arr = array[:rightest_pos] for i in range(rightest_pos): start = i end = i if array[i] is not None: continue for j in range(i, rightest_pos): end = j if array[j] is not None: break if end - start >= l_needed: return start, end return (-1, -1) def compress_by_files(array): all_files = find_files(array) for key in list(all_files.keys())[-1::-1]: f_len, pos = all_files[key] free = find_free_spaces(array, f_len, pos[1]) if free == (-1, -1): continue array[pos[0] : pos[1]], array[free[0] : free[0] + f_len] = ( array[free[0] : free[0] + f_len], array[pos[0] : pos[1]], ) return array def compute_checksum(array): total = 0 for idx, num in enumerate(array): if num: total += idx * num return total 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 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. 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,"f = open(""input.txt"", ""r"") data = f.readlines()[0].strip() f.close() def createFile(line): result = [] counter = 0 for i in range(0, len(line)): if i%2 == 0: txt = [] for j in range(0, int(line[i])): txt.append(str(counter)) result.append(txt) counter += 1 else: txt = [] for j in range(0, int(line[i])): txt.append('.') result.append(txt) return result files = [] free_space = [] result = createFile(data) for i in range(len(result)): if i%2 == 0: files.append(result[i]) else: free_space.append(result[i]) def compressFile(files, free_space): for i in range(len(files)-1, -1, -1): for j in range(i): if free_space[j].count('.') >= len(files[i]): id = free_space[j].index('.') for k in range(len(files[i])) : free_space[j][k+id] = files[i][k] files[i][k] = '.' break def alternate_join(l1, l2): result = [] for i in range(len(l1)): result.append(l1[i]) if i < len(l2): result.append(l2[i]) return result def calculateCheckSum(compressed): sum = 0 for i in range(len(compressed)): if compressed[i] != ""."": sum += i * int(compressed[i]) return sum compressFile(files, free_space) # print(f""files: {files}"") # print(f""free_space: {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 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. 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,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() file_structure = [ (i // 2 if not i % 2 else -1, int(x)) for i, x in enumerate(input_text[0]) ] current_index = len(file_structure) - (1 if file_structure[-1][0] != -1 else 2) while current_index > 0: for idx, (space_id, space_length) in enumerate(file_structure[:current_index]): if space_id == -1 and space_length >= file_structure[current_index][1]: file_structure = ( file_structure[:idx] + [ (-1, 0), file_structure[current_index], (-1, space_length - file_structure[current_index][1]), ] + file_structure[idx + 1 :] ) if current_index + 2 < len(file_structure) - 1: file_structure[current_index + 1] = ( -1, file_structure[current_index + 1][1] + file_structure.pop(current_index + 3)[1] + file_structure.pop(current_index + 2)[1], ) else: file_structure[current_index + 1] = ( -1, file_structure[current_index + 1][1] + file_structure.pop(current_index + 2)[1], ) break else: current_index -= 2 total = 0 idx = 0 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 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. 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,"from collections import deque def read_input(filename): with open(filename) as f: return [[int(x) for x in line.strip()] for line in f] def get_neighbors(grid, x, y): directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # right, down, left, up height, width = len(grid), len(grid[0]) neighbors = [] for dx, dy in directions: new_x, new_y = x + dx, y + dy if (0 <= new_x < height and 0 <= new_y < width): neighbors.append((new_x, new_y)) return neighbors def count_reachable_nines(grid, start_x, start_y): visited = set() reachable_nines = set() queue = deque([(start_x, start_y, 0)]) # (x, y, current_height) while queue: x, y, current_height = queue.popleft() if (x, y) in visited: continue visited.add((x, y)) if grid[x][y] == 9: reachable_nines.add((x, y)) for next_x, next_y in get_neighbors(grid, x, y): if (next_x, next_y) not in visited: if grid[next_x][next_y] == current_height + 1: queue.append((next_x, next_y, grid[next_x][next_y])) return len(reachable_nines) def solve(grid): height, width = len(grid), len(grid[0]) res = 0 for x in range(height): for y in range(width): if grid[x][y] == 0: score = count_reachable_nines(grid, x, y) res += score return res 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 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. 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,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() num_rows = len(input_text) num_cols = len(input_text[0]) topography = {} for row in range(num_rows): for col in range(num_cols): topography[(row, col)] = int(input_text[row][col]) movements = ((1, 0), (-1, 0), (0, 1), (0, -1)) nine_reachable_from = { point: {point} for point, height in topography.items() if height == 9 } for height in range(8, -1, -1): new_nine_reachable_from = {} for nine_point, old_reachable_froms in nine_reachable_from.items(): new_reachable_froms = set() for old_point in old_reachable_froms: for movement in movements: potential_new_point = ( old_point[0] + movement[0], old_point[1] + movement[1], ) if topography.get(potential_new_point) == height: new_reachable_froms.add(potential_new_point) if new_reachable_froms: 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 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. 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,"from collections import deque class Trail: def __init__(self, x, y): self.x = x self.y = y def score(self): seen = set() queue = deque() queue.append(( 0, self.x, self.y, )) while queue: val, x, y = queue.popleft() if x < 0 or y < 0 or x >= xmax or y >= ymax: continue if int(lines[y][x]) != val: continue if val == 9: seen.add((x, y)) continue queue.append((val + 1, x + 1, y)) queue.append((val + 1, x - 1, y)) queue.append((val + 1, x, y + 1)) queue.append((val + 1, x, y - 1)) return len(seen) with open('input.txt') as f: lines = [line.strip() for line in f] xmax = len(lines[0]) ymax = len(lines) score = 0 for yi in range(ymax): for xi in range(xmax): if lines[yi][xi] == '0': score += Trail(xi, yi).score() 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. 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,"file = open(""day10.txt"", ""r"") starts = [] matrix = [] i = 0 for line in file: curr = [] matrix.append(curr) line = line.strip() j = 0 for c in line: num = -1 if c != '.': num = int(c) curr.append(num) if num == 0: starts.append((i, j)) j += 1 i += 1 m = len(matrix) n = len(matrix[0]) directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] def dfs(start, num, visited): if num == 9 and start not in visited: visited.add(start) return 1 i, j = start total = 0 for x, y in directions: newX, newY = i + x, j + y if newX >= 0 and newX < m and newY >= 0 and newY < n and matrix[newX][newY] == num + 1: total += dfs((newX, newY), num + 1, visited) return total trailheads = 0 for start in starts: trailheads += dfs(start, 0, set()) 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. 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,"f = open(""input.txt"", ""r"") data = [[elem for elem in line.strip()] for line in f] f.close() def findTrailHeads(data): trailHeads = [] for i in range(len(data)): for j in range(len(data[i])): if data[i][j] == ""0"": trailHeads.append((i, j)) return trailHeads TrailHeads = findTrailHeads(data) def calculateTrailHeadScore(TrailHead): reachedNines = [] def aux(height, pos): if int(data[pos[0]][pos[1]]) != height: return 0 elif int(data[pos[0]][pos[1]]) == height == 9: if pos not in reachedNines: reachedNines.append(pos) return 1 return 0 else: up = (pos[0] - 1, pos[1]) if pos[0] - 1 >= 0 else pos down = (pos[0] + 1, pos[1]) if pos[0] + 1 < len(data) else pos left = (pos[0], pos[1] - 1) if pos[1] - 1 >= 0 else pos right = (pos[0], pos[1] + 1) if pos[1] + 1 < len(data[pos[0]]) else pos return aux(height + 1, up) + aux(height + 1, down) + aux(height + 1, left) + aux(height + 1, right) return aux(0, TrailHead) score = 0 for trailHead in TrailHeads: score += calculateTrailHeadScore(trailHead) print(f""first trail head score: {calculateTrailHeadScore(TrailHeads[0])}"") print(TrailHeads) 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. 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,"def main(): # cool recursive solution credit to @jonathanpaulson5053 part2 = 0 with open('input.txt', 'r') as file: data = file.read().strip() grid = data.split('\n') rows = len(grid) cols = len(grid[0]) dp = {} def ways(r, c): if grid[r][c] == '0': return 1 if (r, c) in dp: return dp[(r, c)] ans = 0 for dr, dc in [(-1,0), (0,1), (1,0), (0,-1)]: rr = r+dr cc = c+dc if 0<=rr= 0 else pos down = (pos[0] + 1, pos[1]) if pos[0] + 1 < len(data) else pos left = (pos[0], pos[1] - 1) if pos[1] - 1 >= 0 else pos right = (pos[0], pos[1] + 1) if pos[1] + 1 < len(data[pos[0]]) else pos return aux(height + 1, up) + aux(height + 1, down) + aux(height + 1, left) + aux(height + 1, right) return aux(0, TrailHead) score = 0 for trailHead in TrailHeads: score += calculateTrailHeadScore(trailHead) print(f""first trail head score: {calculateTrailHeadScore(TrailHeads[0])}"") print(TrailHeads) 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. 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,"import time file = open(""input.txt"", ""r"") start = time.time() matrix = [] trailheads = [] for line_index, line in enumerate(file.readlines()): matrix.append([]) for column_index, column in enumerate(line.replace(""\n"", """")): elevation = int(column) matrix[line_index].append(elevation) if elevation == 0: trailheads.append((line_index, column_index)) matrix_width = len(matrix[0]) matrix_height = len(matrix) # for line in matrix: # print(line) def get_valid_neighbors(position): y = position[0][0] x = position[0][1] position_elevation = position[1] left_p = (y, x-1) left = None if x == 0 else (left_p, matrix[left_p[0]][left_p[1]]) # left = (None, (left_p, matrix[left_p[0]][left_p[1]]))[x > 0] right_p = (y, x+1) right = None if x == matrix_width-1 else (right_p, matrix[right_p[0]][right_p[1]]) # right = (None, (right_p, matrix[right_p[0]][right_p[1]]))[x < matrix_width-1] up_p = (y-1, x) up = None if y == 0 else (up_p, matrix[up_p[0]][up_p[1]]) # up = (None, (up_p, matrix[up_p[0]][up_p[1]]))[y > 0] down_p = (y+1, x) down = None if y == matrix_height-1 else (down_p, matrix[down_p[0]][down_p[1]]) # down = (None, (down_p, matrix[down_p[0]][down_p[1]]))[y < matrix_height-1] return [x for x in [left, right, up, down] if (x is not None and x[1] == position_elevation + 1)] print(""~~~~~~~~~~RESULT 1~~~~~~~~~~"") def traverse(position): if position[1] == 9: return [position] neighbors = get_valid_neighbors(position) if not neighbors: return [] else: result = [] for traverse_result in [traverse(x) for x in neighbors]: result += traverse_result return result # total_score = 0 # for trailhead in trailheads: # peaks = set() # for trail_end in traverse(((trailhead), 0)): # peaks.add(trail_end[0]) # total_score += len(peaks) # # print(total_score) print(""~~~~~~~~~~RESULT 2~~~~~~~~~~"") def copy_2d_list(two_d_list): new = [] for index_x, x in enumerate(two_d_list): new.append([]) for y in x: new[index_x].append(y) return new def copy_list(list): new = [] for x in list: new.append(x) return new def traverse2(complete, incomplete): updated_complete = copy_2d_list(complete) updated_incomplete = [] for trail in incomplete: last_step = trail[len(trail)-1] if last_step[1] == 9: updated_complete.append(copy_list(trail)) else: neighbors = get_valid_neighbors(last_step) if not neighbors: # no onward paths for this trail, removed from incomplete continue for neighbor in get_valid_neighbors(last_step): updated_incomplete.append(copy_list(trail) + [neighbor]) if not updated_incomplete: return updated_complete return traverse2(updated_complete, updated_incomplete) total_score2 = 0 for trailhead in trailheads: rating = len(traverse2([], [[((trailhead), 0)]])) total_score2 += rating print(total_score2) # Save timestamp end = time.time() print(""~~~~~~~~~~ RUNTIME ~~~~~~~~~~~~~~"") 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. 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,"from collections import deque input_file = 'input.txt' # input_file = 'example.txt' directions = [ (0, 1), (1, 0), (0, -1), (-1, 0), ] def is_inbounds(coords: tuple, arr: list) -> bool: return coords[0] >= 0 and coords[0] < len(arr) and coords[1] >= 0 and coords[1] < len(arr[0]) def bfs(trail_map: list, origin: tuple): queue = deque([origin]) visited = set([origin]) score = 0 while queue: print(queue) row, col = queue.popleft() current_grade = trail_map[row][col] if current_grade == 9: score += 1 continue for d_row, d_col in directions: new_row, new_col = row + d_row, col + d_col if ( is_inbounds((new_row, new_col), trail_map) and trail_map[new_row][new_col] == (current_grade + 1) and (new_row, new_col, (origin[0], origin[1])) not in visited ): queue.append((new_row, new_col)) visited.add((new_row, new_col)) return score with open(input_file, 'r') as file: trail_map = [list(map(int, list(line.strip()))) for line in file] answer = 0 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 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. 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 = ""input"" INPUT = ""test1.in"" grid = [] with open(INPUT, ""r"") as f: lines = f.readlines() for i, line in enumerate(lines): line = line.strip() grid.append([int(c) for c in line]) h = len(grid) w = len(grid[0]) def test(grid, used, x, y, v) -> int: if not (0 <= x < w): return 0 if not (0 <= y < h): return 0 if grid[y][x] != v: return 0 # if used[y][x]: # return 0 # used[y][x] = 1 if v == 9: return 1 res = 0 res += test(grid, used, x + 1, y, v + 1) res += test(grid, used, x - 1, y, v + 1) res += test(grid, used, x, y + 1, v + 1) res += test(grid, used, x, y - 1, v + 1) return res res = 0 for y in range(h): for x in range(w): used = [[0 for _ in range(w)] for _ in range(h)] res += test(grid, used, x, y, 0) # print(x, y, res) # for z in used: # print(z) # print(0) # for z in grid: # print(z) # if res > 0: # exit(0) 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"stones = open('input.txt').read().strip().split(' ') stones = [int(x) for x in stones] def get_next_stones(): for i in range(len(stones)): if stones[i] == 0: stones[i] = 1 elif len(str(stones[i])) % 2 == 0: num = str(stones[i]) # print(num) stones[i] = int(num[:len(num)//2]) stones.append(int(num[len(num)//2:])) else: stones[i] *= 2024 for i in range(25): # print(stones) get_next_stones() print(len(stones))",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def rules(n): if n == 0: return [1] s = str(n) if len(s) % 2 == 0: l = len(s) // 2 return [int(s[:l]), int(s[l:])] return [n * 2024] def calc(stone, blinks): if blinks == 0: return 1 new = rules(stone) return sum(calc(num, blinks - 1) for num in new) res = 0 stones = list(map(int, open('i.txt').read().split())) for stone in stones: res += calc(stone, 25) print(res)",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def blink(stones): newStones = [] for stone in stones: if stone == 0: newStones.append(1) continue n = len(str(stone)) if n % 2 == 0: newStones.append(int(str(stone)[:(n//2)])) newStones.append(int(str(stone)[(n//2):])) continue newStones.append(stone * 2024) return newStones def get_num_stones(stones): for _ in range(25): stones = blink(stones) return len(stones) if __name__ == ""__main__"": # Open file 'day11-1.txt' in read mode with open('day11-1.txt', 'r') as f: stones = [] for line in f: stones = [int(val) for val in line.strip().split()] print(""Number of Stones: "" + str(get_num_stones(stones)))",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def get_next_array(stones): res = [] for stone in stones: if stone == 0: res.append(1) elif len(str(stone)) % 2 == 0: stone_str = str(stone) res.append(int(stone_str[0:len(stone_str)//2])) res.append(int(stone_str[len(stone_str)//2:])) else: res.append(stone * 2024) return res with open('input.txt') as f: stones = [int(s) for s in f.read().split()] for i in range(25): stones = get_next_array(stones) print(len(stones))",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"from functools import cache @cache def blink(value, times): if times == 0: return 1 if value == 0: return blink(1, times - 1) digits = len(str(value)) if digits % 2 == 0: return blink(int(str(value)[:digits // 2]), times - 1) + blink( int(str(value)[digits // 2:]), times - 1) return blink(value * 2024, times - 1) with open(""input.txt"") as file: stones = file.read().strip().split() result = sum([blink(int(stone), 25) for stone in stones]) print(result)",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import cache with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() @cache def stones_created(num, rounds): if rounds == 0: return 1 elif num == 0: return stones_created(1, rounds - 1) elif len(str(num)) % 2 == 0: return stones_created( int(str(num)[: len(str(num)) // 2]), rounds - 1 ) + stones_created(int(str(num)[len(str(num)) // 2 :]), rounds - 1) else: return stones_created(num * 2024, rounds - 1) nums = [int(x) for x in input_text[0].split()] print(sum(stones_created(x, 75) for x in nums))",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import cache @cache def blink(value, times): if times == 0: return 1 if value == 0: return blink(1, times - 1) digits = len(str(value)) if digits % 2 == 0: return blink(int(str(value)[:digits // 2]), times - 1) + blink( int(str(value)[digits // 2:]), times - 1) return blink(value * 2024, times - 1) with open(""input.txt"") as file: stones = file.read().strip().split() result = sum([blink(int(stone), 75) for stone in stones]) print(result)",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import lru_cache def is_even(num): count = 0 a = num while a: a //= 10 count += 1 return count % 2 == 0 @lru_cache(maxsize=1000_000) def check_stone(stone): if stone == 0: return (1, -1) if is_even(stone): s = str(stone) l = s[: len(s) // 2] r = s[len(s) // 2 :] return (int(l), int(r)) return (stone * 2024, -1) in_date = """" with open(""input.txt"") as f: in_date = f.read() init_stones = [int(i) for i in in_date.strip().split()] total_nums = {} for i in init_stones: res = total_nums.get(i, 0) + 1 total_nums[i] = res for iter in range(75): new_total_nums = {} for n, c in total_nums.items(): l, r = check_stone(n) if r != -1: r_count = new_total_nums.get(r, 0) new_total_nums[r] = r_count + (1 * c) l_count = new_total_nums.get(l, 0) new_total_nums[l] = l_count + (1 * c) total_nums = new_total_nums total = sum(total_nums.values()) print(total)",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"from collections import defaultdict import sys sys.setrecursionlimit(2**30) with open(""./day_11.in"") as fin: raw_nums = list(map(int, fin.read().strip().split())) nums = defaultdict(int) for x in raw_nums: nums[x] += 1 def blink(nums: dict): new_nums = defaultdict(int) for x in nums: l = len(str(x)) if x == 0: new_nums[1] += nums[0] elif l % 2 == 0: new_nums[int(str(x)[:l//2])] += nums[x] new_nums[int(str(x)[l//2:])] += nums[x] else: new_nums[x * 2024] += nums[x] return new_nums for i in range(75): nums = blink(nums) ans = 0 for x in nums: ans += nums[x] print(ans)",python 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. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"try: with open(""11/input.txt"", ""r"") as file: data = file.read() except Exception: with open(""input.txt"", ""r"") as file: data = file.read() data = data.split("" "") class Stone: def __init__(self, n, ntimes = 1): self.n = int(n) self.ntimes = ntimes def evolve(self): if self.n == 0: self.n = 1 return [self] elif len(str(self.n)) % 2 == 0: return [Stone(str(self.n)[:len(str(self.n))//2], self.ntimes), Stone(str(self.n)[len(str(self.n))//2:], self.ntimes)] else: self.n = self.n*2024 return [self] def __str__(self): return ""{""+str(self.n)+"",""+str(self.ntimes)+""}"" stones = [] for i in data: stones.append(Stone(i)) blinks = 75 for blink in range(blinks): newstones = [] print(""Blink "", blink) #print("" "".join([x.__str__() for x in stones])) print(len(stones)) for i in range(len(stones)): for stone in stones[i].evolve(): newstones.append(stone) stones = newstones if True: i = -1 while i < len(stones)-1: i = i+1 j = i while j < len(stones)-1: j = j+1 if stones[i].n == stones[j].n: stones[i].ntimes += stones[j].ntimes del stones[j] j = j-1 print(""\n\n"", len(stones)) res = 0 for i in stones: res += i.ntimes print(res)",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"def visit(x, y, visited): area = 1 visited.add((x, y)) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if ((x + dx, y + dy) not in visited and 0 <= x + dx < width and 0 <= y + dy < height and garden[y][x] == garden[y + dy][x + dx]): d_area, _ = visit(x + dx, y + dy, visited) area += d_area return area, visited def perimeter(plot): min_x = min(plot, key=lambda p: p[0])[0] min_y = min(plot, key=lambda p: p[1])[1] max_x = max(plot, key=lambda p: p[0])[0] max_y = max(plot, key=lambda p: p[1])[1] perim = 0 for ray_x in range(min_x , max_x + 1): is_in = False side_count = 0 for ray_y in range(min_y, max_y + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in side_count += 1 perim += side_count for ray_y in range(min_y , max_y + 1): is_in = False side_count = 0 for ray_x in range(min_x, max_x + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in side_count += 1 perim += side_count return perim def main(): visited = set() result = 0 for y, row in enumerate(garden): for x, column in enumerate(row): if (x, y) not in visited: area, v = visit(x, y, set()) perim = perimeter(v) visited.update(v) result += area * perim print(result) with open(""12_input.txt"", ""r"") as f: garden = [line.strip() for line in f.readlines()] width = len(garden[0]) height = len(garden) if __name__ == '__main__': main()",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"from collections import deque inp = [] with open('day12-data.txt', 'r') as f: for line in f: inp.append(list(line.strip())) # print(inp) num_rows = len(inp) num_cols = len(inp[0]) def in_bounds(rc): r, c = rc return (0 <= r < num_rows) and (0 <= c < num_cols) def get_plant(rc): r, c = rc return inp[r][c] def get_neighbors(rc): r, c = rc neighbors = [] ds = [(-1, 0), (0, 1), (1, 0), (0, -1)] # NESW for (dr, dc) in ds: neighbors.append((r + dr, c + dc)) return [n for n in neighbors if in_bounds(n)] def get_plant_neighbors(rc): neighbors = get_neighbors(rc) return [n for n in neighbors if get_plant(n)==get_plant(rc)] # BFS def get_region(rc): visited = set() region = set() queue = deque([rc]) while queue: node = queue.popleft() if node not in visited: visited.add(node) # visit node region.add(node) # add all unvisited neighbors to the queue neighbors = get_plant_neighbors(node) unvisited_neighbors = [n for n in neighbors if n not in visited] # print(f'At node {node}, ns: {neighbors}, unvisited: {unvisited_neighbors}') queue.extend(unvisited_neighbors) return region def calc_perimeter(region): perimeter = 0 for rc in region: plant = get_plant(rc) neighbors = get_plant_neighbors(rc) # Boundary adds to perimeter perimeter += 4 - len(neighbors) return perimeter regions = [] visited = set() for r in range(num_rows): for c in range(num_cols): rc = (r, c) if rc not in visited: region = get_region(rc) visited |= region regions.append(region) # print(regions) total_price = 0 for region in regions: plant = get_plant(next(iter(region))) area = len(region) perimeter = calc_perimeter(region) price = area * perimeter total_price += price # print(f'{plant} (area: {area}, perimeter: {perimeter}): {region}') print(total_price)",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"input = open(""day_12\input.txt"", ""r"").read().splitlines() directions = [(1,0), (0,1), (-1, 0), (0, -1)] total = 0 def add_padding(matrix): padding_row = ['!' * (len(matrix[0]) + 2)] padded_matrix = [f""{'!'}{row}{'!'}"" for row in matrix] return padding_row + padded_matrix + padding_row def explore(char, i, j): global area, perimeter if not input[i][j] == char: perimeter += 1 return visited.add((i,j)) global_visited.add((i, j)) area += 1 for (dy, dx) in directions: if not (i + dy, j + dx) in visited: explore(char, i + dy, j + dx) input = [list(line) for line in add_padding(input)] global_visited = set() for i in range(len(input)): for j in range(len(input[i])): if not input[i][j] == ""!"" and not (i, j) in global_visited: visited = set() area = 0 perimeter = 0 explore(input[i][j], i, j) total += area * perimeter print(f""The total price of fencing all the regions is {total}"")",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"from collections import deque with open('input.txt') as f: data = f.read().splitlines() xmax = len(data[0]) ymax = len(data) total_seen = set() def calc_plot(x, y): plant = data[y][x] perimeter = 0 area = 0 seen = set() q = deque() q.append((x, y)) while q: xi, yi = q.popleft() if (xi, yi) in seen: continue if xi < 0 or xi >= xmax or yi < 0 or yi >= ymax or data[yi][xi] != plant: perimeter += 1 continue seen.add((xi, yi)) area += 1 q.append((xi + 1, yi)) q.append((xi - 1, yi)) q.append((xi, yi + 1)) q.append((xi, yi - 1)) total_seen.update(seen) return area * perimeter total = 0 for yi in range(ymax): for xi in range(xmax): if (xi, yi) in total_seen: continue total += calc_plot(xi, yi) print(total)",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"from typing import List from pprint import pprint as pprint INPUT_FILE = ""input.txt"" visited = set() class Plot: def __init__(self, plant: str, area: int, perimeter: int): self.plant = plant self.area = area self.perimeter = perimeter def __repr__(self): return f""Plot({self.plant}, {self.area}, {self.perimeter})"" def __str__(self): return f""Plot({self.plant}, {self.area}, {self.perimeter})"" def readInput() -> List[List[str]]: with open(INPUT_FILE, 'r') as f: return [list(line.strip()) for line in f.readlines()] def findPlot(grid: List[List[str]], currentPlot: Plot, currentLocation: tuple[int, int]) -> Plot: plot = Plot(currentPlot.plant, currentPlot.area, currentPlot.perimeter) visited.add(currentLocation) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] for direction in directions: x = currentLocation[0] + direction[0] y = currentLocation[1] + direction[1] if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]): plot.perimeter += 1 continue if grid[x][y] != plot.plant: plot.perimeter += 1 continue if (x, y) in visited: continue plot.area += 1 plot = findPlot(grid, plot, (x, y)) return plot def getPlots(grid: List[List[str]]) -> List[Plot]: plots = [] for i in range(len(grid)): for j in range(len(grid[0])): if (i, j) in visited: continue plot = findPlot(grid, Plot(grid[i][j], 1, 0), (i, j)) plots.append(plot) return plots def calculateCosts(plots: List[Plot]) -> int: cost = 0 for plot in plots: cost += plot.area * plot.perimeter return cost def main(): grid = readInput() pprint(grid) plots = getPlots(grid) pprint(plots) print(f'Cost: {calculateCosts(plots)}') if __name__ == ""__main__"": main()",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"input = open(""day_12\input.txt"", ""r"").read().splitlines() directions = [(1,0), (0,1), (-1, 0), (0, -1)] total = 0 def add_padding(matrix): padding_row = ['!' * (len(matrix[0]) + 2)] padded_matrix = [f""{'!'}{row}{'!'}"" for row in matrix] return padding_row + padded_matrix + padding_row def explore(char, i, j): global area, sides visited.add((i,j)) global_visited.add((i,j)) area += 1 for (dy,dx) in directions: if input[i + dy][j + dx] != char: sides += [((dy,dx), (i,j))] elif not (i + dy, j + dx) in visited: explore(char, i + dy, j + dx) def calculate_sides(sides): unique_sides = 0 while len(sides) > 0: current_side = sides[0] sides = explore_side(current_side, sides[0:]) unique_sides += 1 if current_side in sides: sides.remove(current_side) return unique_sides def explore_side(side, sides): if side[0] == (1, 0) or side[0] == (-1, 0): targets = [(side[0], (side[1][0], side[1][1] - 1)), (side[0], (side[1][0], side[1][1] + 1))] for target in targets: if target in sides: sides.remove(target) sides = explore_side(target, sides) elif side[0] == (0, 1) or side[0] == (0, -1): targets = [(side[0], (side[1][0] + 1, side[1][1])), (side[0], (side[1][0] - 1, side[1][1]))] for target in targets: if target in sides: sides.remove(target) sides = explore_side(target, sides) return sides input = [list(line) for line in add_padding(input)] global_visited = set() for i in range(len(input)): for j in range(len(input[i])): if input[i][j] != ""!"" and not (i, j) in global_visited: visited = set() area = 0 sides = [] explore(input[i][j], i, j) total += area * calculate_sides(sides) print(f""The total price of fencing all the regions is {total}"")",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"def add_to_region_from(grid, loc, region, visited): region.add(loc) visited.add(loc) neighbors = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)] neighbors = [pt for pt in neighbors if pt[0] in range(len(grid)) and pt[1] in range(len(grid))] for neighbor in neighbors: if grid[loc[0]][loc[1]] == grid[neighbor[0]][neighbor[1]] and not neighbor in visited: add_to_region_from(grid, neighbor, region, visited) def get_area(region): return len(region) def get_sides(region): sides = 0 visited_edges = set() sorted_region = sorted(list(region)) for loc in sorted_region: above = (loc[0] - 1, loc[1]) if above not in region: visited_edges.add((above, 'bottom')) if ((above[0], above[1] - 1), 'bottom') not in visited_edges and ((above[0], above[1] + 1), 'bottom') not in visited_edges: sides += 1 below = (loc[0] + 1, loc[1]) if below not in region: visited_edges.add((below, 'top')) if ((below[0], below[1] - 1), 'top') not in visited_edges and ((below[0], below[1] + 1), 'top') not in visited_edges: sides += 1 left = (loc[0], loc[1] - 1) if left not in region: visited_edges.add((left, 'right')) if ((left[0] - 1, left[1]), 'right') not in visited_edges and ((left[0] + 1, left[1]), 'right') not in visited_edges: sides += 1 right = (loc[0], loc[1] + 1) if right not in region: visited_edges.add((right, 'left')) if ((right[0] - 1, right[1]), 'left') not in visited_edges and ((right[0] + 1, right[1]), 'left') not in visited_edges: sides += 1 return sides def get_corners(region): corners = 0 for loc in region: outer_top_left = [((0, -1), False), ((-1, 0), False)] outer_top_right = [((0, 1), False), ((-1, 0), False)] outer_bottom_right = [((0, 1), False), ((1, 0), False)] outer_bottom_left = [((0, -1), False), ((1, 0), False)] inner_top_left = [((0, 1), True), ((1, 0), True), ((1, 1), False)] inner_top_right = [((0, -1), True), ((1, 0), True), ((1, -1), False)] inner_bottom_right = [((0, -1), True), ((-1, 0), True), ((-1, -1), False)] inner_bottom_left = [((0, 1), True), ((-1, 0), True), ((-1, 1), False)] all_neighbors = [outer_top_left, outer_top_right, outer_bottom_right, outer_bottom_left, inner_top_left, inner_top_right, inner_bottom_right, inner_bottom_left] corners += sum([all([((loc[0] + pt[0][0], loc[1] + pt[0][1]) in region) == pt[1] for pt in neighbor]) for neighbor in all_neighbors]) return corners def get_perimeter(region): perimeter = 0 for loc in region: neighbors = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)] perimeter += len([pt for pt in neighbors if pt not in region]) return perimeter with open('input.txt') as f: grid = [[c for c in line] for line in f.read().splitlines()] visited = set() regions = [] for i in range(len(grid)): for j in range(len(grid[i])): if not (i, j) in visited: region = set() add_to_region_from(grid, (i, j), region, visited) regions.append(region) visited.add((i, j)) total_price = 0 for region in regions: price = get_area(region) * get_corners(region) total_price += price print(total_price)",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"from collections import deque with open('input.txt') as f: data = f.read().splitlines() xmax = len(data[0]) ymax = len(data) total_seen = set() def count_corners(plant, x, y): up = data[y - 1][x] if y - 1 >= 0 else None down = data[y + 1][x] if y + 1 < ymax else None left = data[y][x - 1] if x - 1 >= 0 else None right = data[y][x + 1] if x + 1 < xmax else None count = sum(1 for i in (up, down, left, right) if i == plant) corners = 0 if count == 0: return 4 if count == 1: return 2 if count == 2: if left == right == plant or up == down == plant: return 0 corners += 1 if up == left == plant and (y - 1 >= 0 and x - 1 >= 0) and data[y - 1][x - 1] != plant: corners += 1 if up == right == plant and (y - 1 >= 0 and x + 1 < xmax) and data[y - 1][x + 1] != plant: corners += 1 if down == left == plant and (y + 1 < ymax and x - 1 >= 0) and data[y + 1][x - 1] != plant: corners += 1 if down == right == plant and (y + 1 < ymax and x + 1 < xmax) and data[y + 1][x + 1] != plant: corners += 1 return corners def calc_plot(x, y): plant = data[y][x] perimeter = 0 area = 0 corners = 0 seen = set() q = deque() q.append((x, y)) while q: xi, yi = q.popleft() if (xi, yi) in seen: continue if xi < 0 or xi >= xmax or yi < 0 or yi >= ymax or data[yi][xi] != plant: perimeter += 1 continue seen.add((xi, yi)) area += 1 corners += count_corners(plant, xi, yi) q.append((xi + 1, yi)) q.append((xi - 1, yi)) q.append((xi, yi + 1)) q.append((xi, yi - 1)) total_seen.update(seen) return area * corners total = 0 for yi in range(ymax): for xi in range(xmax): if (xi, yi) in total_seen: continue total += calc_plot(xi, yi) print(total)",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"def visit(x, y, visited): area = 1 visited.add((x, y)) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if ((x + dx, y + dy) not in visited and 0 <= x + dx < width and 0 <= y + dy < height and garden[y][x] == garden[y + dy][x + dx]): d_area, _ = visit(x + dx, y + dy, visited) area += d_area return area, visited def perimeter(plot): min_x = min(plot, key=lambda p: p[0])[0] min_y = min(plot, key=lambda p: p[1])[1] max_x = max(plot, key=lambda p: p[0])[0] max_y = max(plot, key=lambda p: p[1])[1] # vertical rays hits = {} for ray_x in range(min_x - 1, max_x + 1): is_in = False hits[ray_x] = [] for ray_y in range(min_y - 1, max_y + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in hits[ray_x].append((ray_y, is_in)) side_count = 0 for i, hit_x in enumerate(hits): if i > 0: for (y, is_in) in hits[hit_x]: if (y, is_in) not in hits[hit_x - 1]: side_count += 1 # horizontal rays hits = {} for ray_y in range(min_y - 1, max_y + 1): is_in = False hits[ray_y] = [] for ray_x in range(min_x - 1, max_x + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in hits[ray_y].append((ray_x, is_in)) for i, hit_y in enumerate(hits): if i > 0: for (y, is_in) in hits[hit_y]: if (y, is_in) not in hits[hit_y - 1]: side_count += 1 return side_count def main(): visited = set() result = 0 for y, row in enumerate(garden): for x, column in enumerate(row): if (x, y) not in visited: area, v = visit(x, y, set()) perim = perimeter(v) visited.update(v) result += area * perim print(result) with open(""12_input.txt"", ""r"") as f: garden = [line.strip() for line in f.readlines()] width = len(garden[0]) height = len(garden) if __name__ == '__main__': main()",python 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. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"from collections import deque def get_total_cost(farm): n = len(farm) m = len(farm[0]) def in_bounds(r, c): return (0 <= r < n) and (0 <= c < m) def get_val(r, c): return farm[r][c] def get_neighbours(r, c): neighbours = [] dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)] for (dr, dc) in dirs: neighbours.append((r + dr, c + dc)) return [neighbour for neighbour in neighbours if in_bounds(neighbour[0], neighbour[1])] def get_val_neighbours(r, c): neighbours = get_neighbours(r, c) return [neighbour for neighbour in neighbours if get_val(neighbour[0], neighbour[1]) == get_val(r, c)] def get_region(r, c): visited = set() region = set() queue = deque([(r, c)]) while queue: node = queue.popleft() if node not in visited: visited.add(node) region.add(node) neighbours = get_val_neighbours(node[0], node[1]) neighbours = [neighbour for neighbour in neighbours if neighbour not in visited] queue.extend(neighbours) return region def calc_edges(region): edges = 0 for (r, c) in region: if ((r - 1, c) not in region): if not (((r, c - 1) in region) and ((r - 1, c - 1) not in region)): edges += 1 if ((r + 1, c) not in region): if not (((r, c - 1) in region) and ((r + 1, c - 1) not in region)): edges += 1 if ((r, c - 1) not in region): if not (((r - 1, c) in region) and ((r - 1, c - 1) not in region)): edges += 1 if ((r, c + 1) not in region): if not (((r - 1, c) in region) and ((r - 1, c + 1) not in region)): edges += 1 return edges regions = [] visited = set() for i in range(n): for j in range(m): if (i, j) not in visited: region = get_region(i, j) visited |= region regions.append(region) cost = 0 for region in regions: nextRegion = next(iter(region)) val = get_val(nextRegion[0], nextRegion[1]) area = len(region) edges = calc_edges(region) price = area * edges cost += price return cost if __name__ == ""__main__"": # Open file 'day12-2.txt' in read mode with open('day12-2.txt', 'r') as f: farm = [] for line in f: farm.append(line.strip()) print(""Total fencing cost: "" + str(get_total_cost(farm)))",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() total = 0 for problem in range((len(input_text) + 1) // 4): button_a_move_x, button_a_move_y = ( input_text[problem * 4].removeprefix(""Button A: "").split("", "") ) button_a_move = ( int(button_a_move_x.removeprefix(""X+"")), int(button_a_move_y.removeprefix(""Y+"")), ) button_b_move_x, button_b_move_y = ( input_text[problem * 4 + 1].removeprefix(""Button B: "").split("", "") ) button_b_move = ( int(button_b_move_x.removeprefix(""X+"")), int(button_b_move_y.removeprefix(""Y+"")), ) target_x, target_y = input_text[problem * 4 + 2].removeprefix(""Prize: "").split("", "") target = (int(target_x.removeprefix(""X="")), int(target_y.removeprefix(""Y=""))) min_cost = float(""inf"") for a_presses in range(101): for b_presses in range(101): if ( a_presses * button_a_move[0] + b_presses * button_b_move[0], a_presses * button_a_move[1] + b_presses * button_b_move[1], ) == target: min_cost = min(min_cost, a_presses * 3 + b_presses) if min_cost < float(""inf""): total += min_cost print(total)",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"import re with open(""./day_13.in"") as fin: lines = fin.read().strip().split(""\n\n"") def parse(x): lines = x.split(""\n"") a = list(map(int, re.findall(r""Button A: X\+(\d+), Y\+(\d+)"", lines[0])[0])) b = list(map(int, re.findall(r""Button B: X\+(\d+), Y\+(\d+)"", lines[1])[0])) p = list(map(int, re.findall(r""Prize: X=(\d+), Y=(\d+)"", lines[2])[0])) return a, b, p prices = [] for a, b, p in [parse(line) for line in lines]: def test(i, j): x = a[0] * i + b[0] * j y = a[1] * i + b[1] * j return (x, y) == tuple(p) va = 1<<30 for i in range(100): for j in range(100): if test(i, j): va = min(va, 3*i + j) if va < 1<<30: prices.append(va) spent = 0 print(sum(prices))",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"from typing import List from pprint import pprint as pprint from functools import cache INPUT_FILE = ""input.txt"" MAX_PRIZE = 401 class Button: def __init__(self, price: int, d_x: int, d_y: int): self.price = price self.d_x = d_x self.d_y = d_y def __repr__(self): return f""Button({self.price}, {self.d_x}, {self.d_y})"" def __str__(self): return f""Button({self.price}, {self.d_x}, {self.d_y})"" class Prize: def __init__(self, x: int, y: int): self.x = x self.y = y def __repr__(self): return f""Price({self.x}, {self.y})"" def __str__(self): return f""Price({self.x}, {self.y})"" def readInput() -> List[str]: with open(INPUT_FILE, 'r') as f: return f.read().split('\n\n') def parseInput(data: str) -> tuple[Prize, tuple[Button, Button]]: a, b, prize = data.splitlines() button_a = Button(3, int(a.split(""X+"")[1].split("","")[0]), int(a.split(""Y+"")[1])) button_b = Button(1, int(b.split(""X+"")[1].split("","")[0]), int(b.split(""Y+"")[1])) prize = Prize(int(prize.split(""X="")[1].split("","")[0]), int(prize.split(""Y="")[1])) return (prize, (button_a, button_b)) @cache def getCost(prize: Prize, buttons: tuple[Button, Button]) -> int: # lowest_cost = MAX_PRIZE for a in range(100): for b in range(100): if prize.x == buttons[0].d_x*a+buttons[1].d_x*b and prize.y == buttons[0].d_y*a+buttons[1].d_y*b: return a * buttons[0].price + b * buttons[1].price return 0 def costs(machines: List[tuple[Prize, tuple[Button, Button]]]) -> List[int]: costs = [] for machine in machines: costs.append(getCost(machine[0], machine[1])) return costs def main(): data = readInput() # pprint(data) machines = [parseInput(line) for line in data] # pprint(machines) costs_list = costs(machines) # pprint(costs_list) print(f""Result: {sum(costs_list)}"") if __name__ == ""__main__"": main()",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"f = open(""input.txt"") machines = [elem.split(""\n"") for elem in f.read().split(""\n\n"")] def find_solution(A_button, B_button, prize): X_a, Y_a = A_button X_b, Y_b = B_button X_prize, Y_prize = prize b = (X_prize * Y_a - Y_prize * X_a) / (X_b * Y_a - X_a * Y_b) a = (X_prize * Y_b - Y_prize * X_b) / (X_a * Y_b - X_b * Y_a) if (int(a) == a and a <= 100 and int(b) == b and b <= 100): return (a,b) return () def get_cost(solution): return solution[0]*3 + solution[1] total = 0 for machine in machines: A_button = tuple([int(text[3:]) for text in machine[0].split("":"")[1].split("","")]) B_button = tuple([int(text[3:]) for text in machine[1].split("":"")[1].split("","")]) prize = tuple([int(text[3:]) for text in machine[2].split("":"")[1].split("","")]) solution = find_solution(A_button, B_button, prize) if solution != (): cost = get_cost(solution) total += cost print(total)",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"import os def reader(): return open(f""input.txt"", 'r').read().splitlines() def part1(): f = list(map(lambda s: s.split('\n'), '\n'.join(reader()).split('\n\n'))) M = [] for l in f: Ax = int(l[0][(l[0].find('X+') + 2):l[0].find(',')]) Ay = int(l[0][(l[0].find('Y+') + 2):]) Bx = int(l[1][(l[1].find('X+') + 2):l[1].find(',')]) By = int(l[1][(l[1].find('Y+') + 2):]) X = int(l[2][(l[2].find('X=') + 2):l[2].find(',')]) Y = int(l[2][(l[2].find('Y=') + 2):]) M.append([(Ax, Ay), (Bx, By), (X, Y)]) t = 0 for m in M: l = -1, 0 for i in range(101): for j in range(101): cost = 3 * i + j pos = i * m[0][0] + j * m[1][0], i * m[0][1] + j * m[1][1] if pos == m[2]: l = (0, cost) if l[0] == -1 else (0, min(l[1], cost)) if l[0] == 0: t += l[1] print(t) part1()",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"def get_cheapest(machine): A = machine[0] B = machine[1] prize = (machine[2][0] + 10000000000000, machine[2][1] + 10000000000000) af = (A[1] / A[0]) bf = (B[1] / B[0]) xIntersection = round((prize[0] * af - prize[1]) / (af - bf)) if xIntersection % B[0] != 0: return 0 b = xIntersection // B[0] rem = ((prize[0] - B[0] * b), (prize[1] - B[1] * b)) if rem[0] % A[0] != 0: return 0 a = rem[0] // A[0] if ((B[0] * b) + (A[0] * a) == prize[0] and (B[1] * b) + (A[1] * a)) == prize[1]: return b + (a * 3) return 0 def get_fewest_tokens(machines): tokens = 0 for machine in machines: tokens += get_cheapest(machine) return tokens if __name__ == ""__main__"": # Open file 'day13-2.txt' in read mode with open('day13-2.txt', 'r') as f: machines = [] A = (0, 0) B = (0, 0) prize = (0, 0) for i, line in enumerate(f): line = line.strip() if i % 4 == 0: A = (int(line[line.find('+') + 1: line.find(',')]), int(line[line.find(',') + 4:])) elif i % 4 == 1: B = (int(line[line.find('+') + 1: line.find(',')]), int(line[line.find(',') + 4:])) elif i % 4 == 2: prize = (int(line[line.find('=') + 1: line.find(',')]), int(line[line.find(',') + 4:])) machines.append([ A, B, prize ]) else: A = (0, 0) B = (0, 0) prize = (0, 0) print(""Fewest number of tokens: "" + str(get_fewest_tokens(machines)))",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"f = open(""input.txt"") machines = [elem.split(""\n"") for elem in f.read().split(""\n\n"")] def find_solution(A_button, B_button, prize): X_a, Y_a = A_button X_b, Y_b = B_button X_prize, Y_prize = prize X_prize += 10000000000000 Y_prize += 10000000000000 b = (X_prize * Y_a - Y_prize * X_a) / (X_b * Y_a - X_a * Y_b) a = (X_prize * Y_b - Y_prize * X_b) / (X_a * Y_b - X_b * Y_a) if (int(a) == a and int(b) == b): return (a,b) return () def get_cost(solution): return solution[0]*3 + solution[1] total = 0 for machine in machines: A_button = tuple([int(text[3:]) for text in machine[0].split("":"")[1].split("","")]) B_button = tuple([int(text[3:]) for text in machine[1].split("":"")[1].split("","")]) prize = tuple([int(text[3:]) for text in machine[2].split("":"")[1].split("","")]) solution = find_solution(A_button, B_button, prize) if solution != (): cost = get_cost(solution) total += cost print(total)",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"import re from typing import Tuple, List def parse_input(file_path: str) -> List[Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]]: """""" Parses the input file to extract button and prize coordinates. The input file should contain lines formatted as: ""Button A: X+, Y+ Button B: X+, Y+ Prize: X=, Y="" Args: file_path (str): The path to the input file. Returns: List[Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]]: A list of tuples, each containing: - A tuple representing the coordinates of Button A (X, Y). - A tuple representing the coordinates of Button B (X, Y). - A tuple representing the coordinates of the Prize (X, Y) with 10000000000000 added to each coordinate. """""" pattern = re.compile(r""Button A: X\+(\d+), Y\+(\d+)\s+Button B: X\+(\d+), Y\+(\d+)\s+Prize: X=(\d+), Y=(\d+)"") results = [] with open(file_path, 'r') as file: content = file.read() matches = pattern.findall(content) for match in matches: button_a = (int(match[0]), int(match[1])) button_b = (int(match[2]), int(match[3])) prize = (int(match[4]) + 10000000000000, int(match[5]) + 10000000000000) results.append((button_a, button_b, prize)) return results def solve(scenario: Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]) -> int: """""" Solves the given scenario by finding integers a and b such that the linear combination of the vectors (ax, ay) and (bx, by) equals the target vector (tx, ty). Args: scenario (Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]): A tuple containing three tuples, each representing a vector in the form (x, y). The first two tuples are the vectors (ax, ay) and (bx, by), and the third tuple is the target vector (tx, ty). Returns: int: The result of the expression 3 * a + b if the linear combination is valid, otherwise 0. """""" (ax, ay), (bx, by), (tx, ty) = scenario b = (tx * ay - ty * ax) // (ay * bx - by * ax) a = (tx * by - ty * bx) // (by * ax - bx * ay) if ax * a + bx * b == tx and ay * a + by * b == ty: return 3 * a + b else: return 0 if __name__ == ""__main__"": file_path = 'input.txt' parsed_data = parse_input(file_path) results = [solve(scenario) for scenario in parsed_data] print(sum(results))",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"import re def min_cost_for_prize(prize, a, b): prize_x = prize[0] prize_y = prize[1] a_x = a[0] a_y = a[1] b_x = b[0] b_y = b[1] if (prize_x * b_y - b_x * prize_y) % (a_x * b_y - b_x * a_y) != 0: return (False, -1) a_val = (prize_x * b_y - b_x * prize_y) // (a_x * b_y - b_x * a_y) if (prize_x - a_x * a_val) % b_x != 0: return (False, -1) b_val = (prize_x - a_x * a_val) // b_x return (True, 3 * a_val + b_val) with open('input.txt') as f: claw_strs = f.read().split(""\n\n"") claw_data = [] for claw_input in claw_strs: lines = claw_input.splitlines() claw = dict() claw['A'] = tuple(map(int, re.match(""Button A: X\\+(\\d+), Y\\+(\\d+)"", lines[0]).groups())) claw['B'] = tuple(map(int, re.match(""Button B: X\\+(\\d+), Y\\+(\\d+)"", lines[1]).groups())) claw['Prize'] = tuple(map(lambda n: n + 10000000000000, map(int, re.match(""Prize: X=(\\d+), Y=(\\d+)"", lines[2]).groups()))) claw_data.append(claw) total_cost = 0 for claw in claw_data: res = min_cost_for_prize(claw['Prize'], claw['A'], claw['B']) if res[0]: total_cost += res[1] print(total_cost)",python 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. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() total = 0 for problem in range((len(input_text) + 1) // 4): button_a_move_x, button_a_move_y = ( input_text[problem * 4].removeprefix(""Button A: "").split("", "") ) button_a_move = ( int(button_a_move_x.removeprefix(""X+"")), int(button_a_move_y.removeprefix(""Y+"")), ) button_b_move_x, button_b_move_y = ( input_text[problem * 4 + 1].removeprefix(""Button B: "").split("", "") ) button_b_move = ( int(button_b_move_x.removeprefix(""X+"")), int(button_b_move_y.removeprefix(""Y+"")), ) target_x, target_y = input_text[problem * 4 + 2].removeprefix(""Prize: "").split("", "") target = ( int(target_x.removeprefix(""X="")) + 10000000000000, int(target_y.removeprefix(""Y="")) + 10000000000000, ) sol_a, sol_b = ( (button_b_move[1] * target[0] - button_b_move[0] * target[1]) // (button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0]), (-button_a_move[1] * target[0] + button_a_move[0] * target[1]) // (button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0]), ) if ( ( (button_b_move[1] * target[0] - button_b_move[0] * target[1]) % ( button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0] ) ) == 0 and ( (-button_a_move[1] * target[0] + button_a_move[0] * target[1]) % ( button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0] ) ) == 0 and sol_a > 0 and sol_b > 0 ): total += 3 * sol_a + sol_b print(total)",python 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"import re def read_input(): robots = [] with open(""./input.txt"") as f: while True: line = f.readline() if not line: break numbers = re.findall(r""-?\d+"", line) robots.append([int(s) for s in numbers]) return robots def move_robot_n_step(robot, width, height, n): x0 = robot[0] y0 = robot[1] vx = robot[2] vy = robot[3] for i in range(n): x0 = (x0 + vx) % width y0 = (y0 + vy) % height return x0, y0 def move_robot_one_step(robot, width, height): x0 = robot[0] y0 = robot[1] vx = robot[2] vy = robot[3] robot[0] = (x0 + vx) % width robot[1] = (y0 + vy) % height def get_quadrant(x, y, width, height): cx = width // 2 cy = height // 2 if x < cx and y < cy: return 4 elif x < cx and y > cy: return 3 elif x > cx and y < cy: return 1 elif x > cx and y > cy: return 2 else: return -1 def solve_part1(robots, width, height): q = {1:0, 2:0, 3:0, 4:0, -1:0} for robot in robots: x,y = move_robot_n_step(robot, width, height, 100) iq = get_quadrant(x, y, width, height) q[iq] += 1 print(f""q1: {q[1]}, q2: {q[2]}, q3: {q[3]}, q4: {q[4]}"") return q[1] * q[2] * q[3] * q[4] def solve_part2(robots, width, height): best_iter = None min_safe = float('inf') for i in range(width * height): q = {1:0, 2:0, 3:0, 4:0, -1:0} for robot in robots: x,y = move_robot_n_step(robot, width, height, 1) robot[0] = x robot[1] = y iq = get_quadrant(x, y, width, height) q[iq] += 1 safe = q[1] * q[2] * q[3] * q[4] if safe < min_safe: min_safe = safe best_iter = i if i == 99: print(""At 100 sec, "", safe) print(f""best iter {best_iter}, min safe {min_safe}"") if __name__ == ""__main__"": robots = read_input() width = 101 height = 103 multiply = solve_part1(robots, width, height) print(f""Part 1: the product is {multiply}"") solve_part2(robots, width, height)",python 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"from collections import Counter import re width = 101 #11 half_width = width // 2 height = 103 #7 half_height = height // 2 class Robot: def __init__(self, px, py, vx, vy) -> None: self.px = px self.py = py self.vx = vx self.vy = vy self.q = None def move(self, seconds): self.px = (self.px + self.vx * seconds) % width self.py = (self.py + self.vy * seconds) % height self.q = self.quadrant() def quadrant(self): quadrants = { (True, True): 1, (True, False): 3, (False, True): 2, (False, False): 4, } return quadrants[(self.px < half_width, self.py < half_height)] if self.px != half_width and self.py != half_height else None with open('input.txt') as f: robots = [Robot(*map(int, re.findall(r'(-?\d+)', line))) for line in f] def print_grid(robots: list[Robot]): grid = [list('.' * width) for _ in range(height)] for robot in robots: val = grid[robot.py][robot.px] grid[robot.py][robot.px] = '1' if val == '.' else str(int(val) + 1) print('\n'.join(''.join(row) for row in grid)) quadrants = [] for robot in robots: robot.move(100) quadrants.append(robot.q) counter = Counter(quadrants) counter.pop(None) print(counter[1] * counter[2] * counter[3] * counter[4])",python 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"#!/usr/bin/python3 class Robot: def __init__(self, position, velocity): self.position = position self.velocity = velocity def teleport(self, pos:int, dim:int): """"""Move to opposite side rather than out of the space."""""" return pos - dim if pos >= dim else dim - abs(pos) if pos < 0 else pos def move_robot(self, width:int, height:int): """"""Move robot according to its velocity."""""" self.position = [self.position[0] + self.velocity[0], self.position[1] + self.velocity[1]] if self.position[0] not in range(width): self.position[0] = self.teleport(self.position[0], width) if self.position[1] not in range(height): self.position[1] = self.teleport(self.position[1], height) # Get initial position and velocity for each robot. with open(""input.txt"") as file: robots = {} for l, line in enumerate(file): robot_name = ""robot_"" + str(l+1) pos = line.split()[0].strip(""p="").split("","") vel = line.split()[1].strip(""v="").split("","") robots[robot_name] = Robot([int(pos[0]),int(pos[1])], [int(vel[0]),int(vel[1])]) # Move robots for 100 seconds in a space 101 tiles wide and 103 tiles tall. for robot in robots: for sec in range(100): robots[robot].move_robot(101, 103) # Determine the safety factor. quadrant_1 = [robots[robot].position for robot in robots if robots[robot].position[0] < 50 and robots[robot].position[1] < 51] quadrant_2 = [robots[robot].position for robot in robots if robots[robot].position[0] > 50 and robots[robot].position[1] < 51] quadrant_3 = [robots[robot].position for robot in robots if robots[robot].position[0] < 50 and robots[robot].position[1] > 51] quadrant_4 = [robots[robot].position for robot in robots if robots[robot].position[0] > 50 and robots[robot].position[1] > 51] print(""Safety factor after 100 seconds:"", len(quadrant_1) * len(quadrant_2) * len(quadrant_3) * len(quadrant_4))",python 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"from typing import List EXAMPLE: bool = False WIDTH: int = 11 if EXAMPLE else 101 HEIGHT: int = 7 if EXAMPLE else 103 INPUT_FILE: str = ""e_input.txt"" if EXAMPLE else ""input.txt"" class Robot: def __init__(self, x: int, y: int, v_x: int, v_y: int): self.x = x self.y = y self.v_x = v_x self.v_y = v_y def move(self): self.x += self.v_x self.y += self.v_y if self.x < 0: self.x = WIDTH + self.x if self.y < 0: self.y = HEIGHT + self.y if self.x >= WIDTH: self.x -= WIDTH if self.y >= HEIGHT: self.y -= HEIGHT def __str__(self): return f""Robot: x={self.x}, y={self.y}, v_x={self.v_x}, v_y={self.v_y}"" def __repr__(self): return self.__str__() def read_input() -> List[str]: with open(INPUT_FILE, ""r"") as f: return f.read().splitlines() def parse_input(input: List[str]) -> List[Robot]: robots: List[Robot] = [] for line in input: line = line.split("" "") pos = line[0][2:].split("","") x, y = int(pos[0]), int(pos[1]) velo = line[1][2:].split("","") v_x, v_y = int(velo[0]), int(velo[1]) robots.append(Robot(x, y, v_x, v_y)) return robots def predict(robots: List[Robot], seconds: int) -> List[Robot]: for i in range(seconds): for robot in robots: robot.move() return robots def print_grid(robots: List[Robot]): for y in range(HEIGHT): for x in range(WIDTH): r = 0 for robot in robots: if robot.x == x and robot.y == y: r += 1 if r == 0: print(""."", end="""") else: print(str(r), end="""") print() def safety_score(robots: List[Robot]) -> int: quadrant_one = 0 quadrant_two = 0 quadrant_three = 0 quadrant_four = 0 for robot in robots : if robot.x < WIDTH // 2 and robot.y < HEIGHT // 2: quadrant_one += 1 elif robot.x > WIDTH // 2 and robot.y < HEIGHT // 2: quadrant_two += 1 elif robot.x < WIDTH // 2 and robot.y > HEIGHT // 2: quadrant_three += 1 elif robot.x > WIDTH // 2 and robot.y > HEIGHT // 2: quadrant_four += 1 return quadrant_one * quadrant_two * quadrant_three * quadrant_four def main(): robots = parse_input(read_input()) robots = predict(robots, 100) print(safety_score(robots)) if __name__ == ""__main__"": main()",python 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"import re from functools import reduce from operator import mul result = 0 width = 101 height = 103 duration = 100 robots = [] with open(""14_input.txt"", ""r"") as f: for line in f: px, py, vx, vy = map(int, re.findall(r""(-?\d+)"", line)) for sec in range(duration): px = (px + vx) % width py = (py + vy) % height robots.append((px, py)) q_width = width // 2 q_height = height // 2 quadrants = {0: 0, 1: 0, 2: 0, 3: 0} for robot in robots: if robot[0] < q_width: if robot[1] < q_height: quadrants[0] += 1 elif robot[1] > q_height: quadrants[1] += 1 elif robot[0] > q_width: if robot[1] < q_height: quadrants[2] += 1 elif robot[1] > q_height: quadrants[3] += 1 print(reduce(mul, quadrants.values()))",python 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"from collections import defaultdict from statistics import stdev def read_input(file_path): """"""Read input from file and parse positions and velocities."""""" positions, velocities = [], [] with open(file_path) as f: for line in f: p_sec, v_sec = line.split() positions.append([int(i) for i in p_sec.split(""="")[1].split("","")]) velocities.append([int(i) for i in v_sec.split(""="")[1].split("","")]) return positions, velocities def simulate_motion(positions, velocities, num_x=101, num_y=103, steps=10000): """"""Simulate motion and detect significant changes in distribution."""""" for step in range(1, steps + 1): block_counts = defaultdict(int) new_positions = [] for pos, vel in zip(positions, velocities): new_x = (pos[0] + vel[0]) % num_x new_y = (pos[1] + vel[1]) % num_y new_positions.append([new_x, new_y]) block_counts[(new_x // 5, new_y // 5)] += 1 if stdev(block_counts.values()) > 3: print(step) break positions = new_positions if __name__ == ""__main__"": positions, velocities = read_input(""input.txt"") 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"from collections import defaultdict from statistics import stdev with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() num_x = 101 num_y = 103 initial_positions = [] velocities = [] for line in input_text: p_sec, v_sec = line.split() initial_positions.append([int(i) for i in p_sec.split(""="")[1].split("","")]) velocities.append([int(i) for i in v_sec.split(""="")[1].split("","")]) for counter in range(10000): block_counts = defaultdict(int) new_initial_positions = [] for initial_pos, velocity in zip(initial_positions, velocities): new_position = [ (initial_pos[0] + velocity[0]) % num_x, (initial_pos[1] + velocity[1]) % num_y, ] new_initial_positions.append(new_position) block_counts[(new_position[0] // 5, new_position[1] // 5)] += 1 if stdev(block_counts.values()) > 3: print(counter + 1) initial_positions = new_initial_positions",python 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import re; L = len(M:=[*map(int, re.findall('[-\d]+', open(0).read()))]) R, C = 103, 101; B = (1, -1) for T in range(R*C): G = [['.']*C for _ in range(R)] Z = [0]*4 for i in range(0, L, 4): py, px, vy, vx = M[i:i+4] x = (px+vx*T)%R; y = (py+vy*T)%C G[x][y] = '#' if x == R//2 or y == C//2: continue Z[(x 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 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. 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,"with open(""Day-14-Challenge/input.txt"", ""r"") as file: lines = file.readlines() WIDE = 101 TALL = 103 robots = [] for robot in lines: # format sides = robot.split("" "") left_side = sides[0] right_side = sides[1] left_sides = left_side.split("","") Px = left_sides[0].split(""="")[-1] Py = left_sides[1] right_sides = right_side.split("","") Vx = right_sides[0].split(""="")[-1] Vy = right_sides[1].strip() Px = int(Px) Py = int(Py) Vx = int(Vx) Vy = int(Vy) robots.append([Px,Py,Vx,Vy]) smallest_answer = 999999999999 found_at_second = 0 for second in range(WIDE * TALL): # pattern will repeat every WIDE * TALL times q1 = 0 q2 = 0 q3 = 0 q4 = 0 final_grid = [[0]*WIDE for _ in range(TALL)] for i in range(len(robots)): Px,Py,Vx,Vy = robots[i] new_Py, new_Px = (Px + Vx * second),(Py + Vy * second) # swap X and Y coords because its swapped in the examples too # for matplotlib new_Px, new_Py = (new_Px % TALL), (new_Py % WIDE) final_grid[new_Px][new_Py] += 1 vertical_middle = WIDE // 2 horizontal_middle = TALL // 2 if new_Px < vertical_middle and new_Py < horizontal_middle: q1 += 1 if new_Px > vertical_middle and new_Py < horizontal_middle: q2 += 1 if new_Px < vertical_middle and new_Py > horizontal_middle: q3 += 1 if new_Px > vertical_middle and new_Py > horizontal_middle: q4 += 1 answer = q1 * q2 * q3 * q4 # when answer is smallest, # robots are bunched together to draw the christmas tree, so one corner will have most robots # so when we multiply with other quadrants answer will be smaller # If we have 40 robots, answer is smaller if 37 are in Q1 and 1 each in rest = 37 # If they are evenly split its 10 * 10 * 10 * 10 = 10000 # So we assume that tree is drawn when smallest answer. # Mirrored approach doesnt work if(answer < smallest_answer): # find smallest answer smallest_answer = answer found_at_second = second print(""Found smallest safety factor: "", smallest_answer) print(""at second: "", found_at_second) # Total time complexity # O(WIDE * TALL * n) so kindof O(n) :) # Total space complexity # 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import pathlib import re import math lines = pathlib.Path(""data.txt"").read_text().split(""\n"") iterations = 100 width = 101 height = 103 robots = [] #example input only #width = 11 #height = 7 for line in lines: matches = re.findall(r""[-\d]+"", line) x, y, vx, vy = [int(i) for i in matches] robots.append([x, y, vx, vy]) quadrants = [0, 0, 0, 0] for x, y, vx, vy in robots: x = (x + vx * iterations) % width y = (y + vy * iterations) % height mid_x = width//2 mid_y = height//2 if x < mid_x and y < mid_y: quadrants[0] += 1 elif x < mid_x and y > mid_y: quadrants[1] += 1 elif x > mid_x and y < mid_y: quadrants[2] += 1 elif x > mid_x and y > mid_y: quadrants[3] += 1 safety_factor = math.prod(quadrants) print(safety_factor) pictures = 0 for i in range(1, 100000): new_robots = [] board = [[0 for j in range(width)] for j in range(height)] for x, y, vx, vy in robots: x = (x + vx * i) % width y = (y + vy * i) % height new_robots.append((x, y)) board[y][x] = 1 if len(set(new_robots)) != len(new_robots): continue max_sum = max((sum(row) for row in board)) #the tree picture has 31 robots in a single row if max_sum > 30: print(i) 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"def get_next(pos, move): move_dict = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} return tuple(map(sum, zip(pos, move_dict[move]))) grid = [] moves = [] with open('input.txt') as f: for line in f.read().splitlines(): if line.startswith(""#""): grid += [[c for c in line]] elif not line == """": moves += [c for c in line] for i in range(len(grid)): for j in range(len(grid)): if grid[i][j] == '@': robot_pos = (i, j) break for move in moves: next_i, next_j = get_next(robot_pos, move) if grid[next_i][next_j] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) elif grid[next_i][next_j] == 'O': available = get_next((next_i, next_j), move) while grid[available[0]][available[1]] == 'O': available = get_next(available, move) if grid[available[0]][available[1]] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' grid[available[0]][available[1]] = 'O' robot_pos = (next_i, next_j) total = 0 for i in range(len(grid)): for j in range(len(grid)): if grid[i][j] == 'O': total += 100 * i + j print(total)",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"pos = (0, 0) collision = {} directions = { '<': (-1, 0), '>': (1, 0), '^': (0, -1), 'v': (0, 1), } commands = [] def check_spot(position, directon): if (item := collision.get(position)) is None: return True if item == 'Wall': return False return item.can_move(directon) def can_move(position, direction): x, y = position dir = directions[direction] new_pos = (x + dir[0], y + dir[1]) return check_spot(new_pos, direction) def move(position, direction): dir = directions[direction] return (position[0] + dir[0], position[1] + dir[1]) class Box: def __init__(self, x, y): self.x = x self.y = y @property def position(self): return (self.x, self.y) def can_move(self, direction): x, y = self.position dir = directions[direction] new_pos = (x + dir[0], y + dir[1]) return check_spot(new_pos, direction) def move(self, direction): dir = directions[direction] collision[self.position] = None self.x += dir[0] self.y += dir[1] box = collision.get(self.position) if isinstance(box, Box): box.move(direction) collision[self.position] = self @property def score(self): return self.x + (self.y * 100) with open('input.txt') as f: has_read = False for yi, line in enumerate(f): if not has_read: for xi, c in enumerate(line): if len(line.strip()) == 0: has_read = True continue if not has_read: if c == '#': collision[(xi, yi)] = ""Wall"" elif c == '@': pos = (xi, yi) elif c == 'O': box = Box(xi, yi) collision[(xi, yi)] = box else: commands.append(line.strip()) commands = ''.join(commands) def print_grid(): mx, my = max(collision.keys()) grid = [['.'] * (mx + 1) for _ in range(my + 1)] for k, v in collision.items(): if v is None: continue x, y = k if v == 'Wall': grid[y][x] = '#' elif isinstance(v, Box): bx, by = v.position grid[by][bx] = 'O' grid[pos[1]][pos[0]] = '@' print('\n'.join(''.join(x) for x in grid)) for direction in commands: if can_move(pos, direction): pos = move(pos, direction) if isinstance(collision.get(pos), Box): collision[pos].move(direction) print_grid() boxes = set(collision[x] for x in collision if isinstance(collision[x], Box)) print(sum(x.score for x in boxes))",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"import re from typing import List, Tuple def parse_input(file_path: str) -> Tuple[List[List[str]], List[str]]: with open(file_path, 'r') as file: content = file.read().strip() grid_part, instructions_part = content.split('\n\n') grid = [list(line) for line in grid_part.split('\n')] instructions = list(''.join(instructions_part.split('\n'))) return grid, instructions def find_robot_position(grid: List[List[str]]) -> Tuple[int, int]: for y, row in enumerate(grid): for x, cell in enumerate(row): if cell == '@': return x, y return -1, -1 def move_robot(grid: List[List[str]], instructions: List[str]) -> List[List[str]]: direction_map = { '^': (0, -1), 'v': (0, 1), '<': (-1, 0), '>': (1, 0) } x, y = find_robot_position(grid) for instruction in instructions: dx, dy = direction_map[instruction] new_x, new_y = x + dx, y + dy if not (0 <= new_x < len(grid[0]) and 0 <= new_y < len(grid)): continue if grid[new_y][new_x] == '#': continue elif grid[new_y][new_x] == 'O': # Check if we can push the box box_x, box_y = new_x, new_y while 0 <= box_x + dx < len(grid[0]) and 0 <= box_y + dy < len(grid) and grid[box_y][box_x] == 'O': box_x += dx box_y += dy if not (0 <= box_x + dx < len(grid[0]) and 0 <= box_y + dy < len(grid)) or grid[box_y][box_x] == '#': break else: # Move the robot and push the boxes while (box_x, box_y) != (new_x, new_y): box_x -= dx box_y -= dy grid[box_y + dy][box_x + dx] = 'O' grid[new_y][new_x] = '@' grid[y][x] = '.' x, y = new_x, new_y else: grid[new_y][new_x] = '@' grid[y][x] = '.' x, y = new_x, new_y return grid def calculate_gps_sum(grid: List[List[str]]) -> int: gps_sum = 0 for y, row in enumerate(grid): for x, cell in enumerate(row): if cell == 'O': gps_sum += 100 * y + x return gps_sum if __name__ == ""__main__"": file_path = 'input.txt' grid, instructions = parse_input(file_path) print(""Initial Grid:"") for row in grid: print(''.join(row)) grid = move_robot(grid, instructions) print(""\nFinal Grid:"") for row in grid: print(''.join(row)) gps_sum = calculate_gps_sum(grid) print(f""\nSum of all boxes' GPS coordinates: {gps_sum}"")",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"input = open(""day_15\input.txt"", ""r"").read().splitlines() warehouse_map = [] movements = """" cur_pos = (0,0) total = 0 movement_dict = { ""v"": (1, 0), ""^"": (-1, 0), "">"": (0, 1), ""<"": (0, -1) } def find_open_spot(pos, move): while True: pos = tuple(map(sum, zip(pos, move))) pos_value = warehouse_map[pos[0]][pos[1]] if pos_value == ""#"": return False elif pos_value == ""."": return pos i = 0 while input[i] != """": if ""@"" in input[i]: cur_pos = (i, input[i].index(""@"")) warehouse_map.append(list(input[i])) i += 1 i += 1 while i < len(input): movements += input[i] i += 1 for move in movements: destination = tuple(map(sum, zip(cur_pos, movement_dict[move]))) destination_value = warehouse_map[destination[0]][destination[1]] if destination_value == ""O"": open_spot = find_open_spot(destination, movement_dict[move]) if open_spot: warehouse_map[open_spot[0]][open_spot[1]] = ""O"" warehouse_map[destination[0]][destination[1]] = ""@"" warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" cur_pos = destination elif destination_value == ""."": warehouse_map[destination[0]][destination[1]] = ""@"" warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" cur_pos = destination for i in range(len(warehouse_map)): for j in range(len(warehouse_map[i])): if warehouse_map[i][j] == ""O"": total += 100 * i + j print(f""The sum of all boxes' GPS coordinates is {total}"")",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"from collections import deque def find_start(grid, n, m): for i in range(n): for j in range(m): if grid[i][j] == '@': return (i, j) return (0, 0) def in_bounds(i, j, n, m): return (0 <= i < n) and (0 <= j < m) def move(grid, loc, dir, n, m): curr = (loc[0], loc[1]) addStack = deque() addStack.append('@') while True: newPos = (curr[0] + dir[0], curr[1] + dir[1]) if in_bounds(newPos[0], newPos[1], n, m): val = grid[newPos[0]][newPos[1]] if val == '#': return loc elif val == 'O': addStack.append('O') elif val == '.': revDir = (-dir[0], -dir[1]) while addStack: movedVal = addStack.pop() grid[newPos[0]] = grid[newPos[0]][:newPos[1]] + movedVal + grid[newPos[0]][newPos[1] + 1:] newPos = (newPos[0] + revDir[0], newPos[1] + revDir[1]) grid[loc[0]] = grid[loc[0]][:loc[1]] + '.' + grid[loc[0]][loc[1] + 1:] return (loc[0] + dir[0], loc[1] + dir[1]) else: return loc curr = (newPos[0], newPos[1]) def get_box_coords(grid, instructions): n = len(grid) m = len(grid[0]) loc = find_start(grid, n, m) dirMap = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} for instruction in instructions: loc = move(grid, loc, dirMap.get(instruction), n, m) total = 0 for i in range(n): for j in range(m): if grid[i][j] == 'O': total += ((100 * i) + j) return total if __name__ == ""__main__"": # Open file 'day15-1.txt' in read mode with open('day15-1.txt', 'r') as f: grid = [] ended = False instructions = [] for line in f: if line == '\n': ended = True line = line.strip() if not ended: grid.append(line) else: instructions.extend(list(line)) print(""Final Coordinates of Boxes: "" + str(get_box_coords(grid, instructions)))",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### bool: return 0 <= y < len(self.grid) and 0 <= x < len(self.grid[y]) def is_wall(self, x: int, y: int) -> bool: return self.is_valid(x, y) and self.grid[y][x] == ""#"" def is_box(self, x: int, y: int) -> bool: if self.is_valid(x, y): if self.grid[y][x] == ""O"": return True if self.grid[y][x] == ""["" or self.grid[y][x] == ""]"": return True return False def is_empty(self, x: int, y: int) -> bool: return self.is_valid(x, y) and self.grid[y][x] == ""."" def get_robot_pos(self) -> tuple[int, int]: if self.robot_pos != None: return self.robot_pos for y in range(len(self.grid)): for x in range(len(self.grid[y])): if self.grid[y][x] == ""@"": self.set_robot_pos(x, y) return (x, y) return None def set_robot_pos(self, x: int, y: int): self.robot_pos = (x, y) def swap(self, x1: int, y1: int, x2: int, y2: int): if self.is_valid(x1, y1) and self.is_valid(x2, y2): temp = self.grid[y1][x1] self.grid[y1][x1] = self.grid[y2][x2] self.grid[y2][x2] = temp def __str__(self): out = """" for row in self.grid: line = """" for val in row: line += val out += line + ""\n"" return out def parse() -> tuple[Grid, str]: grid_input, moves = open(""input.txt"").read().split(""\n\n"") grid = Grid([[val for val in line] for line in grid_input.splitlines()]) return (grid, moves) def move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): if move(grid, new_x, new_y, delta_x, delta_y): grid.swap(new_x, new_y, x, y) return True else: return False if grid.is_wall(new_x, new_y): return False return False def can_move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): return True if grid.is_box(new_x, new_y): possible_to_move = False if delta_y != 0: if grid.grid[new_y][new_x] == ""["": possible_to_move |= can_move(grid, new_x + 1, new_y, delta_x, delta_y) else: possible_to_move |= can_move(grid, new_x - 1, new_y, delta_x, delta_y) return possible_to_move and can_move(grid, new_x, new_y, delta_x, delta_y) else: return can_move(grid, new_x, new_y, delta_x, delta_y) if grid.is_wall(new_x, new_y): return False return False def wide_move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): if delta_y != 0: if grid.grid[new_y][new_x] == ""["": wide_move(grid, new_x + 1, new_y, delta_x, delta_y) else: wide_move(grid, new_x - 1, new_y, delta_x, delta_y) wide_move(grid, new_x, new_y, delta_x, delta_y) grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): return False def part1(): grid, moves = parse() for robot_move in moves: x, y = grid.get_robot_pos() delta_x, delta_y = (1 if robot_move == "">"" else -1 if robot_move == ""<"" else 0, 1 if robot_move == ""v"" else -1 if robot_move == ""^"" else 0) if move(grid, x, y, delta_x, delta_y): grid.set_robot_pos(x + delta_x, y + delta_y) print(grid) coords = [100 * y + x if grid.is_box(x, y) else 0 for y in range(len(grid.grid)) for x in range(len(grid.grid[y]))] print(sum(coords)) def part2(): grid, moves = parse() new_grid = [[]] for idx, row in enumerate(grid.grid): new_grid.append([]) for val in row: if val == ""#"": new_grid[idx].append(""#"") new_grid[idx].append(""#"") elif val == ""O"": new_grid[idx].append(""["") new_grid[idx].append(""]"") elif val == ""."": new_grid[idx].append(""."") new_grid[idx].append(""."") elif val == ""@"": new_grid[idx].append(""@"") new_grid[idx].append(""."") grid.grid = new_grid for robot_move in moves: x, y = grid.get_robot_pos() delta_x, delta_y = (1 if robot_move == "">"" else -1 if robot_move == ""<"" else 0, 1 if robot_move == ""v"" else -1 if robot_move == ""^"" else 0) if can_move(grid, x, y, delta_x, delta_y): if wide_move(grid, x, y, delta_x, delta_y): grid.set_robot_pos(x + delta_x, y + delta_y) # print(grid) print(grid) coords = [100 * y + x if grid.grid[y][x] == ""["" else 0 for y in range(len(grid.grid)) for x in range(len(grid.grid[y]))] print(sum(coords)) part2()",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### ': (0, 1), 'v': (1, 0), '<': (0, -1)} return tuple(map(sum, zip(pos, move_dict[move]))) def get_chars(c): if c == '@': return '@.' elif c == 'O': return '[]' else: return c + c def can_push(grid, pos, move): if move in ['<', '>']: next_pos = get_next(get_next(pos, move), move) if grid[next_pos[0]][next_pos[1]] == '.': return True if grid[next_pos[0]][next_pos[1]] in ['[', ']']: return can_push(grid, next_pos, move) return False if move in ['^', 'v']: if grid[pos[0]][pos[1]] == '[': left, right = (pos, (pos[0], pos[1] + 1)) else: left, right = ((pos[0], pos[1] - 1), pos) next_left = get_next(left, move) next_right = get_next(right, move) if grid[next_left[0]][next_left[1]] == '#' or grid[next_right[0]][next_right[1]] == '#': return False return (grid[next_left[0]][next_left[1]] == '.' or can_push(grid, next_left, move)) and (grid[next_right[0]][next_right[1]] == '.' or can_push(grid, next_right, move)) def push(grid, pos, move): if move in ['<', '>']: j = pos[1] while grid[pos[0]][j] != '.': _, j = get_next((pos[0], j), move) if j < pos[1]: grid[pos[0]][j:pos[1]] = grid[pos[0]][j+1:pos[1]+1] else: grid[pos[0]][pos[1]+1:j+1] = grid[pos[0]][pos[1]:j] if move in ['^', 'v']: if grid[pos[0]][pos[1]] == '[': left, right = (pos, (pos[0], pos[1] + 1)) else: left, right = ((pos[0], pos[1] - 1), pos) next_left = get_next(left, move) next_right = get_next(right, move) if grid[next_left[0]][next_left[1]] == '[': push(grid, next_left, move) else: if grid[next_left[0]][next_left[1]] == ']': push(grid, next_left, move) if grid[next_right[0]][next_right[1]] == '[': push(grid, next_right, move) grid[next_left[0]][next_left[1]] = '[' grid[next_right[0]][next_right[1]] = ']' grid[left[0]][left[1]] = '.' grid[right[0]][right[1]] = '.' def print_grid(grid): for line in grid: print("""".join(line)) grid = [] moves = [] with open('input.txt') as f: for line in f.read().splitlines(): if line.startswith(""#""): row = """" for c in line: row += get_chars(c) grid += [[c for c in row]] elif not line == """": moves += [c for c in line] for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == '@': robot_pos = (i, j) break for move in moves: next_i, next_j = get_next(robot_pos, move) if grid[next_i][next_j] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) elif grid[next_i][next_j] in ['[', ']']: if can_push(grid, (next_i, next_j), move): push(grid, (next_i, next_j), move) grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) total = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == '[': total += 100 * i + j print(total)",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### = width or y < 0 or y >= height: return False if (x, y) in walls: return False # horizontal move: if move[1] == 0: # left move: if move[0] == -1: if (x + move[0], x, y) in boxes: # need to move (x + move[0], x, y) box to left to_move.add((x + move[0], x, y)) return can_move(x + move[0], y, move, width, height, to_move) # right move else: if (x, x + move[0], y) in boxes: to_move.add((x, x + move[0], y)) return can_move(x + move[0], y, move, width, height, to_move) # vertical move: if move[0] == 0: if (x - 1, x, y) in boxes: to_move.add((x - 1, x, y)) return can_move(x - 1, y, move, width, height, to_move) and can_move(x, y, move, width, height, to_move) if (x, x + 1, y) in boxes: to_move.add((x, x + 1, y)) return can_move(x, y, move, width, height, to_move) and can_move(x + 1, y, move, width, height, to_move) return True def move_robot(x, y, width, height): for move in moves: to_move = set() if can_move(x, y, move, width, height, to_move): for each in to_move: boxes.remove(each) for each in to_move: boxes.add((each[0] + move[0], each[1] + move[0], each[2] + move[1])) x += move[0] y += move[1] def main(): warehouse_done = False robot_x = 0 robot_y = 0 width = 0 height = 0 y = 0 with open(""15_input.txt"", ""r"") as f: for line in f: line = line.strip() if line != """": if warehouse_done: moves.extend([char_map[c] for c in line]) else: x = 0 for char in line: if char == '#': walls.append((x, y)) walls.append((x + 1, y)) elif char == ""O"": boxes.add((x, x + 1, y)) elif char == ""@"": robot_x = x robot_y = y x += 2 if x > width: width = x else: warehouse_done = True if not warehouse_done: y += 1 if y > height: height = y move_robot(robot_x, robot_y, width, height) result = 0 for box in boxes: result += 100 * box[2] + box[0] print(result) char_map = {""^"": (0, -1), "">"": (1, 0), ""<"": (-1, 0), ""v"": (0, 1)} walls = [] boxes = set() moves = [] if __name__ == ""__main__"": main()",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### "": (1, 0), ""^"": (0, -1), ""v"": (0, 1)} class Warehouse: def __init__(self, width): self.width = width self.robot_location = (0, 0) self.walls = [] self.boxes = {} self.moves = [] def print(self): for y in range(self.height): for x in range(self.width): p = (x, y) if p == self.robot_location: print(ROBOT, end="""") elif p in self.boxes: print(self.boxes[p], end="""") elif p in self.walls: print(WALL, end="""") else: print(""."", end="""") print() def add_wall(self, wall): wall_position = (wall[0] * 2, wall[1]) self.walls.append(wall_position) self.walls.append((wall_position[0] + 1, wall_position[1])) def add_box(self, box): box_position = (box[0] * 2, box[1]) self.boxes[box_position] = BOX_LEFT self.boxes[(box_position[0] + 1, box_position[1])] = BOX_RIGHT def set_robot_location(self, location): self.robot_location = (location[0] * 2, location[1]) def set_height(self, height): self.height = height def print_moves(self): for move in self.moves: print(move) def move(self, move): dx, dy = MOVES[move] new_location = (self.robot_location[0] + dx, self.robot_location[1] + dy) if new_location in self.walls: return if new_location in self.boxes: self.move_box(new_location, move) if new_location in self.boxes or new_location in self.walls: return self.robot_location = new_location def move_box(self, box, move): dx, dy = MOVES[move] if self.boxes[box] == BOX_RIGHT: box_left = (box[0] - 1, box[1]) box_right = box new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) else: box_left = box box_right = (box[0] + 1, box[1]) new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) # if horizontal if move == ""<"" or move == "">"": if self.boxes[box] == BOX_RIGHT: if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_right != box_left: if new_box_left in self.boxes or new_box_right in self.boxes: if not self.move_box(new_box_left, move): return False if new_box_left in self.boxes: if not self.move_box(new_box_left, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT elif self.boxes[box] == BOX_LEFT: if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_left != box_right: if new_box_left in self.boxes or new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False if new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT else: if self.collision_check(box, move): return False if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_left in self.boxes: if not self.move_box(new_box_left, move): return False if new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT return True def collision_check(self, box, move): collision = False dx, dy = MOVES[move] if self.boxes[box] == BOX_RIGHT: box_left = (box[0] - 1, box[1]) box_right = box new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) else: box_left = box box_right = (box[0] + 1, box[1]) new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) if new_box_left in self.walls or new_box_right in self.walls: return True if new_box_left in self.boxes: if self.collision_check(new_box_left, move): return True if new_box_right in self.boxes: if self.collision_check(new_box_right, move): return True return collision def run(self): for move in self.moves: self.move(move) def sum_of_box_locations(self): result = 0 for x, y in self.boxes: if self.boxes[(x, y)] == BOX_LEFT: result += x + 100 * y return result def read_file(): with open(INPUT_FILE, ""r"") as f: lines = f.readlines() width = len(lines[0].strip()) * 2 warehouse = Warehouse(width) moves = [] for y, line in enumerate(lines): if line[0] == ""#"": for x, c in enumerate(line.strip()): p = (x, y) if c == WALL: warehouse.add_wall(p) elif c == ROBOT: warehouse.set_robot_location(p) elif c == BOX: warehouse.add_box(p) elif line[0] == ""\n"": warehouse.set_height(y) else: for move in line.strip(): moves.append(move) warehouse.moves = moves return warehouse warehouse = read_file() warehouse.print() warehouse.run() print(warehouse.sum_of_box_locations())",python 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### "": (0, 1), ""<"": (0, -1) } def move_horizontally(pos, move): while True: pos = tuple(map(sum, zip(pos, move))) pos_value = warehouse_map[pos[0]][pos[1]] if pos_value == ""#"": return False elif pos_value == ""."": if move[1] == 1: warehouse_map[pos[0]][pos[1]] = ""]"" else: warehouse_map[pos[0]][pos[1]] = ""["" while warehouse_map[pos[0]][pos[1] - move[1]] != ""@"": pos = (pos[0], pos[1] - move[1]) warehouse_map[pos[0]][pos[1]] = ""]"" if warehouse_map[pos[0]][pos[1]] == ""["" else ""["" return True def move_vertically(positions, move): involved_boxes = set(positions) next_positions = set(positions) while True: involved_boxes |= next_positions if len(next_positions) == 0: boxes_dict = {(x,y): warehouse_map[x][y] for (x,y) in involved_boxes} for box in involved_boxes: if not (box[0] - move[0], box[1]) in boxes_dict: warehouse_map[box[0]][box[1]] = ""."" warehouse_map[box[0] + move[0]][box[1]] = boxes_dict[box] return True positions = next_positions.copy() next_positions.clear() for pos in positions: next_pos = tuple(map(sum, zip(pos, move))) next_pos_value = warehouse_map[next_pos[0]][next_pos[1]] if next_pos_value == ""["": next_positions.add(next_pos) next_positions.add((next_pos[0], next_pos[1] + 1)) elif next_pos_value == ""]"": next_positions.add(next_pos) next_positions.add((next_pos[0], next_pos[1] - 1)) elif next_pos_value == ""#"": return False i = 0 while input[i] != """": modified_input = [] for char in input[i]: if char == ""#"": modified_input += [""#"", ""#""] elif char == ""O"": modified_input += [""["", ""]""] elif char == ""."": modified_input += [""."", "".""] else: modified_input += [""@"", "".""] cur_pos = (i, modified_input.index(""@"")) warehouse_map.append(modified_input) i += 1 i += 1 while i < len(input): movements += input[i] i += 1 for move in movements: destination = tuple(map(sum, zip(cur_pos, movement_dict[move]))) destination_value = warehouse_map[destination[0]][destination[1]] if destination_value == ""["" or destination_value == ""]"": if move == ""<"" or move == "">"": open_spot = move_horizontally(destination, movement_dict[move]) else: if destination_value == ""["": open_spot = move_vertically([destination, (destination[0], destination[1] + 1)], movement_dict[move]) else: open_spot = move_vertically([destination, (destination[0], destination[1] - 1)], movement_dict[move]) if open_spot: warehouse_map[destination[0]][destination[1]] = ""@"" warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" cur_pos = destination elif destination_value == ""."": warehouse_map[destination[0]][destination[1]] = ""@"" warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" cur_pos = destination for i in range(len(warehouse_map)): for j in range(len(warehouse_map[i])): if warehouse_map[i][j] == ""["": total += 100 * i + j print(f""The sum of all boxes' final GPS coordinates is {total}"")",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"from heapq import heappop, heappush def get_lowest_score(maze): m = len(maze) n = len(maze[0]) start = (-1, -1) end = (-1, -1) for i in range(m): for j in range(n): if maze[i][j] == 'S': start = (i, j) elif maze[i][j] == 'E': end = (i, j) maze[end[0]][end[1]] = '.' dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] visited = set() heap = [(0, 0, *start)] while heap: score, dI, i, j = heappop(heap) if (i, j) == end: break if (dI, i, j) in visited: continue visited.add((dI, i, j)) x = i + dirs[dI][0] y = j + dirs[dI][1] if maze[x][y] == '.' and (dI, x, y) not in visited: heappush(heap, (score + 1, dI, x, y)) left = (dI - 1) % 4 if (left, i, j) not in visited: heappush(heap, (score + 1000, left, i, j)) right = (dI + 1) % 4 if (right, i, j) not in visited: heappush(heap, (score + 1000, right, i, j)) return score if __name__ == ""__main__"": # Open file 'day16-1.txt' in read mode with open('day16-1.txt', 'r') as f: maze = [] for line in f: line = line.strip() maze.append(list(line)) print(""Lowest Score:"", get_lowest_score(maze))",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"import heapq def dijkstra(grid): for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': start = ((i, j), (0, 1)) pq = [(0, start)] costs = { start: 0 } while len(pq) > 0: cost, (pos, direction) = heapq.heappop(pq) if grid[pos[0]][pos[1]] == 'E': return cost turns = [(1000, (pos, turn)) for turn in [(direction[1] * i, direction[0] * i) for i in [-1,1]]] step = tuple(map(sum, zip(pos, direction))) neighbors = turns + ([(1, (step, direction))] if grid[step[0]][step[1]] != '#' else []) for neighbor in neighbors: next_cost = cost + neighbor[0] if next_cost < costs.get(neighbor[1], float('inf')): heapq.heappush(pq, (next_cost, neighbor[1])) costs[neighbor[1]] = next_cost print(""Could not find min path"") return None with open('input.txt') as f: grid = [[c for c in line] for line in f.read().splitlines()] print(dijkstra(grid))",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"# Python heap implementation from heapq import heappush, heappop with open(""./day_16.in"") as fin: grid = fin.read().strip().split(""\n"") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == ""S"": start = (i, j) elif grid[i][j] == ""E"": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # DIjkstra's q = [(0, 0, *start)] seen = set() while len(q) > 0: top = heappop(q) cost, d, i, j = top if (d, i, j) in seen: continue seen.add((d, i, j)) if grid[i][j] == ""#"": continue if grid[i][j] == ""E"": print(cost) break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(cost + 1, d, ii, jj), (cost + 1000, (d + 1) % 4, i, j), (cost + 1000, (d + 3) % 4, i, j)]: if nbr[1:] in seen: continue heappush(q, nbr)",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"import re from typing import List, Tuple import heapq def parse_input(file_path: str): """""" Parse the input file to extract the data. Args: file_path (str): The path to the input file. Returns: List[str]: A list of strings representing the data from the file. """""" with open(file_path, 'r') as file: return [line.strip() for line in file] def find_starting_position(grid: List[str]) -> Tuple[int, int]: """""" Find the starting position marked as 'S' in the grid. Args: grid (List[str]): A list of strings representing the grid. Returns: Tuple[int, int]: A tuple containing the row and column indices of the starting position. """""" for i, row in enumerate(grid): for j, cell in enumerate(row): if cell == 'S': return i, j return -1, -1 # given a grid and a current position as well as a direction, # return the list of next possible moves either moving forward in the current direction or turning left or right def get_possible_moves(grid: List[str], i: int, j: int, direction: str) -> List[Tuple[int, int, str]]: """""" Get the possible moves from the current position in the grid. Args: grid (List[str]): A list of strings representing the grid. i (int): The row index of the current position. j (int): The column index of the current position. direction (str): The current direction ('N', 'E', 'S', 'W'). Returns: List[Tuple[int, int, str]]: A list of tuples where each tuple contains the row index, column index, and the direction of the possible moves. """""" rows, cols = len(grid), len(grid[0]) moves = {'N': (-1, 0), 'E': (0, 1), 'S': (1, 0), 'W': (0, -1)} left_turns = {'N': 'W', 'E': 'N', 'S': 'E', 'W': 'S'} right_turns = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'} possible_moves = [] # Check forward move dx, dy = moves[direction] new_i, new_j = i + dx, j + dy if 0 <= new_i < rows and 0 <= new_j < cols and grid[new_i][new_j] != '#': possible_moves.append((new_i, new_j, direction)) # Check left turn left_direction = left_turns[direction] left_dx, left_dy = moves[left_direction] left_i, left_j = i + left_dx, j + left_dy if 0 <= left_i < rows and 0 <= left_j < cols and grid[left_i][left_j] != '#': possible_moves.append((i, j, left_direction)) # Check right turn right_direction = right_turns[direction] right_dx, right_dy = moves[right_direction] right_i, right_j = i + right_dx, j + right_dy if 0 <= right_i < rows and 0 <= right_j < cols and grid[right_i][right_j] != '#': possible_moves.append((i, j, right_direction)) return possible_moves def find_lowest_score(grid: List[str], i: int, j: int, direction: str) -> int: """""" Finds the shortest path in a grid from a starting position (i, j) in a given direction. Args: grid (List[str]): A 2D grid represented as a list of strings. i (int): The starting row index. j (int): The starting column index. direction (str): The initial direction of movement. Returns: int: The shortest path score to reach the target 'E' in the grid. If the target is not reachable, returns float('inf'). """""" visited = set() heap = [(0, i, j, direction)] # (score, row, col, direction) while heap: score, i, j, direction = heapq.heappop(heap) if (i, j, direction) in visited: continue visited.add((i, j, direction)) if grid[i][j] == 'E': return score for new_i, new_j, new_direction in get_possible_moves(grid, i, j, direction): new_score = score + 1 if new_direction == direction else score + 1000 heapq.heappush(heap, (new_score, new_i, new_j, new_direction)) return float('inf') if __name__ == ""__main__"": file_path = 'input.txt' parsed_data = parse_input(file_path) i, j = find_starting_position(parsed_data) score = find_lowest_score(parsed_data, i, j, 'E') print(score)",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"# Python heap implementation from heapq import heappush, heappop from collections import defaultdict with open(""16.in"") as fin: grid = fin.read().strip().split(""\n"") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == ""S"": start = (i, j) elif grid[i][j] == ""E"": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # Dijkstra's q = [(0, 0, *start, 0, *start)] cost = {} deps = defaultdict(list) while len(q) > 0: top = heappop(q) c, d, i, j, pd, pi, pj = top if (d, i, j) in cost: if cost[(d, i, j)] == c: deps[(d, i, j)].append((pd, pi, pj)) continue never_seen_pos = True for newd in range(4): if (newd, i, j) in cost: never_seen_pos = True break if never_seen_pos: deps[(d, i, j)].append((pd, pi, pj)) cost[(d, i, j)] = c if grid[i][j] == ""#"": continue if grid[i][j] == ""E"": end_dir = d print(c) break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(c + 1, d, ii, jj, d, i, j), (c + 1000, (d + 1) % 4, i, j, d, i, j), (c + 1000, (d + 3) % 4, i, j, d, i, j)]: heappush(q, nbr)",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"# Python heap implementation from heapq import heappush, heappop from collections import defaultdict with open(""16.in"") as fin: grid = fin.read().strip().split(""\n"") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == ""S"": start = (i, j) elif grid[i][j] == ""E"": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # Dijkstra's q = [(0, 0, *start, 0, *start)] cost = {} deps = defaultdict(list) while len(q) > 0: top = heappop(q) c, d, i, j, pd, pi, pj = top if (d, i, j) in cost: if cost[(d, i, j)] == c: deps[(d, i, j)].append((pd, pi, pj)) continue never_seen_pos = True for newd in range(4): if (newd, i, j) in cost: never_seen_pos = True break if never_seen_pos: deps[(d, i, j)].append((pd, pi, pj)) cost[(d, i, j)] = c if grid[i][j] == ""#"": continue if grid[i][j] == ""E"": end_dir = d break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(c + 1, d, ii, jj, d, i, j), (c + 1000, (d + 1) % 4, i, j, d, i, j), (c + 1000, (d + 3) % 4, i, j, d, i, j)]: heappush(q, nbr) # Go back through deps stack = [(end_dir, *end)] seen = set() seen_pos = set() while len(stack) > 0: top = stack.pop() if top in seen: continue seen.add(top) seen_pos.add(top[1:]) for nbr in deps[top]: stack.append(nbr) print(len(seen_pos))",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"#d16 part 2 from heapq import heappop, heappush def part2(puzzle_input): grid = puzzle_input.split('\n') m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] == 'S': start = (i, j) elif grid[i][j] == 'E': end = (i, j) grid[end[0]] = grid[end[0]].replace('E', '.') def can_visit(d, i, j, score): prev_score = visited.get((d, i, j)) if prev_score and prev_score < score: return False visited[(d, i, j)] = score return True directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] heap = [(0, 0, *start, {start})] visited = {} lowest_score = None winning_paths = set() while heap: score, d, i, j, path = heappop(heap) if lowest_score and lowest_score < score: break if (i, j) == end: lowest_score = score winning_paths |= path continue if not can_visit(d, i, j, score): continue x = i + directions[d][0] y = j + directions[d][1] if grid[x][y] == '.' and can_visit(d, x, y, score+1): heappush(heap, (score + 1, d, x, y, path | {(x, y)})) left = (d - 1) % 4 if can_visit(left, i, j, score + 1000): heappush(heap, (score + 1000, left, i, j, path)) right = (d + 1) % 4 if can_visit(right, i, j, score + 1000): heappush(heap, (score + 1000, right, i, j, path)) return len(winning_paths) with open(r'16.txt','r') as f: input_text = f.read() res = part2(input_text) res",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import heapq from sys import maxsize maze = open(""16.txt"").read().splitlines() seen = [[[maxsize for _ in range(4)] for x in range(len(maze[0]))] for y in range(len(maze))] velocities = [(-1, 0), (0, 1), (1, 0), (0, -1)] start_pos = None end_pos = None for j, r in enumerate(maze): for i, c in enumerate(r): if c == 'S': start_pos = (j, i) if c == 'E': end_pos = (j, i) # TODO For C, need a better track of path than shoving it all into a list lmao # I saw on da reddit a lot of folks searching backwards through the maze scores # for all scores where score is -1 or -1001 from current, starting at end. pq = [(0, (*start_pos, 1), [start_pos])] # start facing EAST paths = [] best_score = maxsize while pq and pq[0][0] <= best_score: score, (y, x, dir), path = heapq.heappop(pq) if (y, x) == end_pos: best_score = score paths.append(path) continue if seen[y][x][dir] < score: continue seen[y][x][dir] = score for i in range(4): dy, dx = velocities[i] ny, nx = y + dy, x + dx if maze[ny][nx] != '#' and (ny, nx) not in path: cost = 1 if i == dir else 1001 heapq.heappush(pq, (score + cost, (ny, nx, i), path + [(ny, nx)])) seats = set() for path in paths: seats |= set(path) print(len(seats))",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import heapq from typing import Dict, List, Tuple class MinHeap: """""" Min heap implementation using heapq library """""" def __init__(self): self.heap = [] def insert(self, element: Tuple[int, str]): heapq.heappush(self.heap, element) def extract_min(self) -> Tuple[int, str]: return heapq.heappop(self.heap) def size(self) -> int: return len(self.heap) DIRECTIONS = [ {""x"": 1, ""y"": 0}, {""x"": 0, ""y"": 1}, {""x"": -1, ""y"": 0}, {""x"": 0, ""y"": -1}, ] def dijkstra( graph: Dict[str, Dict[str, int]], start: Dict[str, int], directionless: bool ) -> Dict[str, int]: queue = MinHeap() distances = {} starting_key = ( f""{start['x']},{start['y']},0"" if not directionless else f""{start['x']},{start['y']}"" ) queue.insert((0, starting_key)) distances[starting_key] = 0 while queue.size() > 0: current_score, current_node = queue.extract_min() if distances[current_node] < current_score: continue if current_node not in graph: continue for next_node, weight in graph[current_node].items(): new_score = current_score + weight if next_node not in distances or distances[next_node] > new_score: distances[next_node] = new_score queue.insert((new_score, next_node)) return distances def parse_grid(grid: List[str]): width, height = len(grid[0]), len(grid) start = {""x"": 0, ""y"": 0} end = {""x"": 0, ""y"": 0} forward = {} reverse = {} for y in range(height): for x in range(width): if grid[y][x] == ""S"": start = {""x"": x, ""y"": y} if grid[y][x] == ""E"": end = {""x"": x, ""y"": y} if grid[y][x] != ""#"": for i, direction in enumerate(DIRECTIONS): position = {""x"": x + direction[""x""], ""y"": y + direction[""y""]} key = f""{x},{y},{i}"" move_key = f""{position['x']},{position['y']},{i}"" if ( 0 <= position[""x""] < width and 0 <= position[""y""] < height and grid[position[""y""]][position[""x""]] != ""#"" ): forward.setdefault(key, {})[move_key] = 1 reverse.setdefault(move_key, {})[key] = 1 for rotate_key in [ f""{x},{y},{(i + 3) % 4}"", f""{x},{y},{(i + 1) % 4}"", ]: forward.setdefault(key, {})[rotate_key] = 1000 reverse.setdefault(rotate_key, {})[key] = 1000 for i in range(len(DIRECTIONS)): key = f""{end['x']},{end['y']}"" rotate_key = f""{end['x']},{end['y']},{i}"" forward.setdefault(rotate_key, {})[key] = 0 reverse.setdefault(key, {})[rotate_key] = 0 return {""start"": start, ""end"": end, ""forward"": forward, ""reverse"": reverse} def tilesApartFromMaze() -> int: with open(""input.txt"") as file: con = file.read() grid = con.strip().split(""\n"") parsed = parse_grid(grid) from_start = dijkstra(parsed[""forward""], parsed[""start""], False) to_end = dijkstra(parsed[""reverse""], parsed[""end""], True) end_key = f""{parsed['end']['x']},{parsed['end']['y']}"" target = from_start[end_key] spaces = set() for position in from_start: if ( position != end_key and from_start[position] + to_end.get(position, float(""inf"")) == target ): x, y, *_ = position.split("","") # Unpack and ignore direction in the key spaces.add(f""{x},{y}"") print(len(spaces)) tilesApartFromMaze()",python 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. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import time from collections import deque POSSIBLE_DIRS = (1, -1, 1j, -1j) def calculate_min_scores( start: complex, walls: set[complex] ) -> dict[complex, dict[complex, int]]: scores = {1: {start: 0}, -1: {}, 1j: {}, -1j: {}} points = deque([(start, 1)]) while points: p, d = points.popleft() score = scores[d][p] for move, dir, cost in [(p + d, d, 1), (p, d * -1j, 1000), (p, d * 1j, 1000)]: if move in walls: continue if move in scores[dir] and scores[dir][move] <= score + cost: continue scores[dir][move] = score + cost points.append((move, dir)) return scores def parse(text: str): walls: set[complex] = set() start: complex = 0j end: complex = 0j for y, row in enumerate(text.splitlines()): for x, c in enumerate(row): match c: case ""#"": walls.add(complex(x, y)) case ""S"": start = complex(x, y) case ""E"": end = complex(x, y) case _: pass return start, end, walls def solve_part_2(text: str): start, end, walls = parse(text) scores = calculate_min_scores(start, walls) path: set[complex] = {start, end} cost = min(scores[dir][end] for dir in POSSIBLE_DIRS if end in scores[dir]) points = deque( [ (end, dir, cost) for dir in POSSIBLE_DIRS if end in scores[dir] and scores[dir][end] == cost ] ) while points: p, d, cost = points.popleft() for move, dir, c1 in [ (p - d, d, cost - 1), (p, d * 1j, cost - 1000), (p, d * -1j, cost - 1000), ]: if move in scores[dir] and scores[dir][move] == c1: path.add(move) points.append((move, dir, c1)) return len(path) if __name__ == ""__main__"": with open(""input.txt"", ""r"") as f: quiz_input = f.read() p_2_solution = int(solve_part_2(quiz_input))",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","ADV = 0 BXL = 1 BST = 2 JNZ = 3 BXC = 4 OUT = 5 BDV = 6 CDV = 7 def get_combo_operand(operand, reg): if 0 <= operand <= 3: return operand if 4 <= operand <= 6: return reg[chr(ord('A') + operand - 4)] raise ValueError(f""Unexpected operand {operand}"") with open('input.txt') as f: lines = f.read().splitlines() reg = { 'A': int(lines[0].split("": "")[1]), 'B': int(lines[1].split("": "")[1]), 'C': int(lines[2].split("": "")[1])} instructions = list(map(int, lines[4].split("": "")[1].split("",""))) output = [] instr_ptr = 0 while instr_ptr < len(instructions): jump = False opcode, operand = instructions[instr_ptr:instr_ptr + 2] if opcode == ADV: reg['A'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) elif opcode == BXL: reg['B'] = reg['B'] ^ operand elif opcode == BST: reg['B'] = get_combo_operand(operand, reg) % 8 elif opcode == JNZ: if reg['A'] != 0: instr_ptr = operand jump = True elif opcode == BXC: reg['B'] = reg['B'] ^ reg['C'] elif opcode == OUT: output += [get_combo_operand(operand, reg) % 8] elif opcode == BDV: reg['B'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) elif opcode == CDV: reg['C'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) else: raise ValueError(f""Unexpected opcode {opcode}"") if not jump: instr_ptr += 2 print("","".join(map(str, output)))",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","from collections.abc import Generator def get_out(a: int) -> int: b = (a % 8) ^ 1 return (b ^ (a // 2**b) ^ 4) % 8 def get_all_out(a: int) -> list[int]: out: list[int] = [] while a > 0: out.append(get_out(a)) a = a // 8 return out def next_A(seq: int, a: int) -> Generator[int]: while True: out = get_out(a) if out == seq: yield a a += 1 def main() -> None: seq: list[int] = [0, 3, 5, 5, 3, 0, 4, 1, 7, 4, 5, 7, 1, 1, 4, 2] a: int = 0 steps: dict[int, Generator[int]] = {} i = 1 while True: if i == len(seq) + 1: break s = seq[i - 1] if i not in steps: steps[i] = next_A(s, a) a = next(steps[i]) out = get_all_out(a) if out == list(reversed(seq[:i])): i += 1 a *= 8 print(a // 8) if __name__ == ""__main__"": main()",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","#!/usr/bin/python3 def combo_operand(op:int) -> int: combo_operands = {4:""A"",5:""B"",6:""C""} return op if op < 4 else registers[combo_operands[op]] def adv(op:int) -> int: return int(registers[""A""] / 2 ** combo_operand(op)) def bxl(op:int) -> int: return registers[""B""] ^ op def bst(op:int) -> int: return combo_operand(op) % 8 def jnz(inst_pointer:int, op:int) -> int: return op if registers[""A""] != 0 else inst_pointer + 2 def bxc(op:int) -> int: return registers[""B""] ^ registers[""C""] def out(op:int) -> str: return str(combo_operand(op) % 8) def bdv(op:int) -> int: return adv(op) def cdv(op:int) -> int: return adv(op) with open(""input.txt"") as file: registers = {} for line in file: if ""Register"" in line: line = line.strip().split() registers[line[1].strip("":"")] = int(line[2]) elif ""Program"" in line: line = line.strip(""Program: "") program = [int(n) for n in line.strip().split("","")] instruction_pointer = 0 output = [] while instruction_pointer < len(program): opcode = program[instruction_pointer] operand = program[instruction_pointer + 1] if opcode == 0: registers[""A""] = adv(operand) elif opcode == 1: registers[""B""] = bxl(operand) elif opcode == 2: registers[""B""] = bst(operand) elif opcode == 3: instruction_pointer = jnz(instruction_pointer, operand) continue elif opcode == 4: registers[""B""] = bxc(operand) elif opcode == 5: output.append(out(operand)) elif opcode == 6: registers[""B""] = bdv(operand) elif opcode == 7: registers[""C""] = cdv(operand) instruction_pointer += 2 print(""Program output:"", "","".join(output))",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","output = """" i = 0 def get_result_string(regs, instructions): global output n = len(instructions) global i def get_combo(operand): if 0 <= operand < 4: return operand elif operand == 4: return regs['a'] elif operand == 5: return regs['b'] elif operand == 6: return regs['c'] return 0 def adv(operand): operand = get_combo(operand) regs['a'] = int(regs['a'] // (2**operand)) return def bxl(operand): regs['b'] = int(regs['b'] ^ operand) return def bst(operand): operand = get_combo(operand) regs['b'] = int(operand % 8) return def jnz(operand): global i if regs['a'] != 0: i = int(operand) - 1 return def bxc(operand): regs['b'] = int(regs['b'] ^ regs['c']) return def out(operand): global output operand = get_combo(operand) output += str(operand % 8) return def bdv(operand): operand = get_combo(operand) regs['b'] = int(regs['a'] // (2**operand)) return def cdv(operand): operand = get_combo(operand) regs['c'] = int(regs['a'] // (2**operand)) return while i < n: curr = instructions[i] if curr[0] == 0: adv(curr[1]) elif curr[0] == 1: bxl(curr[1]) elif curr[0] == 2: bst(curr[1]) elif curr[0] == 3: jnz(curr[1]) elif curr[0] == 4: bxc(curr[1]) elif curr[0] == 5: out(curr[1]) elif curr[0] == 6: bdv(curr[1]) elif curr[0] == 7: cdv(curr[1]) i += 1 return ','.join(list(output)) if __name__ == ""__main__"": regs = {} instructions = [] # Open file 'day17-1.txt' in read mode with open('day17-1.txt', 'r') as f: for line in f: line = line.strip() if regs.get('a') is None: regs['a'] = int(line[line.find(':') + 2:]) elif regs.get('b') is None: regs['b'] = int(line[line.find(':') + 2:]) elif regs.get('c') is None: regs['c'] = int(line[line.find(':') + 2:]) else: instructions = [int(val) for val in line[line.find(':') + 2:].split(',') if len(val) == 1] instructions = [(instructions[i], instructions[i + 1]) for i in range(0, len(instructions), 2)] print(""Result String:"", get_result_string(regs, instructions))",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","import re instr_map = { 0: lambda operand: adv(operand), 1: lambda operand: bxl(operand), 2: lambda operand: bst(operand), 3: lambda operand: jnz(operand), 4: lambda operand: bxc(operand), 5: lambda operand: out(operand), 6: lambda operand: bdv(operand), 7: lambda operand: cdv(operand) } def combo(operand): global reg_a, reg_b, reg_c if 0 <= operand <= 3: return operand elif operand == 4: return reg_a elif operand == 5: return reg_b elif operand == 6: return reg_c def adv(operand): global reg_a reg_a = reg_a // (2 ** combo(operand)) def bxl(operand): global reg_b reg_b = reg_b ^ operand def bst(operand): global reg_b reg_b = combo(operand) % 8 def bxc(operand): global reg_b, reg_c reg_b = reg_b ^ reg_c def out(operand): print(f'{combo(operand) % 8},', end='') def bdv(operand): global reg_a, reg_b reg_b = reg_a // (2 ** combo(operand)) def cdv(operand): global reg_a, reg_c reg_c = reg_a // (2 ** combo(operand)) def jnz(operand): global ip, reg_a if reg_a != 0: ip = operand ip -= 2 def main(): global reg_a, reg_b, reg_c, ip with open(""17_input.txt"", ""r"") as f: reg_a = int(re.search(r""(\d+)"", f.readline())[0]) reg_b = int(re.search(r""(\d+)"", f.readline())[0]) reg_c = int(re.search(r""(\d+)"", f.readline())[0]) f.readline() program = [int(opcode) for opcode in re.findall(r""(\d+)"", f.readline())] print(f'{reg_a=}, {reg_b=}, {reg_c=}, {program=}') while 0 <= ip < len(program): instr_map[program[ip]](program[ip+1]) ip += 2 reg_a: int = 0 reg_b: int = 0 reg_c: int = 0 ip: int = 0 if __name__ == '__main__': main()",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"def run(regs, instructions): n = len(instructions) i = 0 output = [] def get_combo(operand): if 0 <= operand < 4: return operand elif operand == 4: return regs['a'] elif operand == 5: return regs['b'] elif operand == 6: return regs['c'] return 0 while i < n: curr = instructions[i] operand = instructions[i + 1] if curr == 0: regs['a'] //= 2**get_combo(operand) elif curr == 1: regs['b'] ^= operand elif curr == 2: regs['b'] = get_combo(operand) % 8 elif curr == 3: if regs['a']: i = operand continue elif curr == 4: regs['b'] ^= regs['c'] elif curr == 5: output.append(get_combo(operand) % 8) elif curr == 6: regs['b'] = regs['a'] // 2**get_combo(operand) elif curr == 7: regs['c'] = regs['a'] // 2**get_combo(operand) i += 2 return list(output) def get_lowest_a(regs, instructions): regs['a'] = 0 j = 1 iFloor = 0 while j <= len(instructions) and j >= 0: regs['a'] <<= 3 for i in range(iFloor, 8): regsCopy = regs.copy() regsCopy['a'] += i if instructions[-j:] == run(regsCopy, instructions): break else: j -= 1 regs['a'] >>= 3 iFloor = regs['a'] % 8 + 1 regs['a'] >>= 3 continue j += 1 regs['a'] += i iFloor = 0 return regs['a'] if __name__ == ""__main__"": regs = {} instructions = [] # Open file 'day17-2.txt' in read mode with open('day17-2.txt', 'r') as f: for line in f: line = line.strip() if regs.get('a') is None: regs['a'] = 0 elif regs.get('b') is None: regs['b'] = int(line[line.find(':') + 2:]) elif regs.get('c') is None: regs['c'] = int(line[line.find(':') + 2:]) else: instructions = [int(val) for val in line[line.find(':') + 2:].split(',') if len(val) == 1] print(""Lowest value of Register A:"", get_lowest_a(regs, instructions))",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"from part1 import parse_input def run(program, regs): """""" Executes a given program with specified registers. Args: program (list of int): A list of integers representing the program's opcodes and operands. regs (list of int): A list of initial values for the registers. Yields: int: The result of the operation specified by opcode 5, modulo 8. The program supports the following opcodes: 0: Divide the value in reg_a by 2 raised to the power of the value in the register specified by operand. 1: XOR the value in reg_b with the operand. 2: Set reg_b to the value in the register specified by operand, modulo 8. 3: If the value in reg_a is non-zero, set the instruction pointer to operand - 2. 4: XOR the value in reg_b with the value in reg_c. 5: Yield the value in the register specified by operand, modulo 8. 6: Set reg_b to the value in reg_a divided by 2 raised to the power of the value in the register specified by operand. 7: Set reg_c to the value in reg_a divided by 2 raised to the power of the value in the register specified by operand. """""" reg_a, reg_b, reg_c = range(4, 7) ip = 0 combo = [0, 1, 2, 3, *regs] while ip < len(program): opcode, operand = program[ip:ip + 2] if opcode == 0: combo[reg_a] //= 2 ** combo[operand] elif opcode == 1: combo[reg_b] ^= operand elif opcode == 2: combo[reg_b] = combo[operand] % 8 elif opcode == 3: if combo[reg_a]: ip = operand - 2 elif opcode == 4: combo[reg_b] ^= combo[reg_c] elif opcode == 5: yield combo[operand] % 8 elif opcode == 6: combo[reg_b] = combo[reg_a] // (2 ** combo[operand]) elif opcode == 7: combo[reg_c] = combo[reg_a] // (2 ** combo[operand]) ip += 2 def expect(program, target_output, prev_a=0): """""" Tries to find an integer 'a' such that when the 'program' is run with inputs derived from 'a', it produces the 'target_output' sequence. Args: program (iterable): The program to be run, which yields outputs based on inputs. target_output (list): The desired sequence of outputs that the program should produce. prev_a (int, optional): The previous value of 'a' used in the recursive calls. Defaults to 0. Returns: int or None: The integer 'a' that produces the 'target_output' when the program is run, or None if no such 'a' can be found. """""" def helper(program, target_output, prev_a): if not target_output: return prev_a for a in range(1 << 10): if a >> 3 == prev_a & 127 and next(run(program, (a, 0, 0))) == target_output[-1]: result = helper(program, target_output[:-1], (prev_a << 3) | (a % 8)) if result is not None: return result return None return helper(program, target_output, prev_a) if __name__ == ""__main__"": file_path = 'input.txt' registers, program = parse_input(file_path) # Example target output target_output = program.copy() initial_value = expect(program, target_output) if initial_value is not None: print(f""The initial value for register A that produces the target output is: {initial_value}"") else: print(""No initial value found that produces the target output within the given attempts."")",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() program = [int(x) for x in input_text[4].removeprefix(""Program: "").split("","")] a = 0 position = 0 offsets = [0] while position < len(program): if program[-1 - position] == ((a % 8) ^ 5 ^ 6 ^ (a // (2 ** ((a % 8) ^ 5)))) % 8: a *= 8 position += 1 offsets.append(0) elif offsets[-1] < 7: a += 1 offsets[-1] += 1 else: while offsets[-1] >= 7 and position > 0: a //= 8 offsets.pop(-1) position -= 1 a += 1 offsets[-1] += 1 print(a // 8)",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"import re with open(""17.txt"") as i: input = [x.strip() for x in i.readlines()] test_data = """"""Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0"""""".split(""\n"") # input = test_data a, b, c = 0, 0, 0 program = None for l in input: if l.startswith(""Register ""): r, v = re.match(r""Register (A|B|C): (\d+)"", l).groups() if r == ""A"": a = int(v) elif r == ""B"": b = int(v) elif r == ""C"": c = int(v) elif l.startswith(""Program: ""): program = [int(x) for x in l[9:].split("","")] def run_program(program: list[int], aa: int, bb: int, cc: int) -> list[int]: output = [] a, b, c = aa, bb, cc ip = 0 while ip < len(program): i = program[ip] op = program[ip+1] cop = None if op == 4: cop = a elif op == 5: cop = b elif op == 6: cop = c else: cop = op if i == 0: # adv a = a // (2**cop) elif i == 1: # bxl b = b ^ op elif i == 2: #bst b = cop % 8 elif i == 3: # jnz if a != 0: ip = op continue elif i == 4: # bxc b = b ^ c elif i == 5: # out output.append(cop%8) elif i == 6: # bdv b = a // (2**cop) elif i == 7: # cdv c = a // (2**cop) ip += 2 return output current = len(program) solutions = [0] while current>0: next_solutions = [] for aa in solutions: for i in range(8): r = run_program(program, (aa<<3) | i, b, c) if r[0] == program[current-1]: next_solutions.append((aa << 3) | i) current = current - 1 solutions = next_solutions part2 = min(solutions) print(part2)",python 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"# day 17 import os def reader(): return open(f""17.txt"", 'r').read().splitlines() def simulate(program, A): l = [0, 1, 2, 3, A, 0, 0, -1] out = [] i = 0 while i < len(program): op = program[i] operand = program[i + 1] if op == 0: l[4] = int(l[4] / (2 ** l[operand])) elif op == 1: l[5] = l[5] ^ operand elif op == 2: l[5] = l[operand] % 8 elif op == 3: if l[4] != 0: i = operand continue elif op == 4: l[5] = l[5] ^ l[6] elif op == 5: out.append(l[operand] % 8) elif op == 6: l[5] = int(l[4] / (2 ** l[operand])) elif op == 7: l[6] = int(l[4] / (2 ** l[operand])) i += 2 return out def part2(): f = reader() program = list(map(int, f[4][(f[4].find(': ') + 2):].split(','))) def backtrack(A=0, j=-1): if -j > len(program): return A m = float('inf') for i in range(8): t = (A << 3) | i if simulate(program, t)[j:] == program[j:]: m = min(m, backtrack(t, j - 1)) return m print(backtrack()) part2()",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heapify, heappop, heappush with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() grid_size = 70 num_fallen = 1024 bytes = set() for byte in input_text[:num_fallen]: byte_x, byte_y = byte.split("","") bytes.add((int(byte_x), int(byte_y))) movements = ((-1, 0), (1, 0), (0, 1), (0, -1)) explored = set() discovered = [(0, 0, 0)] heapify(discovered) while True: distance, byte_x, byte_y = heappop(discovered) if (byte_x, byte_y) not in explored: explored.add((byte_x, byte_y)) if byte_x == byte_y == grid_size: print(distance) break for movement in movements: new_position = (byte_x + movement[0], byte_y + movement[1]) if ( new_position not in bytes and new_position not in explored and all(0 <= coord <= grid_size for coord in new_position) ): heappush(discovered, (distance + 1, *new_position))",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from collections import deque from typing import List, Tuple def parse_input(file_path: str) -> List[Tuple[int, int]]: """""" Parses the input file and returns a list of tuples containing integer pairs. Args: file_path (str): The path to the input file. Returns: List[Tuple[int, int]]: A list of tuples, where each tuple contains two integers parsed from a line in the input file. Each line in the file should contain two integers separated by a comma. """""" with open(file_path, 'r') as file: return [tuple(map(int, line.strip().split(','))) for line in file] def initialize_grid(size: int) -> List[List[str]]: """""" Initializes a square grid of the given size with all cells set to '.'. Args: size (int): The size of the grid (number of rows and columns). Returns: List[List[str]]: A 2D list representing the initialized grid. """""" return [['.' for _ in range(size)] for _ in range(size)] def simulate_falling_bytes(grid: List[List[str]], byte_positions: List[Tuple[int, int]], num_bytes: int): """""" Simulates the falling of bytes in a grid. Args: grid (List[List[str]]): A 2D list representing the grid where bytes will fall. byte_positions (List[Tuple[int, int]]): A list of tuples representing the (x, y) positions of bytes. num_bytes (int): The number of bytes to simulate falling. Returns: None """""" for x, y in byte_positions[:num_bytes]: grid[y][x] = '#' def find_shortest_path(grid: List[List[str]]) -> int: """""" Finds the shortest path in a grid from the top-left corner to the bottom-right corner. The grid is represented as a list of lists of strings, where '.' represents an open cell and any other character represents an obstacle. Args: grid (List[List[str]]): The grid to search, where each element is a string representing a cell. Returns: int: The number of steps in the shortest path from the top-left to the bottom-right corner. Returns -1 if no such path exists. """""" size = len(grid) directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] queue = deque([(0, 0, 0)]) # (x, y, steps) visited = set([(0, 0)]) while queue: x, y, steps = queue.popleft() if (x, y) == (size - 1, size - 1): return steps for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < size and 0 <= ny < size and grid[ny][nx] == '.' and (nx, ny) not in visited: visited.add((nx, ny)) queue.append((nx, ny, steps + 1)) return -1 # No path found if __name__ == ""__main__"": file_path = 'input.txt' byte_positions = parse_input(file_path) grid_size = 71 # For the actual problem, use 71; for the example, use 7 grid = initialize_grid(grid_size) simulate_falling_bytes(grid, byte_positions, 1024) steps = find_shortest_path(grid) print(f""Minimum number of steps needed to reach the exit: {steps}"")",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heappop, heappush def in_bounds(i, j, n): return 0 <= i < n and 0 <= j < n def navigate(maze, n): start = (0, 0) end = (n - 1, n - 1) heap = [(0, start[0], start[1])] visited = set() while heap: score, i, j = heappop(heap) if (i, j) == end: break if (i, j) in visited: continue visited.add((i, j)) if in_bounds(i, j+1, n) and maze[i][j+1] not in visited and maze[i][j+1] == '.': heappush(heap, (score + 1, i, j+1)) if in_bounds(i+1, j, n) and maze[i+1][j] not in visited and maze[i+1][j] == '.': heappush(heap, (score + 1, i+1, j)) if in_bounds(i, j-1, n) and maze[i][j-1] not in visited and maze[i][j-1] == '.': heappush(heap, (score + 1, i, j-1)) if in_bounds(i-1, j, n) and maze[i-1][j] not in visited and maze[i-1][j] == '.': heappush(heap, (score + 1, i-1, j)) return score def init_maze(bytes, n, numBytes): maze = [['.' for _ in range(n)] for _ in range(n)] for byte in bytes[:numBytes]: maze[byte[1]][byte[0]] = '#' return maze def get_min_steps(bytes): n = 71 numBytes = 1024 maze = init_maze(bytes, n, numBytes) return navigate(maze, n) if __name__ == ""__main__"": # Open file 'day18-1.txt' in read mode with open('day18-1.txt', 'r') as f: bytes = [] for line in f: line = line.strip() x, y = line.split(',') bytes.append((int(x), int(y))) print(""Minimum steps:"", get_min_steps(bytes))",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"def bfs(byte_locs, x_len, y_len): start = (0, 0) end = (x_len - 1, y_len - 1) visited = set() frontier = [[start]] while len(frontier) > 0: path = frontier.pop(0) cur = path[-1] if cur == end: return path visited.add(cur) neighbors = [tuple(map(sum, zip(cur, direction))) for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]] neighbors = [pos for pos in neighbors if pos[0] in range(x_len) and pos[1] in range(y_len) and pos not in byte_locs] for neighbor in neighbors: if neighbor not in visited: frontier.append(path + [neighbor]) visited.add(neighbor) print(""no path found"") return None with open('input.txt') as f: lines = f.read().splitlines() byte_locs = [tuple(map(int, line.split("",""))) for line in lines] x_len = 71 y_len = 71 print(len(bfs(set(byte_locs[0:1024]), x_len, y_len)) - 1)",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heappush, heappop with open(""./day_18.in"") as fin: lines = fin.read().strip().split(""\n"") coords = set([tuple(map(int, line.split("",""))) for line in lines][:1024]) dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] N = 70 # Heuristic for A* def h(i, j): return abs(N - i) + abs(N - j) def in_grid(i, j): return 0 <= i <= N and 0 <= j <= N and (i, j) not in coords q = [(h(0, 0), 0, 0)] cost = {} while len(q) > 0: c, i, j = heappop(q) if (i, j) in cost: continue cost[(i, j)] = c - h(i, j) if (i, j) == (N, N): print(cost[(i, j)]) break for di, dj in dd: ii, jj = i + di, j + dj if in_grid(ii, jj): heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj))",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from heapq import heapify, heappop, heappush with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() grid_size = 70 bytes_list = [] for byte in input_text: byte_x, byte_y = byte.split("","") bytes_list.append((int(byte_x), int(byte_y))) movements = ((-1, 0), (1, 0), (0, 1), (0, -1)) bytes_needed_lower = 0 bytes_needed_upper = len(bytes_list) - 1 while bytes_needed_lower < bytes_needed_upper: mid = (bytes_needed_lower + bytes_needed_upper) // 2 bytes = set(bytes_list[:mid]) explored = set() discovered = [(0, 0, 0)] heapify(discovered) while discovered: distance, byte_x, byte_y = heappop(discovered) if (byte_x, byte_y) not in explored: explored.add((byte_x, byte_y)) if byte_x == byte_y == grid_size: break for movement in movements: new_position = (byte_x + movement[0], byte_y + movement[1]) if ( new_position not in bytes and new_position not in explored and all(0 <= coord <= grid_size for coord in new_position) ): heappush(discovered, (distance + 1, *new_position)) else: bytes_needed_upper = mid continue bytes_needed_lower = mid + 1 print("","".join([str(x) for x in bytes_list[bytes_needed_lower - 1]]))",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","def bfs(byte_locs, x_len, y_len): start = (0, 0) end = (x_len - 1, y_len - 1) visited = set() frontier = [[start]] while len(frontier) > 0: path = frontier.pop(0) cur = path[-1] if cur == end: return path visited.add(cur) neighbors = [tuple(map(sum, zip(cur, direction))) for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]] neighbors = [pos for pos in neighbors if pos[0] in range(x_len) and pos[1] in range(y_len) and pos not in byte_locs] for neighbor in neighbors: if neighbor not in visited: frontier.append(path + [neighbor]) visited.add(neighbor) return None with open('input.txt') as f: lines = f.read().splitlines() byte_locs = [tuple(map(int, line.split("",""))) for line in lines] x_len = 71 y_len = 71 lower = 0 upper = len(byte_locs) - 1 while lower <= upper: mid = (lower + upper) // 2 test = bfs(set(byte_locs[0:mid]), x_len, y_len) if test is None: upper = mid - 1 print(""not reachable at"", byte_locs[mid-1]) else: print(""reachable at"", byte_locs[mid-1]) lower = mid + 1 print(byte_locs[mid])",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from heapq import heappush, heappop with open(""./day_18.in"") as fin: lines = fin.read().strip().split(""\n"") coords = [tuple(map(int, line.split("",""))) for line in lines] dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] N = 70 # Heuristic for A* def h(i, j): return abs(N - i) + abs(N - j) def doable(idx): # Can we get to the index with first `idx` coords blocked? def in_grid(i, j): return 0 <= i <= N and 0 <= j <= N and (i, j) not in coords[:idx] q = [(h(0, 0), 0, 0)] cost = {} while len(q) > 0: c, i, j = heappop(q) if (i, j) in cost: continue cost[(i, j)] = c - h(i, j) if (i, j) == (N, N): return True for di, dj in dd: ii, jj = i + di, j + dj if in_grid(ii, jj): heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj)) return False # Binary search for first coord that is not doable lo = 0 hi = len(coords) - 1 while hi > lo: mid = (lo + hi) // 2 if doable(mid): lo = mid + 1 else: hi = mid print("","".join(map(str, coords[lo-1])))",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from collections import deque l = open(""18.txt"").read().splitlines() l = [list(map(int, x.split("",""))) for x in l] max_x = max(coord[0] for coord in l) max_y = max(coord[1] for coord in l) def P2(): for find in range(1024,len(l)): grid = [[""."" for _ in range(max_y + 1)] for _ in range(max_x + 1)] for i in range(find): x,y = l[i] grid[x][y] = ""#"" def bfs(grid, start, end): rows, cols = len(grid), len(grid[0]) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] queue = deque([(start, 0)]) visited = set() while queue: (x, y), dist = queue.popleft() if (x, y) == end: return dist if (x, y) in visited or grid[x][y] == ""#"": continue visited.add((x, y)) for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < rows and 0 <= ny < cols and (nx, ny) not in visited: queue.append(((nx, ny), dist + 1)) return -1 if bfs(grid, (0,0), (max_x, max_y)) == -1: return l[find-1] print(P2())",python 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! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","#!/usr/bin/env python3 import re from collections import defaultdict, deque myfile = open(""18.in"", ""r"") lines = myfile.read().strip().splitlines() myfile.close() blocks = [tuple(map(int, re.findall(r""\d+"", line))) for line in lines] part_one = 0 part_two = 0 height = width = 70 def search(block_count): grid = defaultdict(str) for x in range(width + 1): for y in range(height + 1): grid[(x, y)] = ""."" grid[(width, height)] = ""$"" for x, y in blocks[: block_count + 1]: grid[(x, y)] = """" visited = set() scores = defaultdict(lambda: float(""inf"")) scores[(0, 0)] = 0 q = deque([(0, 0)]) while q: pos = q.popleft() visited.add(pos) if grid[pos] == ""$"": return scores[pos] next_score = scores[pos] + 1 for dir in [(1, 0), (0, -1), (-1, 0), (0, 1)]: next_pos = (pos[0] + dir[0], pos[1] + dir[1]) if next_pos not in visited and next_score < scores[next_pos]: if grid[next_pos] != """": scores[next_pos] = next_score q.append(next_pos) return -1 unblocked, blocked = 1024, len(blocks) while blocked - unblocked > 1: mid = (unblocked + blocked) // 2 result = search(mid) if result == -1: blocked = mid else: unblocked = mid part_two = "","".join(map(str, blocks[blocked])) print(""Part Two:"", part_two)",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from pprint import pprint WHITE = ""w"" BLUE = ""u"" BLACK = ""b"" RED = ""r"" GREEN = ""g"" INPUT_FILE = ""test.txt"" read_file = open(INPUT_FILE, ""r"") lines = read_file.readlines() available_towels = lines[0].strip().split("", "") designs = [] for line in lines[2:]: designs.append(line.strip()) def find_first_pattern(design, start_index=0): for i in range(len(design), 0, -1): if design[start_index:i] in available_towels: return (i, design[start_index:i]) return (None, None) def find_last_pattern(design, end_index): for i in range(len(design)): if design[i:end_index] in available_towels: return (i, design[i:end_index]) return (None, None) def find_largest_from_start(design, start=0): largest_pattern_match = None end = 0 for i in range(1 + start, len(design)): sub_string = design[start:i] print(sub_string) if sub_string in available_towels: largest_pattern_match = sub_string end = i return (largest_pattern_match, end) results = [] impossible_designs = [] def can_build_word(target, patterns): def can_build(remaining, memo=None): if memo is None: memo = {} # Base cases if not remaining: # Successfully used all letters return True if remaining in memo: # Already tried this combo return memo[remaining] # Try each pattern at the start of our remaining string # We can reuse patterns, so no need to track what we've used for pattern in patterns: if remaining.startswith(pattern): new_remaining = remaining[len(pattern) :] if can_build(new_remaining, memo): memo[remaining] = True print(memo) return True memo[remaining] = False return False return can_build(target) can_build_count = 0 for design in designs: if can_build_word(design, available_towels): can_build_count += 1 print(can_build_count) quit() for design in designs: patterns = {} result = 0 pattern_found = False while True: (result, pattern) = find_first_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if not result: pattern_found = False break if design[:result] == design: pattern_found = True break if pattern_found: results.append((design, patterns)) else: patterns = {} result = len(design) pattern_found = False while True: (result, pattern) = find_last_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if result == None: pattern_found = False break if result == 0: pattern_found = True break if pattern_found: results.append((design, patterns)) else: impossible_designs.append(design)",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from functools import cache with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() towels_trie = {} for towel in input_text[0].split("", ""): inner_dict = towels_trie for letter in list(towel): if letter not in inner_dict: inner_dict[letter] = {} inner_dict = inner_dict[letter] inner_dict[None] = None @cache def pattern_possible(pattern): if not pattern: return True patterns_needed = [] trie = towels_trie for i, letter in enumerate(pattern): if letter in trie: trie = trie[letter] if None in trie: patterns_needed.append(pattern[i + 1 :]) else: break return any(pattern_possible(sub_pattern) for sub_pattern in patterns_needed) print(sum(pattern_possible(pattern) for pattern in input_text[2:]))",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"def is_pattern_possible(pattern, towels, visited): if pattern == """": return True visited.add(pattern) return any([pattern.startswith(t) and pattern[len(t):] not in visited and is_pattern_possible(pattern[len(t):], towels, visited) for t in towels]) with open('input.txt') as f: lines = f.read().splitlines() towels = [s.strip() for s in lines[0].split("","")] patterns = lines[2:] print(sum([is_pattern_possible(p, towels, set()) for p in patterns]))",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from pprint import pprint WHITE = ""w"" BLUE = ""u"" BLACK = ""b"" RED = ""r"" GREEN = ""g"" INPUT_FILE = ""test.txt"" read_file = open(INPUT_FILE, ""r"") lines = read_file.readlines() available_towels = lines[0].strip().split("", "") designs = [] for line in lines[2:]: designs.append(line.strip()) def find_first_pattern(design, start_index=0): for i in range(len(design), 0, -1): if design[start_index:i] in available_towels: return (i, design[start_index:i]) return (None, None) def find_last_pattern(design, end_index): for i in range(len(design)): if design[i:end_index] in available_towels: return (i, design[i:end_index]) return (None, None) def find_largest_from_start(design, start=0): largest_pattern_match = None end = 0 for i in range(1 + start, len(design)): sub_string = design[start:i] print(sub_string) if sub_string in available_towels: largest_pattern_match = sub_string end = i return (largest_pattern_match, end) results = [] impossible_designs = [] def can_build_pattern(target, patterns): def can_build(remaining, memo=None): if memo is None: memo = {} # Base cases if not remaining: # Successfully used all letters return True if remaining in memo: # Already tried this combo return memo[remaining] # Try each pattern at the start of our remaining string # We can reuse patterns, so no need to track what we've used for pattern in patterns: if remaining.startswith(pattern): new_remaining = remaining[len(pattern) :] if can_build(new_remaining, memo): memo[remaining] = True print(memo) return True memo[remaining] = False return False return can_build(target) can_build_count = 0 for design in designs: if can_build_pattern(design, available_towels): can_build_count += 1 print(can_build_count) quit() for design in designs: patterns = {} result = 0 pattern_found = False while True: (result, pattern) = find_first_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if not result: pattern_found = False break if design[:result] == design: pattern_found = True break if pattern_found: results.append((design, patterns)) else: patterns = {} result = len(design) pattern_found = False while True: (result, pattern) = find_last_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if result == None: pattern_found = False break if result == 0: pattern_found = True break if pattern_found: results.append((design, patterns)) else: impossible_designs.append(design)",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"with open(""./day_19.in"") as fin: lines = fin.read().strip().split(""\n"") units = lines[0].split("", "") designs = lines[2:] def possible(design): n = len(design) dp = [False] * len(design) for i in range(n): if design[:i+1] in units: dp[i] = True continue for u in units: if design[i-len(u)+1:i+1] == u and dp[i - len(u)]: # print("" "", i, u, design[-len(u):], dp[i - len(u)]) dp[i] = True break # print(design, dp) return dp[-1] ans = 0 for d in designs: if possible(d): print(d) ans += 1 print(ans)",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"def check_count(towels, pattern, cache): if pattern == """": return 1 if (block := cache.get(pattern, None)) is not None: return block result = 0 for towel in towels: if towel == pattern[:len(towel)]: result += check_count(towels, pattern[len(towel):], cache) cache[pattern] = result return result def get_num_achievable_patterns(towels, patterns): return sum([check_count(towels, pattern, {}) for pattern in patterns]) if __name__ == ""__main__"": towels = [] patterns = [] # Open file 'day19-2.txt' in read mode with open('day19-2.txt', 'r') as f: vals = [] for line in f: line = line.strip() if len(line) == 0: continue if len(towels) == 0: towels = line.split(', ') else: patterns.append(line) print(""Number of ways to acheive patterns:"", get_num_achievable_patterns(towels, patterns))",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"def num_possible_patterns(pattern, towels, memo): if pattern == """": return 1 if pattern in memo: return memo[pattern] res = sum([num_possible_patterns(pattern[len(t):], towels, memo) if pattern.startswith(t) else 0 for t in towels]) memo[pattern] = res return res with open('input.txt') as f: lines = f.read().splitlines() towels = [s.strip() for s in lines[0].split("","")] patterns = lines[2:] print(sum([num_possible_patterns(p, towels, dict()) for p in patterns]))",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from functools import cache with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() towels_trie = {} for towel in input_text[0].split("", ""): inner_dict = towels_trie for letter in list(towel): if letter not in inner_dict: inner_dict[letter] = {} inner_dict = inner_dict[letter] inner_dict[None] = None @cache def pattern_possible(pattern): if not pattern: return 1 patterns_needed = [] trie = towels_trie for i, letter in enumerate(pattern): if letter in trie: trie = trie[letter] if None in trie: patterns_needed.append(pattern[i + 1 :]) else: break return sum(pattern_possible(sub_pattern) for sub_pattern in patterns_needed) print(sum(pattern_possible(pattern) for pattern in input_text[2:]))",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from typing import List, Tuple from collections import defaultdict from part1 import parse_input def count_ways_to_construct_design(design: str, towel_patterns: List[str]) -> int: """""" Counts the number of ways to construct a given design using a list of towel patterns. Args: design (str): The design string that needs to be constructed. towel_patterns (List[str]): A list of towel patterns that can be used to construct the design. Returns: int: The number of ways to construct the design using the given towel patterns. """""" n = len(design) dp = defaultdict(int) dp[0] = 1 # Base case: there's one way to construct an empty design for i in range(1, n + 1): for pattern in towel_patterns: if i >= len(pattern) and design[i - len(pattern):i] == pattern: dp[i] += dp[i - len(pattern)] return dp[n] def total_ways_to_construct_designs(towel_patterns: List[str], desired_designs: List[str]) -> int: """""" Calculate the total number of ways to construct each design in the desired designs list using the given towel patterns. Args: towel_patterns (List[str]): A list of available towel patterns. desired_designs (List[str]): A list of desired designs to be constructed. Returns: int: The total number of ways to construct all the desired designs using the towel patterns. """""" return sum(count_ways_to_construct_design(design, towel_patterns) for design in desired_designs) if __name__ == ""__main__"": file_path = 'input.txt' towel_patterns, desired_designs = parse_input(file_path) result = total_ways_to_construct_designs(towel_patterns, desired_designs) print(result)",python 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. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from collections import defaultdict def nb_possible_arrangements(design: str, towels: list[str]) -> int: cache: defaultdict[str, int] = defaultdict(lambda: 0) cache[""""] = 1 for i in range(1, len(design) + 1): design_i = design[-i:] cache[design_i] = 0 for towel in towels: if design_i.startswith(towel): sub_design = design_i[len(towel) :] cache[design_i] += cache[sub_design] return cache[design] def main() -> None: towels: list[str] = [] designs: list[str] = [] with open(""input.txt"") as data: towels = data.readline().strip().split("", "") assert data.readline() == ""\n"" for line in data: designs.append(line.strip()) count = 0 for i, design in enumerate(designs): nb = nb_possible_arrangements(design, towels) count += nb print(count) if __name__ == ""__main__"": main()",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from itertools import permutations keypadSequences = open('input.txt').read().splitlines() keypad = { '7': (0, 0), '8': (0, 1), '9': (0, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '1': (2, 0), '2': (2, 1), '3': (2, 2), '#': (3, 0), '0': (3, 1), 'A': (3, 2) } keypadBadPosition = (3,0) startKeypad = (3, 2) directionalpad = { '#': (0, 0), '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2) } directionalpadBadPosition = (0,0) startdirectionalpad = (0, 2) def getNumericPart(code): return ''.join([elem for elem in code if elem.isdigit()]) def getdirections(drow, dcol): res = [] if drow > 0: res.append('v'*drow) elif drow < 0: res.append('^'*abs(drow)) if dcol > 0: res.append('>'*dcol) elif dcol < 0: res.append('<'*abs(dcol)) return ''.join(res) def getPossiblePermutations(pos, directions, position): perms = set(permutations(directions)) validPerms = [] for perm in perms: if validatepath(pos, perm, position): validPerms.append(''.join(perm)) return validPerms def validatepath(pos, directions, position): _pos = pos for direction in directions: if direction == 'v': _pos = (_pos[0] + 1, _pos[1]) elif direction == '^': _pos = (_pos[0] - 1, _pos[1]) elif direction == '>': _pos = (_pos[0], _pos[1] + 1) elif direction == '<': _pos = (_pos[0], _pos[1] - 1) if _pos == position: return False return True def getDirectionToWriteCode(input): pos = startKeypad result = [] for elem in input: nextPos = keypad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, keypadBadPosition) if len(result) == 0: for path in validPaths: result.append(path + 'A') elif len(result) >= 1: temp = [] for res in result: for path in validPaths: temp.append(res + path + 'A') result = temp pos = nextPos return result def getDirectionToWriteDirection(input): pos = startdirectionalpad result = [] for elem in input: nextPos = directionalpad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition) if len(result) == 0: for path in validPaths: result.append(path + 'A') elif len(result) >= 1: temp = [] for res in result: for path in validPaths: temp.append(res + path + 'A') result = temp pos = nextPos min_length = min(len(r) for r in result) return [r for r in result if len(r) == min_length] def getDirectionToWriteDirectionSample(input): pos = startdirectionalpad result = [] for elem in input: nextPos = directionalpad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition)[0] result.append(validPaths) result.append('A') pos = nextPos return ''.join(result) def calculateComplexity(code): sol1 = getDirectionToWriteCode(code) sol2 = [elem for sol in sol1 for elem in getDirectionToWriteDirection(sol)] sol3 = [getDirectionToWriteDirectionSample(elem) for elem in sol2] print(sol3[0]) print(sol2[0]) print(sol1[0]) print(code) min_length = min(len(r) for r in sol3) num = getNumericPart(code) print(f""Code: Numeric: {num}, minimum length: {min_length}"") return min_length * int(num) total = 0 for code in keypadSequences: score = calculateComplexity(code) total += score print() print(total) # >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A # <A>^AvAA<^A>A<>^AvA^A^A<^A>AAvA^A<A>^AAAvA<^A>A # code = '029A' # sol1 = getDirectionToWriteCode(code) # sol2 = getDirectionToWriteDirection(sol1) # sol3 = getDirectionToWriteDirection(sol2) # print(sol3) # print(sol2) # print(sol1) # print(code) # print(calculateComplexity(""029A""))",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"NUMS = { '0': (3, 1), '1': (2, 0), '2': (2, 1), '3': (2, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '7': (0, 0), '8': (0, 1), '9': (0, 2), 'A': (3, 2), '': (3, 0) } ARROWS = { '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2), '': (0, 0) } DIR_TO_ARROW_MAP = { (-1, 0): '^', (1, 0): 'v', (0, -1): '<', (0, 1): '>' } def get_shortest(keys, sequence): path = [] for i in range(len(sequence) - 1): cur, target = keys[sequence[i]], keys[sequence[i + 1]] next_path = [] dirs = [] for y in range(cur[1] - 1, target[1] - 1, -1): next_path.append((cur[0], y)) dirs.append((0, -1)) for x in range(cur[0] + 1, target[0] + 1): next_path.append((x, cur[1])) dirs.append((1, 0)) for x in range(cur[0] - 1, target[0] - 1, -1): next_path.append((x, cur[1])) dirs.append((-1, 0)) for y in range(cur[1] + 1, target[1] + 1): next_path.append((cur[0], y)) dirs.append((0, 1)) if keys[''] in next_path: dirs = list(reversed(dirs)) path += [DIR_TO_ARROW_MAP[d] for d in dirs] + ['A'] return """".join(path) with open('input.txt') as f: lines = f.read().splitlines() total_complexity = 0 for line in lines: l1 = get_shortest(NUMS, 'A' + line) l2 = get_shortest(ARROWS, 'A' + l1) l3 = get_shortest(ARROWS, 'A' + l2) total_complexity += int(line[0:-1]) * len(l3) print(total_complexity)",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from abc import ABC import argparse from functools import cache from itertools import product from typing import Optional g_verbose = False CHR_A = ord('A') UP = ord('^') DOWN = ord('v') LEFT = ord('<') RIGHT = ord('>') CHR_0 = ord('0') CHR_1 = ord('1') CHR_2 = ord('2') CHR_3 = ord('3') CHR_4 = ord('4') CHR_5 = ord('5') CHR_6 = ord('6') CHR_7 = ord('7') CHR_8 = ord('8') CHR_9 = ord('9') def get_dir_h(dx: int) -> int: return LEFT if dx < 0 else RIGHT def get_dir_v(dy: int) -> int: return UP if dy < 0 else DOWN class RobotPad(ABC): id: int = 0 dir_cache: dict[tuple[int, int], list[list[int]]] pos_cache: dict[tuple[int, int], int] child: Optional['RobotPad'] = None @cache def cost_press_once(self, snapshot: tuple[int, ...]): my_id = self.id if not self.child: assert len(snapshot) == 1 return 1, snapshot g_verbose and print(f'{"" "" * my_id}bot #{my_id} request parent press') cost_moving, new_snapshot = self.child.cost_moving(CHR_A, snapshot[1:]) cost_press, new_snapshot = self.child.cost_press_once(new_snapshot) return cost_moving + cost_press, (snapshot[0], *new_snapshot) @cache def cost_moving(self, target_button: int, snapshot: tuple[int, ...]): my_id = self.id current_button = snapshot[0] g_verbose and print(f'{"" "" * my_id}bot #{my_id} plan {chr(current_button)} -> {chr(target_button)}') if current_button == target_button: g_verbose and print(f'{"" "" * my_id}bot #{my_id} not moving, already at {chr(target_button)}') return 0, snapshot # Last layer distance = self.pos_cache[current_button, target_button] if not self.child: g_verbose and print(f'{"" "" * my_id}bot #{my_id} move to {chr(target_button)}, cost={distance}') assert len(snapshot) == 1 return distance, (target_button,) # Move parent node to the direction I want tracking = [] for possible_routes in self.dir_cache[current_button, target_button]: route_cost = 0 route_snapshot = snapshot[1:] for next_direction in possible_routes: cost_moving, route_snapshot = self.child.cost_moving(next_direction, route_snapshot) cost_press, route_snapshot = self.child.cost_press_once(route_snapshot) route_cost += cost_moving + cost_press tracking.append((route_cost, (target_button, *route_snapshot))) best_cost, best_snapshot = min(tracking, key=lambda x: x[0]) g_verbose and print(f'{"" "" * my_id}bot #{my_id} move to {chr(target_button)}, cost={best_cost}') return best_cost, best_snapshot def move(self, dst: int, snapshot: tuple[int, ...]): return self.cost_moving(dst, snapshot) class NumPad(RobotPad): def __init__(self, bot_id: int): self.id = bot_id self.board = [ [0x37, 0x38, 0x39], [0x34, 0x35, 0x36], [0x31, 0x32, 0x33], [0x00, 0x30, 0x41] ] self.pos_cache = {} self.board_lookup = {value: (x, y) for y, row in enumerate(self.board) for x, value in enumerate(row) if value} dir_cache: dict[tuple[int, int], list[list[int]]] = {} for ((a, (x1, y1)), (b, (x2, y2))) in product(self.board_lookup.items(), repeat=2): if a == b: continue # Find the direction of move from a to b dx = x2 - x1 dy = y2 - y1 x_count = abs(dx) y_count = abs(dy) # Only move in one direction if dx == 0 or dy == 0: dir_cache[a, b] = [[get_dir_h(dx) if dx else get_dir_v(dy)] * (x_count + y_count)] elif a in (CHR_0, CHR_A) and b in (CHR_1, CHR_4, CHR_7): # Can only move up and then left dir_cache[a, b] = [[UP] * y_count + [LEFT] * x_count] elif a in (CHR_1, CHR_4, CHR_7) and b in (CHR_0, CHR_A): # Can only move right and then down dir_cache[a, b] = [[RIGHT] * x_count + [DOWN] * y_count] else: # Can move both horizontally and vertically, any order dir_h = get_dir_h(dx) dir_v = get_dir_v(dy) dir_cache[a, b] = [[dir_h] * x_count + [dir_v] * y_count, [dir_v] * y_count + [dir_h] * x_count] self.pos_cache[a, b] = abs(dx) + abs(dy) self.dir_cache = dir_cache class DirectionPad(RobotPad): def __init__(self, bot_id: int): self.id = bot_id self.board = [ [0x00, UP, CHR_A], [LEFT, DOWN, RIGHT], ] self.board_lookup = {value: (x, y) for y, row in enumerate(self.board) for x, value in enumerate(row) if value} self.pos_cache = {} dir_cache: dict[tuple[int, int], list[list[int]]] = {} for ((a, (x1, y1)), (b, (x2, y2))) in product(self.board_lookup.items(), repeat=2): # Find the direction of move from a to b dx = x2 - x1 dy = y2 - y1 self.pos_cache[a, b] = abs(dx) + abs(dy) x_count = abs(dx) y_count = abs(dy) # Only move in one direction if dx == 0 or dy == 0: dir_cache[a, b] = [[get_dir_h(dx) if dx else get_dir_v(dy)] * (x_count + y_count)] elif a == LEFT and b in (UP, CHR_A): # Can only move right and then UP dir_cache[a, b] = [[RIGHT] * x_count + [UP] * y_count] elif a in (UP, CHR_A) and b == LEFT: # Can only move down and then left dir_cache[a, b] = [[DOWN] * y_count + [LEFT] * x_count] else: # Can move both horizontally and vertically, any order dir_h = get_dir_h(dx) dir_v = get_dir_v(dy) dir_cache[a, b] = [[dir_h] * x_count + [dir_v] * y_count, [dir_v] * y_count + [dir_h] * x_count] self.dir_cache = dir_cache def solve_ex(codes: list[str], count: int) -> int: root = NumPad(0) node = root for i in range(count): bot = DirectionPad(i + 1) node.child = bot node = bot snapshot_init = tuple([CHR_A] * (count + 1)) result = 0 for code in codes: snapshot = snapshot_init total_cost = 0 for current_chr in map(ord, code): prev_char = snapshot[0] cost, snapshot = root.cost_moving(current_chr, snapshot) cost_press, snapshot = root.cost_press_once(snapshot) g_verbose and print( f""** move {chr(prev_char)} -> {chr(current_chr)} cost={cost + cost_press} pos={''.join(map(chr, snapshot))}"") total_cost += cost + cost_press numeric_part = int(code[:-1]) print(f""{code} -> {total_cost} * {numeric_part}"") result += total_cost * numeric_part return result def solve(input_path: str, /, **_kwargs): with open(input_path, ""r"", encoding='utf-8') as file: input_text = file.read().strip().replace('\r', '').splitlines() p1 = solve_ex(input_text, 2) print(f'p1: {p1}') def main(): global g_verbose parser = argparse.ArgumentParser() parser.add_argument(""input"", nargs=""?"", default=""sample.txt"") parser.add_argument(""-v"", ""--verbose"", action=""store_true"") parser.add_argument(""--threshold"", type=int, default=50, help=""Threshold (p2)"") args = parser.parse_args() g_verbose = args.verbose solve(args.input) if __name__ == ""__main__"": main()",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"import functools from typing import List, Tuple, Optional # Define the number pad and the direction pad number_pad = [ ""789"", ""456"", ""123"", "" 0A"" ] direction_pad = [ "" ^A"", """" ] def parse_input(file_path: str) -> List[Tuple[str, int]]: """""" Parses the input file and returns a list of tuples. Each tuple contains a string (the stripped line) and an integer (the first three characters of the line). Args: file_path (str): The path to the input file. Returns: List[Tuple[str, int]]: A list of tuples where each tuple contains a string and an integer. """""" with open(file_path) as file: return [(line.strip(), int(line[:3])) for line in file] def find_position(pad: List[str], char: str) -> Optional[Tuple[int, int]]: """""" Find the position of a character in a 2D list (pad). Args: pad (List[str]): A 2D list representing the pad where each element is a string. char (str): The character to find in the pad. Returns: Optional[Tuple[int, int]]: A tuple containing the x and y coordinates of the character if found, otherwise None. """""" for y, row in enumerate(pad): for x, cell in enumerate(row): if cell == char: return x, y return None def generate_path(pad: List[str], from_char: str, to_char: str) -> str: """""" Generate the shortest path from `from_char` to `to_char` in the given pad. The path is represented as a string of direction changes: - '<' for left - '>' for right - '^' for up - 'v' for down - 'A' for arrival at the target position Args: pad (List[str]): A 2D list representing the pad where each element is a character. from_char (str): The character representing the starting position. to_char (str): The character representing the target position. Returns: str: The shortest path from `from_char` to `to_char` based on the number of direction changes. """""" from_x, from_y = find_position(pad, from_char) to_x, to_y = find_position(pad, to_char) def move(x: int, y: int, path: str): # If the current position is the target position, yield the path with 'A' appended if (x, y) == (to_x, to_y): yield path + 'A' # Move left if possible and the target is to the left if to_x < x and pad[y][x - 1] != ' ': yield from move(x - 1, y, path + '<') # Move up if possible and the target is above if to_y < y and pad[y - 1][x] != ' ': yield from move(x, y - 1, path + '^') # Move down if possible and the target is below if to_y > y and pad[y + 1][x] != ' ': yield from move(x, y + 1, path + 'v') # Move right if possible and the target is to the right if to_x > x and pad[y][x + 1] != ' ': yield from move(x + 1, y, path + '>') # Return the shortest path based on the number of direction changes return min(move(from_x, from_y, """"), key=lambda p: sum(a != b for a, b in zip(p, p[1:]))) @functools.lru_cache(None) def solve(sequence: str, level: int, max_level: int = 2) -> int: """""" Solve the problem recursively. Args: sequence (str): The input sequence to process. level (int): The current recursion level. max_level (int, optional): The maximum recursion depth. Defaults to 2. Returns: int: The result of the recursive computation. """""" if level > max_level: return len(sequence) pad = direction_pad if level else number_pad return sum(solve(generate_path(pad, from_char, to_char), level + 1, max_level) for from_char, to_char in zip('A' + sequence, sequence)) if __name__ == ""__main__"": input_data = parse_input('input.txt') result = sum(solve(sequence, 0) * multiplier for sequence, multiplier in input_data) print(result)",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from functools import cache with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() @cache def num_keypad_paths(start, end): output = [] x_diff = abs(end[0] - start[0]) y_diff = abs(end[1] - start[1]) horiz_char = "">"" if end[0] > start[0] else ""<"" vert_char = ""v"" if end[1] > start[1] else ""^"" for path in { tuple([horiz_char] * x_diff + [vert_char] * y_diff), tuple([vert_char] * y_diff + [horiz_char] * x_diff), }: if not ( (start == (0, 0) and path[:3] == (""v"", ""v"", ""v"")) or (start == (0, 1) and path[:2] == (""v"", ""v"")) or (start == (0, 2) and path[:1] == (""v"",)) or (start == (1, 3) and path[:1] == (""<"",)) or (start == (2, 3) and path[:2] == (""<"", ""<"")) ): output.append(list(path) + [""A""]) return output @cache def dir_keypad_paths(start, end): output = [] x_diff = abs(end[0] - start[0]) y_diff = abs(end[1] - start[1]) horiz_char = "">"" if end[0] > start[0] else ""<"" vert_char = ""v"" if end[1] > start[1] else ""^"" for path in { tuple([horiz_char] * x_diff + [vert_char] * y_diff), tuple([vert_char] * y_diff + [horiz_char] * x_diff), }: if not ( (start == (1, 0) and path[:1] == (""<"",)) or (start == (2, 0) and path[:2] == (""<"", ""<"")) or (start == (0, 1) and path[:1] == (""^"",)) ): output.append(list(path) + [""A""]) return output num_keypad = { ""7"": (0, 0), ""8"": (1, 0), ""9"": (2, 0), ""4"": (0, 1), ""5"": (1, 1), ""6"": (2, 1), ""1"": (0, 2), ""2"": (1, 2), ""3"": (2, 2), ""0"": (1, 3), ""A"": (2, 3), } directional_keypad = {""^"": (1, 0), ""A"": (2, 0), ""<"": (0, 1), ""v"": (1, 1), "">"": (2, 1)} total = 0 for code in input_text: current_pos = (2, 3) solutions = [[]] for character in code: new_pos = num_keypad[character] solutions = [ solution + path for solution in solutions for path in num_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_2_outer = [] for solution in solutions: current_pos = (2, 0) solutions_2 = [[]] for character in solution: new_pos = directional_keypad[character] solutions_2 = [ partial_solution + path for partial_solution in solutions_2 for path in dir_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_2_outer += solutions_2 solutions_3_outer = [] for solution in solutions_2_outer: current_pos = (2, 0) solutions_3 = [[]] for character in solution: new_pos = directional_keypad[character] solutions_3 = [ partial_solution + path for partial_solution in solutions_3 for path in dir_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_3_outer += solutions_3 total += min(len(x) for x in solutions_3_outer) * int(code[:3]) print(total)",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"import sys from collections import Counter from functools import cache def test_input(): _input = """"""029A 980A 179A 456A 379A"""""".strip().split('\n') assert part_1(_input) == 126384 class Pad: LOOKUPS = {} def inputs(self, sequence: str): inputs = [] def _inputs(result, current, sequence): if len(sequence) == 0: inputs.append(result) return for move in self._inputs(current, sequence[0]): _inputs(result + move, sequence[0], sequence[1:]) _inputs('', 'A', sequence) return inputs def _inputs(self, start: str, end: str): sx, sy = self.LOOKUPS[start] ex, ey = self.LOOKUPS[end] dx, dy = ex - sx, ey - sy x_str = '<' * -dx if dx < 0 else '>' * dx y_str = '^' * -dy if dy < 0 else 'v' * dy value = [] if dy != 0 and (sx, sy + dy) != self.LOOKUPS[' ']: value.append(f'{y_str}{x_str}A') if dx != 0 and (sx + dx, sy) != self.LOOKUPS[' ']: value.append(f'{x_str}{y_str}A') if dx == dy == 0: value.append('A') return value class Numpad(Pad): """""" A class representing a numpad with a specific layout. The numpad layout is as follows: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Attributes: LOOKUPS (dict): A dictionary containing lookup values for the numpad. """""" LOOKUPS = { '7': (0, 0), '8': (1, 0), '9': (2, 0), '4': (0, 1), '5': (1, 1), '6': (2, 1), '1': (0, 2), '2': (1, 2), '3': (2, 2), ' ': (0, 3), '0': (1, 3), 'A': (2, 3), } class Dirpad(Pad): """""" A class representing a direction pad with a specific layout. The direction pad layout is as follows: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ Attributes: LOOKUPS (dict): A dictionary containing lookup values for the direction pad. """""" LOOKUPS = { ' ': (0, 0), '^': (1, 0), 'A': (2, 0), '<': (0, 1), 'v': (1, 1), '>': (2, 1), } def read_input(path: str) -> list[str]: with open(path) as input_file: return [line.strip() for line in input_file] @cache def shortest(sequence: str, depth: int): dirpad = Dirpad() if depth == 0: return len(sequence) total = 0 for sub in sequence.split('A')[:-1]: sequences = dirpad.inputs(sub + 'A') total += min(shortest(seq, depth - 1) for seq in sequences) return total def score_at_depth(input_data: list[str], depth: int) -> int: total = 0 numpad = Numpad() for code in input_data: numcode = numpad.inputs(code) min_len = min(shortest(nc, depth) for nc in numcode) total += min_len * int(code[:-1]) return total def part_1(input_data: list[str]) -> int: return score_at_depth(input_data, 2) def part_2(input_data: list[str]) -> int: return score_at_depth(input_data, 25) def main(): input_data = read_input(sys.argv[1]) print(f'Part 1: {part_1(input_data)}') print(f'Part 2: {part_2(input_data)}') if __name__ == '__main__': 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"from collections import defaultdict, Counter NUMS = { '0': (3, 1), '1': (2, 0), '2': (2, 1), '3': (2, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '7': (0, 0), '8': (0, 1), '9': (0, 2), 'A': (3, 2), '': (3, 0) } ARROWS = { '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2), '': (0, 0) } DIR_TO_ARROW_MAP = { (-1, 0): '^', (1, 0): 'v', (0, -1): '<', (0, 1): '>' } memo = dict() def get_shortest(keys, sequence): path = [] for i in range(len(sequence) - 1): cur, target = keys[sequence[i]], keys[sequence[i + 1]] next_path = [] dirs = [] for y in range(cur[1] - 1, target[1] - 1, -1): next_path.append((cur[0], y)) dirs.append((0, -1)) for x in range(cur[0] + 1, target[0] + 1): next_path.append((x, cur[1])) dirs.append((1, 0)) for x in range(cur[0] - 1, target[0] - 1, -1): next_path.append((x, cur[1])) dirs.append((-1, 0)) for y in range(cur[1] + 1, target[1] + 1): next_path.append((cur[0], y)) dirs.append((0, 1)) if keys[''] in next_path: dirs = list(reversed(dirs)) to_append = [DIR_TO_ARROW_MAP[d] for d in dirs] + ['A'] path += to_append return """".join(path).split(""A"")[0:-1] def count_parts(path): return Counter([s +""A"" for s in path]) with open('input.txt') as f: lines = f.read().splitlines() total_complexity = 0 for line in lines: counts = count_parts(get_shortest(NUMS, 'A' + line)) for i in range(25): next_counts = defaultdict(int) for seq, count in counts.items(): for k, v in count_parts(get_shortest(ARROWS, 'A' + seq)).items(): next_counts[k] += count * v counts = next_counts length = sum([len(k) * v for k, v in counts.items()]) total_complexity += int(line[0:-1]) * length print(total_complexity)",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"import functools with open(""21.txt"") as i: input = [x.strip() for x in i.readlines()] test_data = """"""029A 980A 179A 456A 379A"""""".split(""\n"") # input = test_data # +---+---+---+ # | 7 | 8 | 9 | # +---+---+---+ # | 4 | 5 | 6 | # +---+---+---+ # | 1 | 2 | 3 | # +---+---+---+ # | 0 | A | # +---+---+ numeric_keys = { ""7"": (0, 0), ""8"": (1, 0), ""9"": (2, 0), ""4"": (0, 1), ""5"": (1, 1), ""6"": (2, 1), ""1"": (0, 2), ""2"": (1, 2), ""3"": (2, 2), ""0"": (1, 3), ""A"": (2, 3), } # +---+---+ # | ^ | A | #+---+---+---+ #| < | v | > | #+---+---+---+ directional_keys = { ""^"": (1, 0), ""A"": (2, 0), ""<"": (0, 1), ""v"": (1, 1), "">"": (2,1) } allowed_num_pos = [v for v in numeric_keys.values()] allowed_dir_pos = [v for v in directional_keys.values()] pos = (2,3) x, y = pos def find_keystrokes(src, target, directional): if src == target: return [""A""] if not directional and not src in allowed_num_pos: return [] if directional and not src in allowed_dir_pos: return [] x1, y1 = src x2, y2 = target res = [] if x1""+s for s in find_keystrokes((x1+1, y1), target, directional)]) elif x1>x2: res.extend([""<""+s for s in find_keystrokes((x1-1, y1), target, directional)]) if y1y2: res.extend([""^""+s for s in find_keystrokes((x1, y1-1), target, directional)]) return res @functools.cache def find_shortest_to_click(a, b, depth=2): # Assume we start at A always? opts = find_keystrokes(directional_keys[a], directional_keys[b], True) if depth == 1: return min([len(x) for x in opts]) tmps = [] for o in opts: tmp = [] tmp.append(find_shortest_to_click(""A"", o[0], depth-1)) for i in range(1, len(o)): tmp.append(find_shortest_to_click(o[i-1], o[i], depth-1)) tmps.append(sum(tmp)) return min(tmps) def find_shortest(code, levels): pos = numeric_keys[""A""] shortest = 0 for key in code: possible_key_sequences = find_keystrokes(pos, numeric_keys[key], False) tmps = [] for sequence in possible_key_sequences: tmp = [] tmp.append(find_shortest_to_click(""A"", sequence[0], levels)) for i in range(1, len(sequence)): tmp.append(find_shortest_to_click(sequence[i-1], sequence[i], levels)) tmps.append(sum(tmp)) pos = numeric_keys[key] shortest += min(tmps) return shortest def find_total_complexity(codes, levels): complexities = [] for code in input: s = find_shortest(code, levels) complexities.append(s*int(code[:-1])) return sum(complexities) print(find_total_complexity(input, 25))",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"#!/usr/bin/env python3 import re from collections import deque from itertools import product myfile = open(""21.in"", ""r"") lines = myfile.read().strip().splitlines() myfile.close() part_two = 0 # fmt: off num_pad = { (0, 0): ""7"", (1, 0): ""8"", (2, 0): ""9"", (0, 1): ""4"", (1, 1): ""5"", (2, 1): ""6"", (0, 2): ""1"", (1, 2): ""2"", (2, 2): ""3"", (1, 3): ""0"", (2, 3): ""A"", } num_pad_t = {v: k for k, v in num_pad.items()} dir_pad = { (1, 0): ""^"", (2, 0): ""A"", (0, 1): ""<"", (1, 1): ""v"", (2, 1): "">"", } dir_pad_t = {v: k for k, v in dir_pad.items()} # fmt: on button_dirs = {""<"": (-1, 0), "">"": (1, 0), ""^"": (0, -1), ""v"": (0, 1)} def dfs(start, end, use_dir_pad=True): key_pad = dir_pad if use_dir_pad else num_pad sequences = set() seen = set() q = deque([("""", start)]) while q: sequence, pos = q.popleft() seen.add(pos) if pos == end: sequences.add(sequence + ""A"") continue buttons = [""<"", ""^"", ""v"", "">""] for btn in buttons: d_x, d_y = button_dirs[btn] next_pos = (pos[0] + d_x, pos[1] + d_y) if next_pos not in seen and next_pos in key_pad: q.append((sequence + btn, next_pos)) min_len = min(len(x) for x in sequences) return {x for x in sequences if len(x) == min_len} def get_sequences(sequence, use_dir_pad=True): key_pad_t = dir_pad_t if use_dir_pad else num_pad_t sub_sequences = [] start = key_pad_t[""A""] for c in sequence: end = key_pad_t[c] sub_sequences.append(dfs(start, end, use_dir_pad)) start = end sequences = {"""".join(x) for x in product(*sub_sequences)} min_len = min(len(x) for x in sequences) return {x for x in sequences if len(x) == min_len} memo = {} def solve(sequence, robots, is_code=False): if robots == 0: return len(sequence) if (sequence, robots) not in memo: total = 0 sub_sequences = list(re.findall(r"".*?A"", sequence)) for sub_seq in sub_sequences: total += min( solve(s, robots - 1) for s in get_sequences(sub_seq, not is_code) ) memo[(sequence, robots)] = total return memo[(sequence, robots)] for code in lines: numeric_code = int(code[:-1]) part_two += solve(code, 26, is_code=True) * numeric_code print(""Part Two:"", part_two)",python 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. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"#day 21 import os from itertools import pairwise from functools import cache def reader(): return open(f""input.txt"", 'r').read().splitlines() def getPT(G, chars): P = {c: (i, j) for i, r in enumerate(G) for j, c in enumerate(r)} T = {c1: {c2: set() for c2 in chars} for c1 in chars} for c1 in T: for c2 in T[c1]: (x1, y1), (x2, y2) = P[c1], P[c2] v, vc = 'v' if x1 < x2 else '^', abs(x2 - x1) h, hc = '>' if y1 < y2 else '<', abs(y2 - y1) if G[x1][y2] in chars: T[c1][c2].add(h * hc + v * vc) if G[x2][y1] in chars: T[c1][c2].add(v * vc + h * hc) return P, T def part2(): f = reader() G0 = [ ['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['#', '0', 'A'], ] GC = [ ['#', '^', 'A'], ['<', 'v', '>'] ] _, G0T = getPT(G0, '0123456789A') _, GCT = getPT(GC, '<^>vA') def r(T, s, i=0, c='A'): return [[t1] + t2 for t1 in T[c][s[i]] for t2 in r(T, s, i + 1, s[i])] if i < len(s) else [[]] @cache def count(c1, c2, M): return min(sum(count(cc1, cc2, M - 1) for cc1, cc2 in pairwise('A' + t + 'A')) for t in GCT[c1][c2]) if M > 0 else 1 ans = 0 for s0 in f: l = min(sum(count(cc1, cc2, 25) for cc1, cc2 in pairwise('A' + t + 'A')) for t in map(lambda l: 'A'.join(l), r(G0T, s0))) ans += l * int(s0[:-1]) print(ans) part2()",python 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). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"from collections import defaultdict with open('input.txt') as f: lines = f.read().splitlines() connections = defaultdict(set) pairs = [tuple(line.split(""-"")) for line in lines] for pair in pairs: connections[pair[0]].add(pair[1]) connections[pair[1]].add(pair[0]) trios = set() for pair in pairs: intersection = connections[pair[0]].intersection(connections[pair[1]]) for val in intersection: trios.add(tuple(sorted((pair[0], pair[1], val)))) trios_with_t = [trio for trio in trios if any(v.startswith(""t"") for v in trio)] print(len(trios_with_t))",python 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). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"import argparse import re from collections import defaultdict from typing import Iterable class Network: completed_networks: defaultdict[int, set[tuple[str, ...]]] nodes: defaultdict[str, set[str]] def __init__(self, text: str): cache: defaultdict[str, set[str]] = defaultdict(set) for m in re.finditer(r'(..)-(..)', text): a = m.group(1) b = m.group(2) cache[a].add(b) cache[b].add(a) self.nodes = cache self.completed_networks = defaultdict(set) def get_names(self): return self.nodes.keys() def get_largest_networks(self): largest_network_length = max(*self.completed_networks.keys()) return list(self.completed_networks[largest_network_length]) def get_complete_network_with_n_nodes(self, n: int): return list(self.completed_networks[n]) def build_network_for(self, names: Iterable[str]): networks = self.completed_networks for name in names: name_pool = set(self.nodes[name]) depth = 1 work: set[tuple[str, ...]] = {(name,)} while work: next_work = set() for network in work: # Don't bother with already explored networks if network in networks[depth]: continue networks[depth].add(network) for next_name in name_pool.difference(network): if self.nodes[next_name].issuperset(network): next_work.add(tuple(sorted({*network, next_name}))) depth += 1 work = next_work def solve(input_path: str, /, **_kwargs): with open(input_path, ""r"", encoding='utf-8') as file: input_text = file.read().strip().replace('\r', '') network = Network(input_text) names_with_t = [name for name in network.get_names() if name.startswith('t')] network.build_network_for(names_with_t) p1 = len(network.get_complete_network_with_n_nodes(3)) print(f'p1 = {p1}') largest_networks = network.get_largest_networks() assert len(largest_networks) == 1, ""p2 solution should have a single, unique answer"" p2 = ','.join(largest_networks[0]) print(f'p2 = {p2}') def main(): parser = argparse.ArgumentParser() parser.add_argument(""input"", nargs=""?"", default=""sample.txt"") parser.add_argument(""-v"", ""--verbose"", action=""store_true"") args = parser.parse_args() solve(args.input, verbose=args.verbose) if __name__ == ""__main__"": main()",python 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). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"from collections import defaultdict with open(""./day_23.in"") as fin: lines = fin.read().strip().split(""\n"") adj = defaultdict(list) for line in lines: a, b = line.split(""-"") adj[a].append(b) adj[b].append(a) triangles = set() for a in dict(adj): for i in adj[a]: for j in adj[a]: if j in adj[i]: triangles.add(tuple(sorted([a, i, j]))) ans = 0 for a, b, c in triangles: if ""t"" in [a[0], b[0], c[0]]: ans += 1 print(ans)",python 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). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"def readfile(): file_name = ""23.txt"" mapping = {} with open(file_name) as f: tuples = [tuple(line.strip().split(""-"")) for line in f.readlines()] # Add reverse order as well tuples += [(i[1], i[0]) for i in tuples] # Map all computers to which they are connected for key, val in tuples: if key in mapping: mapping[key].append(val) else: mapping[key] = [val] return mapping def make_mapping_part1(mapping, computer, depth, lan_party, lan_parties): # We have reached 3 computers so make sure that we have closed the loop if depth == 0: if lan_party[0] == lan_party[-1] and any( [i.startswith(""t"") for i in lan_party] ): lan_parties.add(tuple(sorted(lan_party[:3]))) return # Check all computers that are connected to the current one for val in mapping[computer]: lan_party.append(val) make_mapping_part1(mapping, val, depth - 1, lan_party, lan_parties) del lan_party[-1] def part1(mapping): lan_parties = set() # Find all lan parties with exactly 3 computers for computer in mapping: make_mapping_part1(mapping, computer, 3, [computer], lan_parties) print(len(lan_parties)) if __name__ == ""__main__"": test_file = False mapping = readfile() print(""Answer to part 1:"") part1(mapping)",python 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). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"#!/usr/bin/env python3 from collections import defaultdict from itertools import combinations myfile = open(""23.in"", ""r"") lines = myfile.read().strip().splitlines() myfile.close() conns = defaultdict(set) part_one = 0 for line in lines: a, b = line.split(""-"") conns[a].add(b) conns[b].add(a) trios = set() for comp, others in conns.items(): pairs = combinations(others, 2) for a, b in pairs: if b in conns[a]: trios.add(frozenset([comp, a, b])) for t in trios: if any(x.startswith(""t"") for x in t): part_one += 1 print(""Part One:"", part_one)",python 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). 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","from collections import defaultdict def bron_kerbosch(connections, R, P, X): if len(P) == 0 and len(X) == 0: yield R while len(P) > 0: v = P.pop() yield from bron_kerbosch(connections, R.union(set([v])), P.intersection(connections[v]), X.intersection(connections[v])) X = X.union(set([v])) with open('input.txt') as f: lines = f.read().splitlines() connections = defaultdict(set) pairs = [tuple(line.split(""-"")) for line in lines] for pair in pairs: connections[pair[0]].add(pair[1]) connections[pair[1]].add(pair[0]) cliques = bron_kerbosch(connections, set(), set(connections.keys()), set()) print("","".join(sorted(max(cliques, key=len))))",python 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). 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","f = open(""input.23.txt"") graph = {} for p in f: [a,b] = p.strip().split(""-"") if(a in graph.keys()): graph[a].append(b) else: graph[a] = [b] if(b in graph.keys()): graph[b].append(a) else: graph[b] = [a] f.close() triplets = [] v = [] #visited def gettriplet(n2,n1): ret = [] for n3 in graph[n2]: if n1 in graph[n3]: ret.append('-'.join(sorted([n1,n2,n3]))) return ret for n in graph.keys(): if n in v: continue v.append(n) for nbr in graph[n]: t = gettriplet(nbr,n) if len(t) > 0: triplets.extend(t) ans = 0 triplets = list(set(triplets)) for triplet in triplets: if triplet.find('t') >= 0: ans += 1 print(triplet) print(ans)",python 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). 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","from collections import defaultdict import itertools def is_clique(connections, nodes): for i, node1 in enumerate(nodes): for _, node2 in enumerate(nodes[i+1:]): if node2 not in connections[node1]: return False return True def max_clique_starting_at(connections, node): neighbors = connections[node] for i in range(len(neighbors), 1, -1): for group in itertools.combinations(neighbors, i): if is_clique(connections, group): return set([node, *group]) return set() with open('input.txt') as f: lines = f.read().splitlines() connections = defaultdict(set) pairs = [tuple(line.split(""-"")) for line in lines] for pair in pairs: connections[pair[0]].add(pair[1]) connections[pair[1]].add(pair[0]) cliques = [max_clique_starting_at(connections, node) for node in connections.keys()] max_clique = max(cliques, key=len) print("","".join(sorted(max_clique)))",python 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). 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","from collections import defaultdict from copy import deepcopy with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() connections = defaultdict(set) for connection in input_text: person1, person2 = connection.split(""-"") connections[person1].add(person2) connections[person2].add(person1) max_clique_size = 0 max_clique = set() def bron_kerbosch(R, P, X): global max_clique global max_clique_size if (not P) and (not X) and len(R) > max_clique_size: max_clique = R max_clique_size = len(R) for person in deepcopy(P): bron_kerbosch(R | {person}, P & connections[person], X & connections[person]) P -= {person} X |= {person} bron_kerbosch(set(), set(connections.keys()), set()) print("","".join(sorted(max_clique)))",python 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). 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","def parse() -> list[tuple[str]]: return [(line.strip().split(""-"")[0], line.strip().split(""-"")[1]) for line in open(""input.txt"").readlines()] def generate_graph(connections) -> dict: nodes = {} for connection in connections: if nodes.get(connection[0]) == None: nodes[connection[0]] = set() if nodes.get(connection[1]) == None: nodes[connection[1]] = set() nodes[connection[0]].add(connection[1]) nodes[connection[1]].add(connection[0]) return nodes def part1(): connections = parse() graph = generate_graph(connections) # Finds a three length loop with at least one containg t found = set() for node, neighbors in graph.items(): for neighbor in neighbors: for neighbors_neighbor in graph[neighbor]: if node in graph[neighbors_neighbor]: if node.startswith(""t"") or neighbor.startswith(""t"") or neighbors_neighbor.startswith(""t""): s = sorted([node, neighbor, neighbors_neighbor]) found.add(tuple(s)) print(len(found)) def neighbors_all(node: str, graph: dict, subgraph: set) -> bool: for n in subgraph: if node not in graph[n]: return False return True def part2(): connections = parse() graph = generate_graph(connections) biggest_subgraph = set() for node, neighbors in graph.items(): result = set() result.add(node) for neighbor in neighbors: if neighbors_all(neighbor, graph, result): result.add(neighbor) if len(result) > len(biggest_subgraph): biggest_subgraph = result in_order = sorted([x for x in biggest_subgraph]) print("","".join(in_order)) part2()",python 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. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"import operator from pprint import pprint import re with open(""input24.txt"") as i: input = [x.strip() for x in i.readlines()] test_data_1 = """"""x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02"""""".split(""\n"") test_data_2 = """"""x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj"""""".split(""\n"") # input = test_data_1 # input = test_data_2 wires = {} i = 0 while input[i]!="""": n, v = input[i].split("": "") wires[n] = int(v) i += 1 operator_lookup = { ""AND"": operator.and_, ""OR"": operator.or_, ""XOR"": operator.xor } gates = {} for l in input[i+1:]: l, op, r, o = re.match(r""(.+) (AND|OR|XOR) (.+) -> (.+)"", l).groups() gates[o] = (l, operator_lookup[op], r) def get_bit(name: str) -> int: if name in wires.keys(): return wires[name] l, op, r = gates[name] res = op(get_bit(l), get_bit(r)) return res bit_count = max([int(x[1:]) for x in gates.keys() if x.startswith(""z"")])+1 res = 0 for i in range(bit_count-1,-1, -1): b = get_bit(f""z{i:02}"") res = (res<<1) | b print(res) def swap_gates(a, b): t = gates[a] gates[a] = gates[b] gates[b] = t def add(a: int, b: int) -> int: for i in range(bit_count): wires[f""x{i:02}""] = (a>>i)%2 wires[f""y{i:02}""] = (b>>i)%2 res = 0 try: for i in range(bit_count-1,-1, -1): c = get_bit(f""z{i:02}"") res = (res<<1) | c except RecursionError: raise ""Loop detected"" return res def find_gate(a, op, b): for k, v in gates.items(): aa, opp, bb = v if ((a==aa and b==bb) or (a==bb and b==aa)) and opp==op: return k return None def find_gate2(a, op): for k, v in gates.items(): if (v[0]==a or v[2]==a) and op==v[1]: return k print() # f[i] = x[i] xor y[i] # g[i] = x[i] and y[i] # z[i] = (x[i] xor y[i]) xor r[i-1] # z[i] = f[i] xor r[i-1] # r[i] = (x[i] and y[i]) or ((x[i] xor y[i]) and r[i-1]) # r[i] = g[i] or (f[i] and r[i-1]) remainders = [find_gate(""x00"", operator.and_, ""y00"")] f = [find_gate(f""x{i:02}"", operator.xor, f""y{i:02}"") for i in range(0, bit_count)] g = [find_gate(f""x{i:02}"", operator.and_, f""y{i:02}"") for i in range(0, bit_count)] swaps = [] for i in range(1, bit_count-1): e = find_gate2(f[i], operator.xor) if e is not None and e!=f""z{i:02}"": swaps.append((e, f""z{i:02}"")) elif e is None: print(f""No swap found for bit {i}..."") # e = find_gate2(remainders[i-1], operator.xor) # print(e) # print(remainders) # swaps.append() # x = find_gate2(f[i], operator.and_) # rr = find_gate2(g[i], operator.or_) # print(x, rr) remainders.append(find_gate2(g[i], operator.or_)) print("","".join(sorted([x for y in swaps for x in y])))",python 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. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() states = {} z_wires = [] XOR = [] OR = [] AND = [] for line in input_text: if "":"" in line: wire, value = line.split("": "") states[wire] = bool(int(value)) elif ""XOR"" in line: wires, output = line.split("" -> "") wire1, wire2 = wires.split("" XOR "") XOR.append((wire1, wire2, output)) if output[0] == ""z"": z_wires.append(output) elif ""OR"" in line: wires, output = line.split("" -> "") wire1, wire2 = wires.split("" OR "") OR.append((wire1, wire2, output)) if output[0] == ""z"": z_wires.append(output) elif ""AND"" in line: wires, output = line.split("" -> "") wire1, wire2 = wires.split("" AND "") AND.append((wire1, wire2, output)) if output[0] == ""z"": z_wires.append(output) while not all(z in states for z in z_wires): for op_list, op in ((XOR, ""__xor__""), (OR, ""__or__""), (AND, ""__and__"")): new_list = [] for wire1, wire2, output in op_list: if states.get(wire1) is not None and states.get(wire2) is not None: states[output] = getattr(states[wire1], op)(states[wire2]) else: new_list.append((wire1, wire2, output)) op_list = new_list place = 0 total = 0 while f""z{place:02d}"" in states: total += int(states[f""z{place:02d}""]) << place place += 1 print(total)",python 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. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"wires = {} gates = [] with open(""day24-data.txt"") as f: initial = True for line in f.readlines(): if line == ""\n"": initial = False continue if initial: wires[line.split()[0].strip(':')] = int(line.split()[1]) else: gate = line.strip('\n').split() gates.append([gate[0], gate[1], gate[2], gate[4], False]) for gate in gates: if gate[0] not in wires: wires[gate[0]] = -1 if gate[2] not in wires: wires[gate[2]] = -1 all_done = False while not all_done: print('*', end='') all_done = True for gate in gates: if wires[gate[0]] != -1 and wires[gate[2]] != -1 and gate[4] == False: if gate[1] == ""AND"": wires[gate[3]] = 1 if wires[gate[0]] + wires[gate[2]] == 2 else 0 elif gate[1] == ""OR"": wires[gate[3]] = 1 if wires[gate[0]] + wires[gate[2]] >= 1 else 0 else: wires[gate[3]] = 1 if wires[gate[0]] != wires[gate[2]] else 0 gate[4] = True print('.', end='') elif gate[4] == False: all_done = False print() #print(sorted(wires.items())) #print(gates) output = {} for key, val in wires.items(): if key[0] == 'z': output[key] = val sorted_output = dict(sorted(output.items())) power = 0 dec = 0 for key, val in sorted_output.items(): print(key, val) dec += val * (2**power) power += 1 print(dec)",python 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. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"#!/usr/bin/python3 class Wire: def __init__(self, name, wire_val): self.name = name self.wire_val = wire_val class Gate: def __init__(self, logic:str, input_1:str, input_2:str): self.logic = logic self.input_1 = input_1 self.input_2 = input_2 def get_output(self, wire_dict:dict) -> str: if self.logic == ""AND"": return (""1"" if wire_dict[self.input_1].wire_val == ""1"" and wire_dict[self.input_2].wire_val == ""1"" else ""0"") elif self.logic == ""OR"": return (""1"" if wire_dict[self.input_1].wire_val == ""1"" or wire_dict[self.input_2].wire_val == ""1"" else ""0"") elif self.logic == ""XOR"": return (""1"" if wire_dict[self.input_1].wire_val != wire_dict[self.input_2].wire_val else ""0"") with open(""input.txt"") as file: wires = {} gates = {} for line in file: line = line.strip() if "":"" in line: wires[line.split("": "")[0]] = Wire(line.split("": "")[0], line.split("": "")[1]) elif ""->"" in line: gates[line.split()[4]] = Gate(line.split()[1], line.split()[0], line.split()[2]) while any(gate not in wires for gate in gates): for gate in gates: if (gates[gate].input_1 in wires.keys() and gates[gate].input_2 in wires.keys()): out_val = gates[gate].get_output(wires) wires[gate] = Wire(gate, out_val) z_wires = sorted([wires[wire].name for wire in wires if wires[wire].name.startswith(""z"")]) z_bits = """".join([wires[z].wire_val for z in z_wires[::-1]]) print('Decimal number output on the wires starting with ""z"":', int(z_bits, 2))",python 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. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"#!/usr/bin/env python3 from collections import deque myfile = open(""24.in"", ""r"") lines = myfile.read().strip().split(""\n\n"") myfile.close() in_vals, out_vals = lines[0].splitlines(), lines[1].splitlines() wires = {} for line in in_vals: wire, val = line.split("": "") wires[wire] = int(val) q = deque(out_vals) while q: curr = q.popleft() wires_in, out_wire = curr.split("" -> "") left, op, right = wires_in.split("" "") if left not in wires or right not in wires: q.append(curr) continue result = -1 if op == ""XOR"": result = wires[left] ^ wires[right] elif op == ""OR"": result = wires[left] | wires[right] elif op == ""AND"": result = wires[left] & wires[right] wires[out_wire] = result x_wires, y_wires, z_wires = [], [], [] for wire in wires.keys(): if ""x"" in wire: x_wires.append(wire) elif ""y"" in wire: y_wires.append(wire) elif ""z"" in wire: z_wires.append(wire) x_wires.sort(reverse=True) y_wires.sort(reverse=True) z_wires.sort(reverse=True) x_digits = [str(wires[w]) for w in x_wires] y_digits = [str(wires[w]) for w in y_wires] z_digits = [str(wires[w]) for w in z_wires] x_dec = int("""".join(x_digits), 2) y_dec = int("""".join(y_digits), 2) z_dec = int("""".join(z_digits), 2) part_one = z_dec print(""Part One:"", part_one) # part two analysis for manual solving print() print(""Part Two Analysis"") width = len(z_digits) expected = f""{x_dec + y_dec:0{width}b}""[::-1] actual = f""{z_dec:0{width}b}""[::-1] # z wires that must swap must_swap = [] for line in out_vals: wires_in, out_wire = line.split("" -> "") left, op, right = wires_in.split("" "") if out_wire.startswith(""z""): if out_wire != f""z{width - 1}"" and op != ""XOR"": must_swap.append(out_wire) elif out_wire == f""z{width - 1}"" and op != ""OR"": must_swap.append(out_wire) print(""Must swap:"") print("", "".join(must_swap)) # z wires where something is wrong wrong_z = [] for i, digit in enumerate(expected): if digit != actual[i]: wrong_z.append(f""z{i:02}"") print(""Investigate:"") print("", "".join(wrong_z))",python 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. 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","class Gate: def __init__(self, inputs, op, label): self.inputs = inputs self.op = op self.label = label def __eq__(self, other): if type(self) == type(other): return self.op == other.op and self.inputs == other.inputs and self.label == self.label else: return False def __hash__(self): return hash((self.op, self.inputs, self.label)) def __str__(self): first, second = sorted(map(str, self.inputs)) return f""({first} {self.op} {second})"" class Circuit: def __init__(self, input_lines): self.input_digit_xors = [] self.input_digit_ands = [] self.output_to_expr = {} self.expr_to_output = {} self.invalid_input_ands = {} self.result_gates = [] self.carry_gates = [] self.__parse_input(input_lines) def __parse_input(self, input_lines): for line in input_lines: if ""->"" in line: expr, wire = line.split("" -> "") left, op, right = expr.split("" "") left, right = sorted((left, right)) self.output_to_expr[wire] = (left, right, op) self.expr_to_output[(left, right, op)] = wire input_exprs = dict({(k, v) for (k, v) in self.expr_to_output.items() if k[0].startswith(""x"")}) for input_expr in sorted(input_exprs.items()): idx = int(input_expr[0][0][1:]) op = input_expr[0][2] res = input_expr[1] if op == 'AND': self.input_digit_ands.append(res) if (res.startswith(""z"")): self.invalid_input_ands[idx] = res elif op == 'XOR': self.input_digit_xors.append(res) for i in range(len(self.input_digit_xors) + 1): input_bits_xor_gate = Gate((f""x{i:02}"", f""y{i:02}""), ""XOR"", None) input_bits_and_gate = Gate((f""x{i:02}"", f""y{i:02}""), ""AND"", None) if i == 0: result_gate = input_bits_xor_gate carry_gate = input_bits_and_gate else: result_gate = Gate((input_bits_xor_gate, self.carry_gates[i - 1]), ""XOR"", None) carry_gate = Gate((input_bits_and_gate, Gate((input_bits_xor_gate, self.carry_gates[i - 1]), ""AND"", None)), ""OR"", None) self.result_gates.append(result_gate) self.carry_gates.append(carry_gate) print(self.result_gates[-1]) with open('input.txt') as f: lines = f.read().splitlines() circuit = Circuit(lines) output_to_expr = dict() expr_to_output = dict() for line in lines: if ""->"" in line: expr, wire = line.split("" -> "") left, op, right = expr.split("" "") left, right = sorted((left, right)) output_to_expr[wire] = (left, right, op) expr_to_output[(left, right, op)] = wire input_exprs = dict({(k, v) for (k, v) in expr_to_output.items() if k[0].startswith(""x"")}) input_digit_xors = [] input_digit_ands = [] output_digit_carries = [] output_digit_results = [] invalid_input_ands = {} for input_expr in sorted(input_exprs.items()): idx = int(input_expr[0][0][1:]) op = input_expr[0][2] res = input_expr[1] if op == 'AND': input_digit_ands.append(res) if (res.startswith(""z"")): print(f""{res} is an AND!"") invalid_input_ands[idx] = res elif op == 'XOR': input_digit_xors.append(res) print(input_digit_xors) print(input_digit_ands) swaps = {} for i in range(len(input_digit_xors)): if i == 0: output_digit_results.append(input_digit_xors[0]) output_digit_carries.append(input_digit_ands[0]) else: result_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), ""XOR"") if result_op not in expr_to_output: incorrect = output_to_expr[f""z{i:02}""] swap1 = set(result_op).difference(set(incorrect)).pop() swap2 = set(incorrect).difference(set(result_op)).pop() print(f""need to swap {swap1} and {swap2}"") swaps[swap1] = swap2 swaps[swap2] = swap1 result_output = expr_to_output[incorrect] if input_digit_xors[i] == swap1: print(""swapping input digit xors to"", swap2) input_digit_xors[i] = swap2 if input_digit_ands[i] == swap2: print(""swapping input digit ands to"", swap1) input_digit_ands[i] = swap1 else: result_output = expr_to_output[result_op] if not result_output.startswith(""z""): expected_output = f""z{i:02}"" if i in invalid_input_ands and expected_output == invalid_input_ands[i]: print(f""need to swap {expected_output} and {result_output}"") swaps[result_output] = expected_output swaps[expected_output] = result_output print(""swapping input digit ands to"", result_output) input_digit_ands[i] = result_output print(""swapping result"") result_output = expected_output else: print(f""need to swap {expected_output} and {result_output}"") swaps[result_output] = expected_output swaps[expected_output] = result_output print(""swapping result"") result_output = expected_output elif int(result_output[1:]) != i: if result_output in swaps: expr_to_output[result_op] = swaps[result_output] else: expected_output = f""z{i:02}"" print(f""need to swap {result_output} and {expected_output}"") swaps[expected_output] = result_output swaps[result_output] = expected_output expr_to_output[result_op] = expected_output output_digit_results.append(result_output) rhs_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), ""AND"") rhs_output = expr_to_output[rhs_op] if rhs_output in swaps: print(""swapping rhs"") rhs_output = swaps[rhs_output] carry_op = (*sorted((input_digit_ands[i], rhs_output)), ""OR"") carry_output = expr_to_output[carry_op] if carry_output in swaps: print(""swapping carry"") carry_output = swaps[carry_output] output_digit_carries.append(carry_output) print(f""{i:02} is in {result_output} with carry {carry_output}"") print("","".join(sorted(swaps.keys())))",python 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. 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","with open('input.txt') as f: lines = f.read().splitlines() output_to_expr = dict() expr_to_output = dict() for line in lines: if ""->"" in line: expr, wire = line.split("" -> "") left, op, right = expr.split("" "") left, right = sorted((left, right)) output_to_expr[wire] = (left, right, op) expr_to_output[(left, right, op)] = wire input_exprs = dict({(k, v) for (k, v) in expr_to_output.items() if k[0].startswith(""x"")}) input_digit_xors = [] input_digit_ands = [] output_digit_carries = [] output_digit_results = [] invalid_input_ands = {} for input_expr in sorted(input_exprs.items()): idx = int(input_expr[0][0][1:]) op = input_expr[0][2] res = input_expr[1] if op == 'AND': input_digit_ands.append(res) if (res.startswith(""z"")): print(f""{res} is an AND!"") invalid_input_ands[idx] = res elif op == 'XOR': input_digit_xors.append(res) print(input_digit_xors) print(input_digit_ands) swaps = {} for i in range(len(input_digit_xors)): if i == 0: output_digit_results.append(input_digit_xors[0]) output_digit_carries.append(input_digit_ands[0]) else: result_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), ""XOR"") if result_op not in expr_to_output: incorrect = output_to_expr[f""z{i:02}""] swap1 = set(result_op).difference(set(incorrect)).pop() swap2 = set(incorrect).difference(set(result_op)).pop() print(f""need to swap {swap1} and {swap2}"") swaps[swap1] = swap2 swaps[swap2] = swap1 result_output = expr_to_output[incorrect] if input_digit_xors[i] == swap1: print(""swapping input digit xors to"", swap2) input_digit_xors[i] = swap2 if input_digit_ands[i] == swap2: print(""swapping input digit ands to"", swap1) input_digit_ands[i] = swap1 else: result_output = expr_to_output[result_op] if not result_output.startswith(""z""): expected_output = f""z{i:02}"" if i in invalid_input_ands and expected_output == invalid_input_ands[i]: print(f""need to swap {expected_output} and {result_output}"") swaps[result_output] = expected_output swaps[expected_output] = result_output print(""swapping input digit ands to"", result_output) input_digit_ands[i] = result_output print(""swapping result"") result_output = expected_output else: print(f""need to swap {expected_output} and {result_output}"") swaps[result_output] = expected_output swaps[expected_output] = result_output print(""swapping result"") result_output = expected_output elif int(result_output[1:]) != i: if result_output in swaps: expr_to_output[result_op] = swaps[result_output] else: expected_output = f""z{i:02}"" print(f""need to swap {result_output} and {expected_output}"") swaps[expected_output] = result_output swaps[result_output] = expected_output expr_to_output[result_op] = expected_output output_digit_results.append(result_output) rhs_op = (*sorted((input_digit_xors[i], output_digit_carries[i - 1])), ""AND"") rhs_output = expr_to_output[rhs_op] if rhs_output in swaps: print(""swapping rhs"") rhs_output = swaps[rhs_output] carry_op = (*sorted((input_digit_ands[i], rhs_output)), ""OR"") carry_output = expr_to_output[carry_op] if carry_output in swaps: print(""swapping carry"") carry_output = swaps[carry_output] output_digit_carries.append(carry_output) print(f""{i:02} is in {result_output} with carry {carry_output}"") print("","".join(sorted(swaps.keys())))",python 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. 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","from typing import List, Dict from collections import defaultdict from part1 import parse_input def collect_outputs(wire_values: Dict[str, int], prefix: str) -> List[int]: """""" Collects and returns a list of output values from a dictionary of wire values where the keys start with a given prefix. Args: wire_values (Dict[str, int]): A dictionary containing wire names as keys and their corresponding values. prefix (str): The prefix to filter the wire names. Returns: List[int]: A list of values from the dictionary where the keys start with the specified prefix. """""" return [value for key, value in sorted(wire_values.items()) if key.startswith(prefix)] def is_input(operand: str) -> bool: """""" Checks if the given operand is an input variable. Args: operand (str): The operand to check. Returns: bool: True if the operand is an input variable ('x' or 'y'), False otherwise. """""" return operand[0] in 'xy' def get_usage_map(gates: List[str]) -> Dict[str, List[str]]: """""" Generates a usage map from a list of gate strings. Each gate string is expected to be in the format ""source -> destination"". The function splits each gate string and maps both the source and destination to the original gate string in the resulting dictionary. Args: gates (List[str]): A list of gate strings. Returns: Dict[str, List[str]]: A dictionary where each key is a gate (either source or destination) and the value is a list of gate strings that include the key. """""" usage_map = defaultdict(list) for gate in gates: parts = gate.split(' ') usage_map[parts[0]].append(gate) usage_map[parts[2]].append(gate) return usage_map def check_xor_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool: """""" Checks if the given conditions for XOR operations are met. Args: left (str): The left operand of the XOR operation. right (str): The right operand of the XOR operation. result (str): The result of the XOR operation. usage_map (Dict[str, List[str]]): A dictionary mapping results to a list of operations that use them. Returns: bool: True if the conditions are met, False otherwise. """""" if is_input(left): if not is_input(right) or (result[0] == 'z' and result != 'z00'): return True usage_ops = [op.split(' ')[1] for op in usage_map[result]] if result != 'z00' and sorted(usage_ops) != ['AND', 'XOR']: return True elif result[0] != 'z': return True return False def check_and_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool: """""" Checks specific conditions based on the provided inputs and usage map. Args: left (str): The left operand. right (str): The right operand. result (str): The result operand. usage_map (Dict[str, List[str]]): A dictionary mapping result operands to a list of operations. Returns: bool: True if the conditions are met, False otherwise. Conditions: 1. If 'left' is an input and 'right' is not an input, return True. 2. If the operations associated with 'result' in the usage_map are not all 'OR', return True. """""" if is_input(left) and not is_input(right): return True if [op.split(' ')[1] for op in usage_map[result]] != ['OR']: return True return False def check_or_conditions(left: str, right: str, result: str, usage_map: Dict[str, List[str]]) -> bool: """""" Checks if the given conditions involving 'left', 'right', and 'result' meet certain criteria. Args: left (str): The left operand. right (str): The right operand. result (str): The result operand. usage_map (Dict[str, List[str]]): A dictionary mapping result operands to a list of operations. Returns: bool: True if any of the conditions are met: - Either 'left' or 'right' is an input. - The operations associated with 'result' in 'usage_map' are not exactly 'AND' and 'XOR'. Otherwise, returns False. """""" if is_input(left) or is_input(right): return True usage_ops = [op.split(' ')[1] for op in usage_map[result]] if sorted(usage_ops) != ['AND', 'XOR']: return True return False def find_swapped_wires(wire_values: Dict[str, int], gates: List[str]) -> List[str]: """""" Identifies and returns a list of swapped wires based on the provided wire values and gate operations. Args: wire_values (Dict[str, int]): A dictionary mapping wire names to their integer values. gates (List[str]): A list of strings representing gate operations in the format ""left op right -> result"". Returns: List[str]: A sorted list of wire names that are identified as swapped. The function processes each gate operation, checks the operation type (XOR, AND, OR), and applies specific conditions to determine if the result wire is swapped. It skips gates where the result is 'z45' or the left operand is 'x00'. """""" usage_map = get_usage_map(gates) swapped_wires = set() for gate in gates: left, op, right, _, result = gate.split(' ') if result == 'z45' or left == 'x00': continue if op == 'XOR' and check_xor_conditions(left, right, result, usage_map): swapped_wires.add(result) elif op == 'AND' and check_and_conditions(left, right, result, usage_map): swapped_wires.add(result) elif op == 'OR' and check_or_conditions(left, right, result, usage_map): swapped_wires.add(result) else: print(gate, 'unknown op') return sorted(swapped_wires) if __name__ == ""__main__"": wire_values, gates = parse_input('input.txt') swapped_wires = find_swapped_wires(wire_values, gates) result = ','.join(swapped_wires) print(result)",python 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. 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 get_expr_for_output(output): return output_to_expr[swaps.get(output, output)] def get_output_for_expr(expr): output = expr_to_output[expr] return swaps.get(output, output) def swap(out_a, out_b): print(f""SWAP: {out_a} for {out_b}"") swaps[out_a] = out_b swaps[out_b] = out_a def find_matching_expr(output, op): matching = [expr for expr in expr_to_output if expr[2] == op and output in (expr[0], expr[1])] if len(matching) == 0: return None assert len(matching) == 1 return matching[0] with open('input.txt') as f: lines = f.read().splitlines() output_to_expr = dict() expr_to_output = dict() swaps = dict() carries = [] max_input_bit_index = -1 for line in lines: if ""->"" in line: expr, wire = line.split("" -> "") left, op, right = expr.split("" "") left, right = sorted((left, right)) output_to_expr[wire] = (left, right, op) expr_to_output[(left, right, op)] = wire if "":"" in line: max_input_bit_index = max(max_input_bit_index, int(line.split("":"")[0][1:])) num_input_bits = max_input_bit_index + 1 for i in range(num_input_bits): z_output = f""z{i:02}"" input_xor_expr = (f""x{i:02}"", f""y{i:02}"", ""XOR"") input_and_expr = (f""x{i:02}"", f""y{i:02}"", ""AND"") input_xor_output = get_output_for_expr(input_xor_expr) input_and_output = get_output_for_expr(input_and_expr) if i == 0: if z_output == input_xor_output: carries.append(input_and_output) continue else: raise ValueError(""Error in first digits"") result_expr = find_matching_expr(input_xor_output, ""XOR"") if result_expr == None: result_expr = find_matching_expr(carries[i - 1], ""XOR"") actual_input_xor_output = result_expr[1] if result_expr[0] == carries[i - 1] else result_expr[0] swap(actual_input_xor_output, input_xor_output) else: carry_input = result_expr[1] if result_expr[0] == input_xor_output else result_expr[0] if carry_input != carries[i - 1]: swap(carry_input, carries[i - 1]) carries[i - 1] = carry_input if z_output != get_output_for_expr(result_expr): swap(z_output, get_output_for_expr(result_expr)) intermediate_carry_expr = (*sorted((get_output_for_expr(input_xor_expr), carries[i - 1])), ""AND"") intermediate_carry_output = get_output_for_expr(intermediate_carry_expr) carry_expr = find_matching_expr(intermediate_carry_output, ""OR"") if carry_expr == None: print(""TODO"") else: expected_input_and_output = carry_expr[1] if carry_expr[0] == intermediate_carry_output else carry_expr[0] if expected_input_and_output != get_output_for_expr(input_and_expr): swap(get_output_for_expr(input_and_expr), expected_input_and_output) carry_expr = (*sorted((get_output_for_expr(input_and_expr), intermediate_carry_output)), ""OR"") carry_output = get_output_for_expr(carry_expr) carries.append(carry_output) print(*sorted(swaps.keys()), sep="","")",python 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. 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","#day 24 import os from functools import cache import re from itertools import chain def reader(): return open(f""24.txt"", 'r').read().splitlines() def part2(): f = '\n'.join(reader()).split('\n\n') B = {} for l in f[0].split('\n'): v, b = l.split(': ') B[v] = int(b) F = {} D = {} for l in f[1].split('\n'): f, v = l.split(' -> ') v1, op, v2 = f.split(' ') v1, v2 = sorted((v1, v2)) D[v] = {v1, v2} op = {'XOR': '^', 'AND': '&', 'OR': '|'}[op] F[v] = f""{v1} {op} {v2}"" for vv in [v, v1, v2]: if vv not in B: B[vv] = None def swap(s1, s2): F[s1], F[s2] = F[s2], F[s1] D[s1], D[s2] = D[s2], D[s1] # swap('z15', 'jgc') # swap('z22', 'drg') # swap('z35', 'jbp') # swap('qjb', 'gvw') def r(v): if B[v] is None: for dv in D[v]: r(dv) B[v] = eval(F[v], None, B) return B[v] def getNum(s): return int(''.join(map(lambda t: str(t[1]), sorted( filter(lambda t: t[0][0] == s, B.items()), reverse=True))), base=2) for v in B: r(v) @cache def getFullFormula(v): if v[0] in {'x', 'y'}: return v v1, op, v2 = F[v].split(' ') v1, v2 = sorted((v1, v2)) return f""({getFullFormula(v1)}) {op} ({getFullFormula(v2)})"" FD = {} for v in D: formula = getFullFormula(v) FD[v] = set(re.findall(r'x\d{2}|y\d{2}', formula)) problems = [] for i in range(1, len(list(filter(lambda t: t[0][0] == 'z', B.items()))) - 1): p = f'((x{i:02}) ^ (y{i:02}))' formula = getFullFormula(f'z{i:02}') if f'{p} ^' not in formula and f'^ {p}' not in formula: problems.append(i) swaps = [] for p in problems: x = f'x{p:02}' y = f'y{p:02}' z = f'z{p:02}' start = f'{x} ^ {y}' p1 = next(filter(lambda t: t[1] == start, F.items()))[0] v1, op, v2 = F[z].split(' ') if op != '^': p2 = next( filter(lambda t: f'^ {p1}' in t[1] or f'{p1} ^' in t[1], F.items()))[0] swaps.append((z, p2)) else: swaps.append( (p1, sorted((v1, v2), key=lambda v: len(getFullFormula(v)))[0])) print(','.join(sorted(chain(*swaps)))) part2()",python 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. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"#!/usr/bin/env python3 myfile = open(""25.in"", ""r"") lines = myfile.read().strip().split(""\n\n"") myfile.close() schematics = [line.split(""\n"") for line in lines] part_one = 0 keys = set() locks = set() for schematic in schematics: is_lock = schematic[0][0] == ""#"" width = len(schematic[0]) cols = [[row[i] for row in schematic] for i in range(width)] heights = tuple(c.count(""#"") - 1 for c in cols) if is_lock: locks.add(heights) else: keys.add(heights) for lock in locks: for key in keys: max_key = tuple(5 - h for h in lock) if all(h <= max_key[i] for i, h in enumerate(key)): part_one += 1 print(""Part One:"", part_one)",python 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. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"with open(""./day_25.in"") as fin: lines = fin.read().strip().split(""\n\n"") def parse(s): lock = s[0][0] == ""#"" if lock: vals = [] for j in range(5): for i in range(7): if s[i][j] == ""."": vals.append(i) break return vals, lock vals = [] for j in range(5): for i in range(6, -1, -1): if s[i][j] == ""."": vals.append(6 - i) break return vals, lock locks = [] keys = [] for s in lines: vals, lock = parse(s.split(""\n"")) if lock: locks.append(vals) else: keys.append(vals) ans = 0 for lock in locks: for key in keys: good = True for j in range(5): if lock[j] + key[j] > 7: good = False break ans += good print(ans)",python 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. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"import time def parse(lines) -> set[tuple[int, int]]: return { (x, y) for y, line in enumerate(lines) for x, char in enumerate(line) if char == ""#"" } def solve_part_1(text: str): blocks = text.split(""\n\n"") locks = [] keys = [] for b in blocks: lines = b.splitlines() schema = parse(lines[1:-1]) locks.append(schema) if lines[0] == ""#####"" else keys.append(schema) r = 0 for lock in locks: for key in keys: r += len(lock & key) == 0 return r def solve_part_2(text: str): return 0 if __name__ == ""__main__"": with open(""input.txt"", ""r"") as f: quiz_input = f.read() start = time.time() p_1_solution = int(solve_part_1(quiz_input)) middle = time.time() print(f""Part 1: {p_1_solution} (took {(middle - start) * 1000:.3f}ms)"") p_2_solution = int(solve_part_2(quiz_input)) end = time.time() print(f""Part 2: {p_2_solution} (took {(end - middle) * 1000:.3f}ms)"")",python 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. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"locks = [] keys = [] with open(""day25-data.txt"") as file: lines = file.readlines() for i in range(0, len(lines), 8): schematic = [line.strip('\n') for line in lines[i+1:i+6]] schematic_transposed = [[schematic[j][i] for j in range(len(schematic))] for i in range(len(schematic[0]))] pins = [a.count('#') for a in schematic_transposed] if (lines[i] == ""#####\n""): locks.append(pins) # lock elif lines[i] == "".....\n"": keys.append(pins) # key sum = 0 for lock in locks: for key in keys: test = [lock[i] + key[i] for i in range(0, len(lock))] if max(test) < 6: sum += 1 print(""Day 25 part 1, sum ="", sum)",python 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. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"import itertools def get_lock(block): col_counts = [5] * 5 for line in block[1:6]: for i in range(5): if line[i] == ""."": col_counts[i] -= 1 return col_counts def get_key(block): col_counts = [0] * 5 for line in block[1:6]: for i in range(5): if line[i] == ""#"": col_counts[i] += 1 return col_counts with open('input.txt') as f: lines = f.read().splitlines() locks = [] keys = [] for i in range(0, len(lines), 8): block = lines[i:i+7] if block[0][0] == ""#"": locks.append(get_lock(block)) elif block[0][0] == ""."": keys.append(get_key(block)) ct_fit = sum([all([lock[i] + key[i] <= 5 for i in range(5)]) for lock, key in itertools.product(locks, keys)]) print(ct_fit)",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"data = open('input.txt').read().strip().split('\n') def generateNextNumber(num): res1 = num temp = (num * 64) res1 = (res1 ^ temp) % 16777216 res2 = res1 temp = (res1 // 32) res2 = (res2 ^ temp) % 16777216 res3 = res2 temp = (res2 * 2048) res3 = (res3 ^ temp) % 16777216 return res3 total = 0 for i in range(0, len(data)): num = int(data[i]) for i in range(2000): num = generateNextNumber(num) total += num print(total)",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"from typing import List def parse_input(file_path: str) -> List[int]: """""" Reads a file containing integers, one per line, and returns a list of these integers. Args: file_path (str): The path to the input file. Returns: List[int]: A list of integers read from the file. """""" with open(file_path) as f: return [int(line.strip()) for line in f] def next_secret_number(secret: int) -> int: """""" Calculate the next secret number based on the given secret number. The function performs a series of bitwise operations and modular arithmetic to generate a new secret number from the input secret number. Steps: 1. Multiply the secret by 64, mix with XOR, and prune with modulo 16777216. 2. Divide the result by 32, mix with XOR, and prune with modulo 16777216. 3. Multiply the result by 2048, mix with XOR, and prune with modulo 16777216. Args: secret (int): The input secret number. Returns: int: The next secret number. """""" # Step 1: Multiply by 64, mix, and prune secret = (secret ^ (secret * 64)) % 16777216 # Step 2: Divide by 32, mix, and prune secret = (secret ^ (secret // 32)) % 16777216 # Step 3: Multiply by 2048, mix, and prune secret = (secret ^ (secret * 2048)) % 16777216 return secret def generate_2000th_secret(initial_secret: int) -> int: """""" Generates the 2000th secret number starting from the given initial secret. Args: initial_secret (int): The initial secret number to start from. Returns: int: The 2000th secret number. """""" secret = initial_secret for _ in range(2000): secret = next_secret_number(secret) return secret if __name__ == ""__main__"": input_data = parse_input('input.txt') total = sum(generate_2000th_secret(secret) for secret in input_data) print(total)",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"def step(num): num = (num ^ (num * 64)) % 16777216 num = (num ^ (num // 32)) % 16777216 num = (num ^ (num * 2048)) % 16777216 return num def process_buyers(file_path): total = 0 with open(file_path) as file: for line in file: num = int(line) buyer = [num % 10] for _ in range(2000): num = step(num) buyer.append(num % 10) total += num return total def main(): total = process_buyers(""i.txt"") print(total) if __name__ == ""__main__"": main()",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"from collections import defaultdict import numpy as np with open(""input.txt"") as f: ns = list(map(int, f.read().strip().split(""\n""))) def hsh(secret): for _ in range(2000): secret ^= secret << 6 & 0xFFFFFF secret ^= secret >> 5 & 0xFFFFFF secret ^= secret << 11 & 0xFFFFFF yield secret secrets = list(map(list, map(hsh, ns))) # Part 1 print(sum(s[-1] for s in secrets))",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"def step(num): num = (num ^ (num * 64)) % 16777216 num = (num ^ (num // 32)) % 16777216 num = (num ^ (num * 2048)) % 16777216 return num def process_buyers(file_path): total = 0 with open(file_path) as file: for line in file: num = int(line) buyer = [num % 10] for _ in range(2000): num = step(num) buyer.append(num % 10) total += num return total def main(): total = process_buyers(""22.txt"") print(total) if __name__ == ""__main__"": main()",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"from collections import defaultdict import numpy as np with open(""input.txt"") as f: ns = list(map(int, f.read().strip().split(""\n""))) def hsh(secret): for _ in range(2000): secret ^= secret << 6 & 0xFFFFFF secret ^= secret >> 5 & 0xFFFFFF secret ^= secret << 11 & 0xFFFFFF yield secret # Part 2 result = defaultdict(int) for n in ns: ss = [s % 10 for s in hsh(n)] diffs = np.diff(ss) changes = set() for i in range(1996): if (change := tuple(diffs[i : i + 4])) not in changes: changes.add(change) result[change] += ss[i + 4] print(max(result.values()))",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"def step(num): num = (num ^ (num * 64)) % 16777216 num = (num ^ (num // 32)) % 16777216 num = (num ^ (num * 2048)) % 16777216 return num def process_buyers(file_path): buyers = [] with open(file_path) as file: for line in file: num = int(line) buyer = [num % 10] for _ in range(2000): num = step(num) buyer.append(num % 10) buyers.append(buyer) return buyers def calculate_sorok(buyers): sorok = {} for b in buyers: seen = set() for i in range(len(b) - 4): a1, a2, a3, a4, a5 = b[i:i+5] sor = (a2 - a1, a3 - a2, a4 - a3, a5 - a4) if sor in seen: continue seen.add(sor) if sor not in sorok: sorok[sor] = 0 sorok[sor] += a5 return sorok def main(): buyers = process_buyers(""22.txt"") sorok = calculate_sorok(buyers) print(max(sorok.values())) if __name__ == ""__main__"": main()",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"import time N = 2000 def next_secret(s): """"""3-step pseudorandom transformation for a 24-bit integer."""""" s = (s ^ ((s << 6) & 0xFFFFFF)) & 0xFFFFFF s = (s ^ (s >> 5)) & 0xFFFFFF s = (s ^ ((s << 11) & 0xFFFFFF)) & 0xFFFFFF return s def pack_diffs_into_key(d0, d1, d2, d3): """""" Each diff is offset by +9 to fit into [0..18] (5 bits each). Combine them into a single 20-bit integer. """""" return (d0 << 15) | (d1 << 10) | (d2 << 5) | d3 def solve_part_2(text: str): buyers = list(map(int, text.splitlines())) size = 1 << 20 # total possible 4-diff combinations seen = [0] * size results = [0] * size buyer_id = 1 secrets_arr = [0] * (N + 1) prices_arr = [0] * (N + 1) deltas_arr = [0] * (N + 1) for secret_number in buyers: # Fill arrays with generated secrets, prices, and deltas secrets_arr[0] = secret_number prices_arr[0] = secrets_arr[0] % 10 for i in range(1, N + 1): secrets_arr[i] = next_secret(secrets_arr[i - 1]) prices_arr[i] = secrets_arr[i] % 10 deltas_arr[i] = prices_arr[i] - prices_arr[i - 1] # From index 4 onward, we have a valid window of 4 consecutive deltas for i in range(4, N + 1): # We gather the 4 consecutive deltas leading to prices_arr[i]. d0 = deltas_arr[i - 3] + 9 d1 = deltas_arr[i - 2] + 9 d2 = deltas_arr[i - 1] + 9 d3 = deltas_arr[i] + 9 key = pack_diffs_into_key(d0, d1, d2, d3) # Only record the first time this buyer sees this pattern if seen[key] != buyer_id: seen[key] = buyer_id results[key] += prices_arr[i] buyer_id += 1 return max(results) if __name__ == ""__main__"": with open(""22.txt"", ""r"") as f: quiz_input = f.read() p_2_solution = int(solve_part_2(quiz_input)) print(f""Part 2: {p_2_solution}"")",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"import time, re, itertools as itt, collections as coll def load(file): with open(file) as f: return map(int, re.findall('\d+', f.read())) def mix_prune(s): s = (s ^ (s * 64)) % 16777216 s = (s ^ (s // 32)) % 16777216 return (s ^ (s * 2048)) % 16777216 def solve(p): part1 = part2 = 0 bananas = coll.defaultdict(int) for s in p: nums = [s := mix_prune(s) for _ in range(2000)] diffs = [b % 10 - a % 10 for a, b in itt.pairwise(nums)] first_seen_pat = set() for i in range(len(nums) - 4): pat = tuple(diffs[i:i + 4]) if pat in first_seen_pat: continue bananas[pat] += nums[i + 4] % 10 first_seen_pat.add(pat) part2 = max(bananas.values()) return part2 print(f'Solution: {solve(load(""22.txt""))}')",python 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. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"with open(""input.txt"", ""r"") as file: lines = file.readlines() def secretStep(secret): # Cleaned up secret = (secret * 64 ^ secret) % 16777216 secret = (secret // 32 ^ secret) % 16777216 secret = (secret * 2048 ^ secret) % 16777216 return secret # Custom implementation of max function def findMax(sequence_totals): max_key = None max_value = float('-inf') # Start with the smallest possible value for key, value in sequence_totals.items(): if value > max_value: max_value = value max_key = key return max_key def findMaxBananas(lines): sequence_totals = {} for line in lines: secret_number = int(line) price_list = [secret_number % 10] # Store last digit of secret numbers # Generate 2000 price steps for _ in range(2000): secret_number = secretStep(secret_number) price_list.append(secret_number % 10) tracked_sequences = set() # Examine all sequences of 4 consecutive price changes for index in range(len(price_list) - 4): p1, p2, p3, p4, p5 = price_list[index:index + 5] # Extract 5 consecutive prices price_change = (p2 - p1, p3 - p2, p4 - p3, p5 - p4) # Calculate changes if price_change in tracked_sequences: # Skip since we wont choose same again continue tracked_sequences.add(price_change) if price_change not in sequence_totals: sequence_totals[price_change] = 0 sequence_totals[price_change] += p5 # Add the price to the total # Find highest total # best_sequence = max(sequence_totals, key=sequence_totals.get) best_sequence = findMax(sequence_totals) max_bananas = sequence_totals[best_sequence] return best_sequence, max_bananas best_sequence, max_bananas = findMaxBananas(lines) print(max_bananas)",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"import time from enum import Enum import heapq file = open(""20.txt"", ""r"") start_time = time.time() class Direction(Enum): UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 class Position: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f""{self.__dict__}"" def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return hash(f""{self.x}_{self.y}"") @classmethod def list(cls): return list(map(lambda c: c.value, cls)) class TrackNode: def __init__(self, position, order): self.position = position self.order = order def __repr__(self): return f""{self.__dict__}"" def __eq__(self, other): return self.position == other.position and self.order == other.order def __hash__(self): return hash(f""{self.position}_{self.order}"") class Cheat: def __init__(self, s, e): self.s = s self.e = e def __repr__(self): return f""{self.__dict__}"" def __eq__(self, other): return self.s == other.s and self.e == other.e def __hash__(self): return hash(f""{self.s}_{self.e}"") space = 0 wall = 1 def import_matrix(matrix_string): matrix = [] start_position = None goal_position = None for line_index, line in enumerate(matrix_string.split(""\n"")): matrix.append([]) # print(line) for column_index, tile in enumerate(line): if tile == ""."": matrix[line_index].append(space) elif tile == ""#"": matrix[line_index].append(wall) elif tile == ""S"": matrix[line_index].append(space) start_position = Position(column_index, line_index) elif tile == ""E"": matrix[line_index].append(space) goal_position = Position(column_index, line_index) return (matrix, start_position, goal_position) map, start, goal = import_matrix(file.read()) def print_map(path = set()): for line_index, line in enumerate(map): string = [] for column_index, tile in enumerate(line): if Position(column_index, line_index) == start: string.append(""S"") elif Position(column_index, line_index) == goal: string.append(""E"") elif Position(column_index, line_index) in path: string.append(""O"") elif tile == wall: string.append(""#"") else: string.append(""."") print("""".join(string)) def get_valid_in_direction(current_position, direction): match direction: case Direction.UP: p = Position(current_position.x, current_position.y-1) case Direction.LEFT: p = Position(current_position.x-1, current_position.y) case Direction.RIGHT: p = Position(current_position.x+1, current_position.y) case Direction.DOWN: p = Position(current_position.x, current_position.y+1) if p.x < 0 or p.x >= len(map[0]) or p.y < 0 or p.y >= len(map): return None return (p, direction) def get_neighbors_and_cheats(current_position): directions = [Direction.LEFT, Direction.RIGHT, Direction.UP, Direction.DOWN] neighbors_in_map = [get_valid_in_direction(current_position, d) for d in directions] neighbors = [] walls_with_direction = [] for n in neighbors_in_map: if n is None: continue if map[n[0].y][n[0].x] == space: neighbors.append(n[0]) else: walls_with_direction.append(n) cheats = [] for wd in walls_with_direction: possible_cheat = get_valid_in_direction(wd[0], wd[1]) if possible_cheat is None: continue if map[possible_cheat[0].y][possible_cheat[0].x] == space: cheats.append(Cheat(wd[0], possible_cheat[0])) return (neighbors, cheats) print(""~~~~~~~~~~RESULT 1~~~~~~~~~~"") def create_track_1(): graph = {} cheats_dict = {} for line_index, line in enumerate(map): for column_index, tile in enumerate(line): if tile == wall: continue position = Position(column_index, line_index) (neighbors, cheats) = get_neighbors_and_cheats(position) graph[position] = neighbors cheats_dict[position] = cheats # track = {} # step: position track = {} # position: step cheats = {} # step: [Cheat] ignore = set() # tracks what steps to ignore in track building; should contain whole path current_position = start current_step = 0 while True: ignore.add(current_position) # track[current_step] = current_position track[current_position] = current_step if current_position == goal: break # ignore already traversed track (backward cheat is not a cheat) valid_cheats = [c for c in cheats_dict[current_position] if c.e not in ignore] cheats[current_step] = valid_cheats neighbors = graph[current_position] # assuming only one valid path forward (or none if end) for neighbor in neighbors: if neighbor not in ignore: # ignore already traversed track current_position = neighbor continue current_step += 1 return (track, cheats, current_step) (track, cheats, total_steps) = create_track_1() solution = 0 for step in cheats.keys(): for cheat in cheats[step]: length_up_to_cheat = step step_at_cheat_end = track[cheat.e] resulting_length = length_up_to_cheat + 2 + (total_steps - step_at_cheat_end) steps_saved = total_steps - resulting_length if steps_saved >= 100: solution += 1 print(solution)",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"grid = [[elem for elem in line.strip()] for line in open('input.txt')] def get_start(grid): for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 'S': return (i, j) def get_end(grid): for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 'E': return (i, j) start = get_start(grid) end = get_end(grid) def get_neighbors(grid, pos): i, j = pos neighbors = [] if i > 0 and grid[i-1][j] != '#': neighbors.append((i-1, j)) if i < len(grid) - 1 and grid[i+1][j] != '#': neighbors.append((i+1, j)) if j > 0 and grid[i][j-1] != '#': neighbors.append((i, j-1)) if j < len(grid[i]) - 1 and grid[i][j+1] != '#': neighbors.append((i, j+1)) return neighbors def get_race_track(grid, start, end): visited = [] queue = [start] while queue: pos = queue.pop(0) visited.append(pos) if pos == end: return visited neighbors = get_neighbors(grid, pos) for neighbor in neighbors: if neighbor not in visited: queue.append(neighbor) return [] def print_path(grid, path): grid_copy = [line.copy() for line in grid] for pos in path[:10]: i, j = pos grid_copy[i][j] = 'X' for line in grid_copy: print(''.join(line)) def print_cheat(grid, first, second): grid_copy = [line.copy() for line in grid] grid_copy[first[0]][first[1]] = '1' grid_copy[second[0]][second[1]] = '2' for line in grid_copy: print(''.join(line)) def get_cheats(path,grid): cheats = {} for i in range(len(path)): for j in range(i,len(path)): if (path[i][0] == path[j][0] and abs(path[i][1]-path[j][1]) == 2 and grid[path[i][0]][(path[i][1]+path[j][1])//2] == '#') or (path[i][1] == path[j][1] and abs(path[i][0]-path[j][0]) == 2 and grid[(path[i][0]+path[j][0])//2][path[i][1]] == '#'): savedTime = j - i - 2 if savedTime not in cheats: cheats[savedTime] = 1 else: cheats[savedTime] += 1 return cheats path = get_race_track(grid, start, end) cheats = get_cheats(path,grid) #rint(cheats) count = 0 for key in cheats: if key >= 100: count += cheats[key] print(count)",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from collections import defaultdict, deque from tqdm import tqdm import copy with open(""./day_20.in"") as fin: grid = [list(line) for line in fin.read().strip().split(""\n"")] N = len(grid) def in_grid(i, j): return 0 <= i < N and 0 <= j < N for i in range(N): for j in range(N): if grid[i][j] == ""S"": si, sj = i, j elif grid[i][j] == ""E"": ei, ej = i, j dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] # Determine OG path path = [(si, sj)] while path[-1] != (ei, ej): i, j = path[-1] for di, dj in dd: ii, jj = i + di, j + dj if not in_grid(ii, jj): continue if len(path) > 1 and (ii, jj) == path[-2]: continue if grid[ii][jj] == ""#"": continue path.append((ii, jj)) break og = len(path) - 1 times = {} for t, coord in enumerate(path): times[coord] = og - t counts = defaultdict(int) saved = {} for t, coord in enumerate(tqdm(path, ncols=80)): i, j = coord for di1, dj1 in dd: for di2, dj2 in dd: ii, jj = i + di1 + di2, j + dj1 + dj2 if not in_grid(ii, jj) or grid[ii][jj] == ""#"": continue rem_t = times[(ii, jj)] saved[(i, j, ii, jj)] = og - (t + rem_t + 2) ans = 0 for v in saved.values(): if v >= 0: counts[v] += 1 if v >= 100: ans += 1 print(ans)",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from collections import Counter def find_shortcuts(map, p): y, x = p for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]: if in_direction(map, p, direction, 1) == '#': shortcut_to = in_direction(map, p, direction, 2) if shortcut_to == '#' or shortcut_to == '.': continue #print(f""Shortcut found from {p} to {shortcut_to}"") yield map[y][x] - shortcut_to - 2 def in_direction(map, f, d, count): y = f[0] x = f[1] for _ in range(count): y += d[0] x += d[1] if 0 > y or y >= len(map) or 0 > x or x >= len(map[0]): return '#' return map[y][x] def step(map, p, steps): y, x = p for r, c in [(y+1,x), (y-1,x), (y,x+1), (y,x-1)]: if map[r][c] == '.': map[r][c] = steps return (r, c) map = [] with open('input') as input: row = 0 for l in input: l = l.strip() map.append(list(l)) if 'S' in l: start = (row, l.find('S')) if 'E' in l: end = (row, l.find('E')) row += 1 print(f""Race from {start} to {end}"") p = start shortcuts = [] steps = 0 map[start[0]][start[1]] = 0 map[end[0]][end[1]] = '.' while p != end: steps += 1 #print(f""Step {steps} from {p}"") shortcuts.extend(find_shortcuts(map, p)) p = step(map, p, steps) # And also shortcuts straight to the end shortcuts.extend(find_shortcuts(map, p)) for l, count in sorted(Counter(shortcuts).items(), key=lambda x: x[0]): print(f""{l}: {count}"") print(sum(1 for s in shortcuts if s >= 100))",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from dataclasses import dataclass from pathlib import Path TEST = False if TEST: text = Path(""20_test.txt"").read_text().strip() else: text = Path(""20.txt"").read_text().strip() grid = [list(l) for l in text.split(""\n"")] width = len(grid[0]) height = len(grid) def get_grid(p): x = p.x y = p.y if x < 0 or x > width: return None if y < 0 or x > height: return None return grid[y][x] @dataclass(frozen=True) class Position: x: int y: int def __add__(self, other): x = self.x + other.x y = self.y + other.y return Position(x=x, y=y) def manhattan_distance(self, other): d_x = self.x - other.x d_y = self.y - other.y return abs(d_x) + abs(d_y) def neighbours(position): directions = [ Position(1, 0), Position(-1, 0), Position(0, 1), Position(0, -1) ] for d in directions: new_position = position + d if get_grid(new_position) == '.': yield new_position # Find the 'S', and the path from the 'S' to the 'E' - we're told there's a unique path. for x in range(len(grid[0])): for y in range(len(grid)): p = Position(x=x, y=y) if get_grid(p) == 'S': start_position = p grid[y][x] = '.' elif get_grid(p) == 'E': end_position = p grid[y][x] = '.' path = {start_position: 0} last_position = start_position while last_position != end_position: next_ = [x for x in neighbours(last_position) if x not in path] assert len(next_) == 1 next_ = next_[0] path[next_] = len(path) last_position = next_ # Part 1: How many jumps of length 2 save at least 100 picoseconds? directions = [ Position(2, 0), Position(-2, 0), Position(0, 2), Position(0, -2) ] count = 0 for point in path: for d in directions: next_point = point + d if next_point in path: time_saved = path[next_point] - path[point] - 2 if time_saved >= 100: count += 1 print(count)",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"from collections import defaultdict with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() start = (-1, -1) end = (-1, -1) walls = set() for row in range(len(input_text)): for col in range(len(input_text[0])): match input_text[row][col]: case ""S"": start = (row, col) case ""E"": end = (row, col) case ""#"": walls.add((row, col)) moves = ((1, 0), (-1, 0), (0, 1), (0, -1)) no_cheat_move_count = {start: 0} current_pos = start move_count = 0 while current_pos != end: for row_move, col_move in moves: new_pos = (current_pos[0] + row_move, current_pos[1] + col_move) if new_pos not in walls and new_pos not in no_cheat_move_count: move_count += 1 current_pos = new_pos no_cheat_move_count[current_pos] = move_count break cheat_moves = [] for delta_row in range(-20, 21): for delta_col in range(-(20 - abs(delta_row)), 21 - abs(delta_row)): cheat_moves.append((delta_row, delta_col)) cheats = defaultdict(int) for (initial_row, initial_col), step in no_cheat_move_count.items(): for row_move, col_move in cheat_moves: cheat_pos = (initial_row + row_move, initial_col + col_move) if no_cheat_move_count.get(cheat_pos, 0) > step + abs(row_move) + abs(col_move): cheats[ no_cheat_move_count[cheat_pos] - step - abs(row_move) - abs(col_move) ] += 1 print(sum(count for saving, count in cheats.items() if saving >= 100))",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"def readfile(test_file): file_name = ""test.txt"" if test_file else ""input.txt"" with open(file_name) as f: maze = [list(line.strip()) for line in f.readlines()] start = (-1, -1) end = (-1, -1) # Create the maze with 1 as blocks and 0 as free for r, row in enumerate(maze): for c, _ in enumerate(row): symbol = maze[r][c] if symbol == ""S"": # Keep track of start start = (r, c) maze[r][c] = 0 elif symbol == ""E"": # Keep track of end end = (r, c) maze[r][c] = 0 elif symbol == ""."": maze[r][c] = 0 else: maze[r][c] = 1 return maze, start, end def part2(maze, start, end): path, costs = cheapest_path(maze, start, end) cheats = [] # Find all possible cheats with max duration of 20 picoseconds by pairwise matching of path for i in range(0, len(path)): for j in range(i, len(path)): start = path[i] end = path[j] diff = abs(end[1] - start[1]) + abs(end[0] - start[0]) if 0 < diff <= 20: cheats.append((start, end, diff)) time_saved = {} # For each cheat keep track of how much time is saved for cheat in cheats: start = cheat[0] end = cheat[1] steps = cheat[2] diff = costs[end] - costs[start] - steps # Ignore cheats saving less than 100 picoseconds if diff < 100: continue elif diff in time_saved: time_saved[diff] += 1 else: time_saved[diff] = 1 print(sum(time_saved.values())) if __name__ == ""__main__"": test_file = False maze, start, end = readfile(test_file) print(""\nAnswer to part 2:"") part2(maze, start, end)",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"with open(""input20.txt"") as i: input = [x.strip() for x in i.readlines()] test_data = """"""############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ###############"""""".split(""\n"") # input = test_data map = """".join(input) w, h = len(input[0]), len(input) start, end = map.index(""S""), map.index(""E"") def print_map(): for r in range(h): print(map[r*w:(r+1)*w]) distances = [None]*w*h working_set = [end] current = 0 while len(working_set)>0: next = [] for i in working_set: if distances[i] is None: distances[i] = current next = [x for x in [i-1, i-w, i+1, i+w] if map[x]!=""#"" and distances[x] is None] working_set = next current += 1 original = distances[start] def get_cheats(cheat_length, limit): count = 0 for i in range(0, w*h): if distances[i] is None: continue for j in range(i+1, w*h): if distances[j] is None: continue x1, y1, x2, y2 = i%w, i//w, j%w, j//w if abs(x1-x2) + abs(y1-y2)<=cheat_length: k = 0 if distances[i] > distances[j]: k = distances[start]-distances[i] + distances[j] + abs(x1-x2) + abs(y1-y2) elif distances[i] < distances[j]: k = distances[start]-distances[j] + distances[i] + abs(x1-x2) + abs(y1-y2) if original-k>=limit: count += 1 return count print(get_cheats(20, 100))",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"from collections import defaultdict import heapq def parse_input(filename): grid = [] with open(filename, 'r') as file: for line in file: line = line.strip() grid.append([char for char in line]) return grid def solve1(grid, minsave): si, sj, ei, ej = 0,0,0,0 N, M = len(grid), len(grid[0]) def inside(i,j): return 0<=i= minsave and grid[ti][tj] == '#': savings[(i,j,ni,nj)] = cost[(ni,nj)] - cost[(i,j)] - 2 count += 1 print(f""Part One - {count}"") # 1518 def solve2(grid, minsave): si, sj, ei, ej = 0,0,0,0 N, M = len(grid), len(grid[0]) def inside(i,j): return 0<=i= minsave: savings[(i,j,ni,nj)] = cost[(ni,nj)] - cost[(i,j)] - step count += 1 print(f""Part Two - {count}"") # 1032257 # grid = parse_input('./inputs/day20toy.txt') # solve1(grid, 0) # solve2(grid, 50) grid = parse_input('./inputs/day20.txt') solve1(grid, 100) solve2(grid, 100)",python 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! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"#!/usr/bin/env python3 from collections import defaultdict, deque myfile = open(""20.txt"", ""r"") lines = myfile.read().strip().splitlines() myfile.close() end = start = (-1, -1) grid = defaultdict(str) for y in range(len(lines)): for x in range(len(lines[y])): if lines[y][x] == ""S"": start = (x, y) elif lines[y][x] == ""E"": end = (x, y) grid[(x, y)] = lines[y][x] part_one = 0 part_two = 0 visited = set() scores = defaultdict(lambda: float(""inf"")) scores[start] = 0 q = deque([start]) while q: pos = q.popleft() visited.add(pos) for dir in [(1, 0), (0, -1), (-1, 0), (0, 1)]: next_pos = (pos[0] + dir[0], pos[1] + dir[1]) if next_pos not in visited and grid[next_pos] != ""#"" and grid[next_pos] != """": scores[next_pos] = scores[pos] + 1 q.append(next_pos) for a in visited: for i in range(-20, 21): for j in range(-20, 21): dist = abs(i) + abs(j) if dist > 20: continue b = (a[0] + i, a[1] + j) if b not in visited: continue savings = scores[b] - scores[a] - dist if savings < 100: continue if dist <= 2: part_one += 1 part_two += 1 print(""Part One:"", part_one) print(""Part Two:"", part_two)",python 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. 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,"const fs = require('fs'); // Read the input file, validate file const data = fs.readFileSync('input.txt', 'utf8'); // Parse the input data const lines = data.trim().split('\n'); let leftList = []; let rightList = []; lines.forEach(line => { const [left, right] = line.split(/\s+/).map(Number); leftList.push(left); rightList.push(right); }); // Sort both lists leftList.sort((a, b) => a - b); rightList.sort((a, b) => a - b); // Calculate the absolute distance let totalDistance = 0; for (let i = 0; i < leftList.length; i++) { totalDistance += Math.abs(leftList[i] - rightList[i]); } 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. 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,"const fs = require(""fs""); let buffer, input, rows; try { buffer = fs.readFileSync(__dirname + ""/input.txt"", ""utf8""); } catch (e) { throw e; } input = buffer.toString(); rows = input.split(""\n""); const left_list = []; const right_list = []; rows.forEach((row) => { if (row === """") { return; } const nums = row.split("" ""); left_list.push(Number(nums[0])); right_list.push(Number(nums[1])); }); left_list.sort(); right_list.sort(); const total_distance = left_list.reduce((accumulator, item, index) => { return accumulator + Math.abs(right_list[index] - item); }, 0); 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. 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,"const fs = require('fs'); const input = fs.readFileSync('./input.txt', 'utf8').trim().split('\n'); const leftList = []; const rightList = []; input.forEach(line => { const [left, right] = line.split(' ').map(Number); leftList.push(left); rightList.push(right); }); // Part 1 function calculateTotalDistance(leftList, rightList) { const sortedLeft = [...leftList].sort((a, b) => a - b); const sortedRight = [...rightList].sort((a, b) => a - b); let totalDistance = 0; for (let i = 0; i < sortedLeft.length; i++) { totalDistance += Math.abs(sortedLeft[i] - sortedRight[i]); } return totalDistance; } // Part 2 function calculateSimilarityScore(leftList, rightList) { const frequencyMap = new Map(); rightList.forEach(num => { frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1); }); let similarityScore = 0; leftList.forEach(num => { const count = frequencyMap.get(num) || 0; similarityScore += num * count; }); return similarityScore; } const totalDistance = calculateTotalDistance(leftList, rightList); console.log('Part 1 - Total Distance:', totalDistance); const similarityScore = calculateSimilarityScore(leftList, rightList); 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. 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?",2378066,"const fs = require('fs'); // Function to calculate total distance between two lists function calculateTotalDistance(leftList, rightList) { // Sort both lists in ascending order leftList.sort((a, b) => a - b); rightList.sort((a, b) => a - b); // Calculate the distances and sum them up let totalDistance = 0; for (let i = 0; i < leftList.length; i++) { totalDistance += Math.abs(leftList[i] - rightList[i]); } return totalDistance; } // Read the input file fs.readFile('input.txt', 'utf-8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } // Split the input into lines and parse the two lists const lines = data.trim().split('\n'); const leftList = []; const rightList = []; lines.forEach(line => { const [left, right] = line.split(/\s+/).map(Number); // Split and convert to numbers leftList.push(left); rightList.push(right); }); // Calculate the total distance const totalDistance = calculateTotalDistance(leftList, rightList); // Output the result console.log('Total Distance:', totalDistance); });",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. 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,"let fs = require('fs'); let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); let firstLocations = []; let secondLocations = []; puzzleInput.forEach((line) => { let parseLine = line.split(' '); if (parseLine[0] != '') firstLocations.push(parseLine[0]); if (parseLine[1] != '') secondLocations.push(parseLine[1]); }); let sortedFirstLocations = firstLocations.sort(); let sortedSecondLocations = secondLocations.sort(); let accumulatedDistance = 0; sortedFirstLocations.forEach((location, index) => { let difference = location - sortedSecondLocations[index]; if (difference < 0) { difference = difference * -1; } accumulatedDistance += difference; }); 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. 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,"const fs = require(""fs""); const path = require(""path""); const fileTxt = fs.readFileSync(path.join(__dirname, ""input.txt"")); const inputFromAdvent = fileTxt.toString(); const parseInput = (input) => { const parsedInput = input .trim() .split(""\n"") .reduce( (acc, item) => { const [first, second] = item.split("" "").filter(Boolean); acc[0].push(Number(first)); acc[1].push(Number(second)); return acc; }, [[], []] ); return parsedInput; }; const orderLists = (input) => { const [first, second] = input; const orderedFirst = first.sort((a, b) => a - b); const orderedSecond = second.sort((a, b) => a - b); return [orderedFirst, orderedSecond]; }; const getDistance = (input) => { const distanceArray = []; const [first, second] = orderLists(input); for (let i = 0; i < first.length; i++) { distanceArray.push(Math.abs(first[i] - second[i])); } return distanceArray; }; const sumDistance = (input) => { return input.reduce((acc, item) => acc + item, 0); }; const getTotalDistance = (input) => { const [arrayA, arrayB] = input .trim() .split(""\n"") .reduce( (acc, line) => { const [a, b] = line.match(/\S+/g).map(Number); acc[0].push(a); acc[1].push(b); return acc; }, [[], []] ); arrayA.sort((a, b) => a - b); arrayB.sort((a, b) => a - b); return arrayA.reduce((total, a, index) => { return total + Math.abs(a - arrayB[index]); }, 0); }; const main1 = () => { console.log(getTotalDistance(inputFromAdvent)); }; const getTotalSimilarity = (input) => { const [arrayA, arrayB] = parseInput(input); return arrayA.reduce((total, arrayAItem) => { return ( total + arrayB.filter((arrayBItem) => arrayBItem === arrayAItem).length * arrayAItem ); }, 0); }; const main2 = () => { console.log(getTotalSimilarity(inputFromAdvent)); }; module.exports = { parseInput, orderLists, getDistance, sumDistance, getTotalDistance, getTotalSimilarity, }; // main1(); 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error('Error reading file:', err); return; } data = data.split(/\s+/); const lists = [[], []]; for (let i = 0; i < data.length; i++) { lists[i % 2].push(Number(data[i])); } console.log(part1(lists)); console.log(part2(lists)); }); const part1 = (lists) => { lists = lists.map(list => list.sort()); return lists[0].reduce((acc, curr, index) => { const diff = Math.abs(lists[1][index] - curr); return acc + diff; }, 0); } const part2 = (lists) => { let similarityScore = 0; lists[0].forEach(num => { similarityScore += (lists[1].filter(item => item === num).length * num); }) return similarityScore; }",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. 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8'); const lines = input.split('\n'); const leftNumbers = []; const rightNumbers = []; let similarityScore = 0; lines.forEach((line) => { const [left, right] = line.trim().split(/\s+/).map(Number); leftNumbers.push(left); rightNumbers.push(right); }); for (let i = 0; i < leftNumbers.length; i++) { let counter = rightNumbers.filter((x) => x == leftNumbers[i]).length; similarityScore += counter * leftNumbers[i]; } 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. 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,"const fs = require(""fs""); let input = fs.readFileSync(""input.txt"", ""utf-8""); input = input.split(/\r?\n/).map((row) => row.split("" "")); const firstCol = input.map((row) => row[0]); const secondCol = input.map((row) => row[1]); const firstSolution = () => { const firstColSorted = firstCol.sort(); const secondColSorted = secondCol.sort(); const distances = firstColSorted.map((firstColValue, index) => Math.abs(firstColValue - secondColSorted[index]) ); return distances.reduce((acc, value) => acc + value, 0); }; console.log(""first part result:"", firstSolution()); const secondSolution = () => { const similarity = firstCol.map( (firstColValue) => firstColValue * secondCol.filter((secondColValue) => secondColValue === firstColValue) .length ); return similarity.reduce((acc, value) => acc + value, 0); }; 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. 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,"let fs = require('fs'); let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); let firstLocations = []; let secondLocations = []; puzzleInput.forEach((line) => { let parseLine = line.split(' '); if (parseLine[0] != '') firstLocations.push(parseLine[0]); if (parseLine[1] != '') secondLocations.push(parseLine[1]); }); let similarityScore = 0; firstLocations.forEach((firstLocation) => { let occurancesInSecond = secondLocations.filter((secondLocation) => secondLocation === firstLocation).length; let locationSimilarityScore = occurancesInSecond > 0 ? firstLocation * occurancesInSecond : 0; similarityScore += locationSimilarityScore; }); 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. 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8'); const pattern = /mul\((\d+),(\d+)\)/g; let sum = 0; let match; while ((match = pattern.exec(input)) !== null) { sum += match[1] * match[2]; } 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. 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,"// PART 1 const fs = require('fs'); const path = require('path'); // Resolve the file path const filePath = path.join(__dirname, 'input.txt'); const filePathTest1 = path.join(__dirname, 'test-1.txt'); const filePathTest2 = path.join(__dirname, 'test-2.txt'); // Read the file function readFile(filePath) { try { const data = fs.readFileSync(filePath, 'utf8'); return data; } catch (err) { console.error('Error reading the file:', err); return null; } } const string = readFile(filePath); const stringTest1 = readFile(filePathTest1); const stringTest2 = readFile(filePathTest2); // Match any group of 1-3 digits, separated by a comma, between ""mul("" and "")"" const regex = /(?<=mul\()(\d{1,3},\d{1,3})(?=\))/g; const arrayOfMatches = (string.match(regex)).map((el) => el.split(',').map(Number)); const arrayMultiplied = arrayOfMatches.map((el => el.reduce((a , b) => a * b))); const arraySummed = arrayMultiplied.reduce((a, b) => a + b); console.log(arraySummed); // PART 2 // Regex to find string between ""don't()"" and ""do()"" const regexPart2 = /don't\(\).*?do\(\)/g; // Create first array of matches let arrayofMarchesPart2 = string.split(regexPart2).filter(Boolean); // Regex to find ""don't()"" without a following ""do()"" const regexRemoveAfterLastDont = /don't\(\)(?!.*do\(\)).*/; // Remove for each array element anything after the last ""don't()"" if no ""do()"" exists arrayofMarchesPart2 = arrayofMarchesPart2.map(element => { if (regexRemoveAfterLastDont.test(element)) { return element.replace(regexRemoveAfterLastDont, ''); } return element; // Return the element unchanged if the condition is not met }); const arrayofMarchesPart2Bis = (arrayofMarchesPart2.map((el => (el.match(regex)).map((el) => el.split(',').map(Number))))).flat(1); const arrayMultipliedPart2 = arrayofMarchesPart2Bis.map((el => el.reduce((a , b) => a * b))); const arraySummedPart2 = arrayMultipliedPart2.reduce((a, b) => a + b); 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. 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,"let fs = require('fs'); let puzzleInput = fs.readFileSync('input.txt').toString(); let mul = (a, b) => a * b; let regexp = /mul\([0-9]{1,3},[0-9]{1,3}\)/g; let multiplications = puzzleInput.match(regexp); let total = 0; multiplications.forEach((thisMul) => { let mulValue = eval(thisMul); total += mulValue; }) 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. 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,"const fs = require(""fs""); let buffer, input, rows; try { buffer = fs.readFileSync(__dirname + ""/input.txt"", ""utf8""); } catch (e) { throw e; } input = buffer.toString(); rows = input.split(""\n""); const multiply_sum = rows.reduce((accumulator, row) => { if (row === """") return accumulator; // Empty row check, skip let sum = 0; let results; // Match mul(x,y) from row as string const regex = /mul\((\d+)\,(\d+)\)/g; while ((results = regex.exec(row)) !== null) { // Match numbers from mul(x,y) sum += Number(results[1]) * Number(results[2]); // console.log(`Found ${results[1]} x ${results[2]} at ${results.index}.`); } return accumulator + sum; }, 0); 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. 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,"const fs = require('fs'); // Read the input file const data = fs.readFileSync('input.txt', 'utf8'); const lines = data.trim().split('\n'); let totalSum = 0; //Constructs regex to match criteria: //mul(number1, number2) where number1 and number2 are 1-3 digit numbers const regex = /mul\((\d{1,3}),(\d{1,3})\)/g; lines.forEach(line => { let match; //regex.exec finds all the matches while ((match = regex.exec(line)) !== null) { //Parses the string to return an integer as a base10 (standard numeric output) const number1 = parseInt(match[1], 10); const number2 = parseInt(match[2], 10); totalSum += number1 * number2; } }); 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. 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,"let fs = require('fs'); let puzzleInput = fs.readFileSync('input.txt').toString(); let mul = (a, b) => a * b; let regEx = /do\(\)|don\'t\(\)|mul\([0-9]{1,3},[0-9]{1,3}\)/g; let parts = puzzleInput.match(regEx); let doing = true; let total = 0; parts.forEach((part) => { if (doing && part.substring(0, 3) == 'mul') { let value = eval(part); total += value; } if (part.substring(0, 3) == 'do(') doing = true; if (part.substring(0, 3) == 'don') doing = false; }); 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. 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,"const fs = require('fs'); // Read the input file const data = fs.readFileSync('input.txt', 'utf8'); const inputString = data.trim(); let totalSum = 0; let mulEnabled = true; const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g; let match; while ((match = instructionRegex.exec(inputString)) !== null) { if (match[1]) { // Matched 'do()' mulEnabled = true; } else if (match[2]) { // Matched ""don't()"" mulEnabled = false; } else if (match[3] && mulEnabled) { // Matched 'mul(X,Y)' and mul is enabled const number1 = parseInt(match[3], 10); const number2 = parseInt(match[4], 10); totalSum += number1 * number2; } } 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. 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,"const fs = require(""fs""); const path = require(""path""); const fileTxt = fs.readFileSync(path.join(__dirname, ""input.txt"")); const inputFromAdvent = fileTxt.toString(); const parseInput = (input) => { // want to take only between () and comma inside after mul. Eg mul(2,4) 2,4 const regex = /mul\((\d+),(\d+)\)/g; const matches = input.match(regex); return matches.map((match) => match.slice(4, -1).split("","").map(Number)); }; const parseAndMultiplyInput = (input) => { return input .split(""do()"") // split into chunks .map((chunk) => chunk.split(""don't()"")[0]) // remove don't() .map((s) => [...s.matchAll(/mul\((\d+),(\d+)\)/g)]) // find all mul pairs .flatMap((m) => m.map((m) => m[1] * m[2])) // multiply pairs .reduce((acc, curr) => acc + curr, 0); // sum up }; const multiplyPairsTotal = (pairs) => { return pairs.reduce((acc, pair) => acc + pair[0] * pair[1], 0); }; const main1 = () => { console.log(multiplyPairsTotal(parseInput(inputFromAdvent))); }; const main2 = () => { console.log(parseAndMultiplyInput(inputFromAdvent)); }; module.exports = { parseInput, multiplyPairsTotal, parseAndMultiplyInput }; // main1(); 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. 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,"const fs = require('fs'); function question2() { fs.readFile('./input.txt', (err, data) => { const memory = data.toString().replace(/\r/g, '').trimEnd(); const regex = /mul\(\d+,\d+\)|do\(\)|don't\(\)/g; const matches = memory.matchAll(regex); const instructions = []; for (const match of matches) { if (match[0].includes('mul')) { instructions.push(match[0].slice(4, -1).split(',')); } else { instructions.push(match[0]); } } let addEnabled = true; const result = instructions.reduce((acc, instr) => { if (typeof instr !== 'string' && addEnabled) { return (acc += instr[0] * instr[1]); } else if (instr === 'do()') { addEnabled = true; return acc; } else if (instr === ""don't()"") { addEnabled = false; return acc; } else { return acc; } }, 0); console.log(result); }); } 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. 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,"const fs = require('fs'); // Function to read and process the input data function readInput(filePath) { try { const data = fs.readFileSync(filePath, 'utf8'); return data.trim(); // Return the input string after trimming any extra whitespace } catch (error) { console.error('Error reading the file:', error); return ''; } } // Function to process the instructions and compute the sum of valid multiplications function calculateTotalSum(inputString) { let totalSum = 0; let mulEnabled = true; const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g; let match; // Iterate through each instruction in the input string while ((match = instructionRegex.exec(inputString)) !== null) { if (match[1]) { mulEnabled = true; // Enable mul if 'do()' is matched } else if (match[2]) { mulEnabled = false; // Disable mul if ""don't()"" is matched } else if (match[3] && mulEnabled) { // If a valid 'mul(X,Y)' is matched and mul is enabled, multiply and add to the total sum const number1 = parseInt(match[3], 10); const number2 = parseInt(match[4], 10); totalSum += number1 * number2; } } return totalSum; } // Main function to execute the program function main() { const inputString = readInput('input.txt'); if (inputString) { const totalSum = calculateTotalSum(inputString); console.log(`Total sum of all multiplied numbers: ${totalSum}`); } } 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! 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,"import fs from ""node:fs""; const a = fs.readFileSync(""./input.txt"", ""utf8"").toString().split(""\n""); const data = a.map((item) => item.split("""")); const values = { horizontalLR: 0, horizontalRL: 0, verticalTB: 0, verticalBT: 0, diagonalTLtoBR: 0, diagonalBRtoTL: 0, diagonalTRtoBL: 0, diagonalBLtoTR: 0, }; data.forEach((item, itemIdx) => { item.forEach((child, childIdx) => { // Horizontal (left to right) if (child === ""X"") { if (data[itemIdx][childIdx + 1] === ""M"") { if (data[itemIdx][childIdx + 2] === ""A"") { if (data[itemIdx][childIdx + 3] === ""S"") values.horizontalLR += 1; } } // Descending Diagonal (center to bottom right) if (data[itemIdx + 1][childIdx + 1] === ""M"") { if (data[itemIdx + 2][childIdx + 2] === ""A"") { if (data[itemIdx + 3][childIdx + 3] === ""S"") values.diagonalTLtoBR += 1; } } // Descending Vertical (center to bottom) if (data[itemIdx + 1][childIdx] === ""M"") { if (data[itemIdx + 2][childIdx] === ""A"") { if (data[itemIdx + 3][childIdx] === ""S"") values.verticalTB += 1; } } // Descending diagonal (center to bottom left) if (childIdx >= 3) { if (data[itemIdx + 1][childIdx - 1] === ""M"") { if (data[itemIdx + 2][childIdx - 2] === ""A"") { if (data[itemIdx + 3][childIdx - 3] === ""S"") values.diagonalTRtoBL += 1; } } } // Horizontal (right to left) if (childIdx >= 3) { if (data[itemIdx][childIdx - 1] === ""M"") { if (data[itemIdx][childIdx - 2] === ""A"") { if (data[itemIdx][childIdx - 3] === ""S"") values.horizontalRL += 1; } } } // ascending diagonal (center to top left) if (itemIdx >= 3 && childIdx >= 3) { if (data[itemIdx - 1][childIdx - 1] === ""M"") { if (data[itemIdx - 2][childIdx - 2] === ""A"") { if (data[itemIdx - 3][childIdx - 3] === ""S"") values.diagonalBRtoTL += 1; } } } // ascending vertical (center to top) if (itemIdx >= 3) { if (data[itemIdx - 1][childIdx] === ""M"") { if (data[itemIdx - 2][childIdx] === ""A"") { if (data[itemIdx - 3][childIdx] === ""S"") values.verticalBT += 1; } } } // ascending diagonal (center to top right) if (itemIdx >= 3) { if (data[itemIdx - 1][childIdx + 1] === ""M"") { if (data[itemIdx - 2][childIdx + 2] === ""A"") { if (data[itemIdx - 3][childIdx + 3] === ""S"") values.diagonalBLtoTR += 1; } } } } }); }); console.log(values); let count = 0; Object.values(values).forEach((item) => { count += item; }); 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! 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,"const fs = require(""fs""); // const puzzleInput = fs.readFileSync(""./sample_input.txt"").toString().split('\n'); const puzzleInput = fs.readFileSync(""./input.txt"").toString().split('\n'); function findWordCount(grid, word) { const rows = grid.length; const cols = grid[0].length; const wordLength = word.length; const reverseWord = word.split('').reverse().join(''); let count = 0; function checkHorizontal(row, col) { if (col <= cols - wordLength) { const horizontalWord = grid[row].slice(col, col + wordLength); if (horizontalWord === word || horizontalWord === reverseWord) { count++; // console.log(`Found ${word} horizontally at row ${row}, starting column ${col}`); } } } function checkVertical(row, col) { if (row <= rows - wordLength) { let verticalWord = ''; for (let i = 0; i < wordLength; i++) { verticalWord += grid[row + i][col]; } if (verticalWord === word || verticalWord === reverseWord) { count++; // console.log(`Found ${word} vertically at column ${col}, starting row ${row}`); } } } function checkDiagonal(row, col) { // Diagonal down-right if (row <= rows - wordLength && col <= cols - wordLength) { let diagonalWord = ''; for (let i = 0; i < wordLength; i++) { diagonalWord += grid[row + i][col + i]; } if (diagonalWord === word || diagonalWord === reverseWord) { count++; // console.log(`Found ${word} diagonally (down-right) starting at row ${row}, column ${col}`); } } // Diagonal down-left if (row <= rows - wordLength && col >= wordLength - 1) { let diagonalWord = ''; for (let i = 0; i < wordLength; i++) { diagonalWord += grid[row + i][col - i]; } if (diagonalWord === word || diagonalWord === reverseWord) { count++; // console.log(`Found ${word} diagonally (down-left) starting at row ${row}, column ${col}`); } } } for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { checkHorizontal(r, c); checkVertical(r, c); checkDiagonal(r, c); } } return count; } const wordCount = findWordCount(puzzleInput, ""XMAS""); 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! 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,"const fs = require('fs'); // Read the input file const data = fs.readFileSync('input.txt', 'utf8'); const lines = data.trim().split('\n'); const grid = lines.map(line => line.trim().split('')); const numRows = grid.length; const numCols = grid[0].length; const word = 'XMAS'; let count = 0; // Directions: N, NE, E, SE, S, SW, W, NW const directions = [ [-1, 0], // N [-1, 1], // NE [ 0, 1], // E [ 1, 1], // SE [ 1, 0], // S [ 1, -1], // SW [ 0, -1], // W [-1, -1] // NW ]; for (let row = 0; row < numRows; row++) { for (let col = 0; col < numCols; col++) { for (let [dx, dy] of directions) { let match = true; for (let k = 0; k < word.length; k++) { const x = row + k * dx; const y = col + k * dy; if (x < 0 || x >= numRows || y < 0 || y >= numCols || grid[x][y] !== word[k]) { match = false; break; } } if (match) { count++; } } } } 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! 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,"import fs from ""fs""; const countXmasOccurrences = (inputFilePath) => { const xmasMatrix = []; try { const text = fs.readFileSync(inputFilePath, ""utf8""); if (!text) return 0; const rows = text.trim().split(""\n""); for (const row of rows) { xmasMatrix.push(row.split("""")); } let xmasCounter = 0; for (let i = 0; i < xmasMatrix.length; i++) { for (let j = 0; j < xmasMatrix[i].length; j++) { const currentChar = xmasMatrix[i][j]; if (xmasMatrix?.[i - 3]?.[j - 3]) { const topLeftDiagonal = currentChar + xmasMatrix[i - 1][j - 1] + xmasMatrix[i - 2][j - 2] + xmasMatrix[i - 3][j - 3]; if (topLeftDiagonal === ""XMAS"") xmasCounter++; } if (xmasMatrix?.[i - 3]?.[j + 3]) { const topRightDiagonal = currentChar + xmasMatrix[i - 1][j + 1] + xmasMatrix[i - 2][j + 2] + xmasMatrix[i - 3][j + 3]; if (topRightDiagonal === ""XMAS"") xmasCounter++; } if (xmasMatrix?.[i + 3]?.[j - 3]) { const botLeftDiagonal = currentChar + xmasMatrix[i + 1][j - 1] + xmasMatrix[i + 2][j - 2] + xmasMatrix[i + 3][j - 3]; if (botLeftDiagonal === ""XMAS"") xmasCounter++; } if (xmasMatrix?.[i + 3]?.[j + 3]) { const botRightDiagonal = currentChar + xmasMatrix[i + 1][j + 1] + xmasMatrix[i + 2][j + 2] + xmasMatrix[i + 3][j + 3]; if (botRightDiagonal === ""XMAS"") xmasCounter++; } if (xmasMatrix[i]?.[j - 3]) { const left = currentChar + xmasMatrix[i][j - 1] + xmasMatrix[i][j - 2] + xmasMatrix[i][j - 3]; if (left === ""XMAS"") xmasCounter++; } if (xmasMatrix[i]?.[j + 3]) { const right = currentChar + xmasMatrix[i][j + 1] + xmasMatrix[i][j + 2] + xmasMatrix[i][j + 3]; if (right === ""XMAS"") xmasCounter++; } if (xmasMatrix?.[i - 3]?.[j]) { const top = currentChar + xmasMatrix[i - 1][j] + xmasMatrix[i - 2][j] + xmasMatrix[i - 3][j]; if (top === ""XMAS"") xmasCounter++; } if (xmasMatrix?.[i + 3]?.[j]) { const bot = currentChar + xmasMatrix[i + 1][j] + xmasMatrix[i + 2][j] + xmasMatrix[i + 3][j]; if (bot === ""XMAS"") xmasCounter++; } } } return xmasCounter; } catch (err) { console.error(err); } }; const totalXmasOccurrences = countXmasOccurrences(""./puzzle-input.txt""); 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! 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,"let fs = require('fs'); let rows = fs.readFileSync('input.txt').toString().split(""\n""); // We need a Width and a Height - we will assume it is a rectangular wordsearch and that all rows are the same length const WIDTH = rows[0].length; const HEIGHT = rows.length; const DIRECTIONS = [ [1, 0], // East [1, 1], // South East [0, 1], // South [-1, 1], // South West [-1, 0], // West [-1, -1], // North West [0, -1], // North [1, -1], // North East ]; const SEARCH = 'XMAS'; // Keep a running total of how many times we have found the Search Word let runningTotal = 0; rows.forEach((row, rowIndex) => { if (row.length > 0) { [...row].forEach((letter, colIndex) => { if (letter === SEARCH[0]) { DIRECTIONS.forEach((direction) => { for (let i = 1; i <= SEARCH.length - 1; i++) { let coordY = rowIndex + (direction[0] * i); let coordX = colIndex + (direction[1] * i); if (coordY < HEIGHT && coordY >= 0 && coordX < WIDTH && coordX >= 0) { if (rows[coordY][coordX] === SEARCH[i]) { if (i === SEARCH.length - 1) { runningTotal++; break; } } else { break; } } } }); } }); } }); 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! 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,"import fs from ""node:fs""; const a = fs.readFileSync(""./input.txt"", ""utf8"").toString().split(""\n""); const data = a.map((item) => item.split("""")); let count = 0; data.forEach((_, vertIdx) => { data[vertIdx].forEach((_, horzIdx) => { if (vertIdx >= 1 && horzIdx >= 1) { if (data[vertIdx][horzIdx] === ""A"") { if ( data[vertIdx - 1][horzIdx - 1] === ""M"" && data[vertIdx - 1][horzIdx + 1] === ""S"" && data[vertIdx + 1][horzIdx - 1] === ""M"" && data[vertIdx + 1][horzIdx + 1] === ""S"" ) { count += 1; } if ( data[vertIdx - 1][horzIdx - 1] === ""S"" && data[vertIdx - 1][horzIdx + 1] === ""S"" && data[vertIdx + 1][horzIdx - 1] === ""M"" && data[vertIdx + 1][horzIdx + 1] === ""M"" ) { count += 1; } if ( data[vertIdx - 1][horzIdx - 1] === ""M"" && data[vertIdx - 1][horzIdx + 1] === ""M"" && data[vertIdx + 1][horzIdx - 1] === ""S"" && data[vertIdx + 1][horzIdx + 1] === ""S"" ) { count += 1; } if ( data[vertIdx - 1][horzIdx - 1] === ""S"" && data[vertIdx - 1][horzIdx + 1] === ""M"" && data[vertIdx + 1][horzIdx - 1] === ""S"" && data[vertIdx + 1][horzIdx + 1] === ""M"" ) { count += 1; } } } }); }); 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! 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,"const fs = require(""fs""); const filename = ""input.txt""; var buffer, input, rows; try { buffer = fs.readFileSync(__dirname + ""/"" + filename, ""utf8""); } catch (e) { throw e; } input = buffer.toString(); rows = input.split(""\n"").map(el => el.split("""")); function find_xmas(letter, i, j) { let total = 0; if (letter !== 'A') return total; // This aint it fam // If the coords exists, check for the letter // M ? S // ? A ? // M ? S if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""M"") { if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""S"") { if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""M"") { if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""S"") { total++; } } } } // M ? M // ? A ? // S ? S if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""M"") { if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""M"") { if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""S"") { if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""S"") { total++; } } } } // S ? S // ? A ? // M ? M if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""S"") { if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""S"") { if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""M"") { if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""M"") { total++; } } } } // S ? M // ? A ? // S ? M if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""S"") { if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""M"") { if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""S"") { if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""M"") { total++; } } } } return total; } let found_xmass = 0; for (let i = 0; i < rows.length; i++) { for (let j = 0; j < rows[i].length; j++) { found_xmass += find_xmas(rows[i][j], i, j); } } 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! 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,"const fs = require('fs'); // Function to read the input file and split it into rows function readInput(filePath) { try { const data = fs.readFileSync(filePath, 'utf-8'); return data.split(""\n"").filter(row => row.length > 0); // Filter out any empty rows } catch (error) { console.error('Error reading the file:', error); return []; } } // Function to check if an ""X-MAS"" pattern is found at a given position in the grid function isXMASPattern(rows, rowIndex, colIndex, WIDTH, HEIGHT) { // Check if we're within bounds and the letter at the center is 'A' if (rowIndex > 0 && rowIndex < HEIGHT - 1 && colIndex > 0 && colIndex < WIDTH - 1 && rows[rowIndex][colIndex] === 'A') { return ( // Check for diagonals forming 'X-MAS' in both directions ( rows[rowIndex + 1][colIndex + 1] === 'M' && rows[rowIndex - 1][colIndex - 1] === 'S' || rows[rowIndex + 1][colIndex + 1] === 'S' && rows[rowIndex - 1][colIndex - 1] === 'M' ) && ( rows[rowIndex + 1][colIndex - 1] === 'M' && rows[rowIndex - 1][colIndex + 1] === 'S' || rows[rowIndex + 1][colIndex - 1] === 'S' && rows[rowIndex - 1][colIndex + 1] === 'M' ) ); } return false; } // Function to count occurrences of the ""X-MAS"" pattern in the grid function countXMASPatterns(rows, WIDTH, HEIGHT) { let runningTotal = 0; // Loop over each row and column to check for ""X-MAS"" patterns rows.forEach((row, rowIndex) => { [...row].forEach((letter, colIndex) => { if (isXMASPattern(rows, rowIndex, colIndex, WIDTH, HEIGHT)) { runningTotal++; } }); }); return runningTotal; } // Main function to orchestrate the entire process function main() { const rows = readInput('input.txt'); if (rows.length === 0) return; const WIDTH = rows[0].length; const HEIGHT = rows.length; // Count the occurrences of ""X-MAS"" patterns const totalPatterns = countXMASPatterns(rows, WIDTH, HEIGHT); // Output the result console.log(totalPatterns); } 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! 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,"let fs = require('fs'); let rows = fs.readFileSync('input.txt').toString().split(""\n""); // We need a Width and a Height - we will assume it is a rectangular wordsearch and that all rows are the same length const WIDTH = rows[0].length; const HEIGHT = rows.length; // Keep a running total of how many times we have found the Search Word let runningTotal = 0; rows.forEach((row, rowIndex) => { if (row.length > 0) { [...row].forEach((letter, colIndex) => { if (letter === 'A') { if ( rowIndex > 0 && rowIndex < HEIGHT - 1 && colIndex > 0 && colIndex < WIDTH - 1 && ( (rows[rowIndex + 1][colIndex + 1] === 'M' && rows[rowIndex - 1][colIndex - 1] === 'S') || (rows[rowIndex + 1][colIndex + 1] === 'S' && rows[rowIndex - 1][colIndex - 1] === 'M') ) && ( (rows[rowIndex + 1][colIndex - 1] === 'M' && rows[rowIndex - 1][colIndex + 1] === 'S') || (rows[rowIndex + 1][colIndex - 1] === 'S' && rows[rowIndex - 1][colIndex + 1] === 'M') ) ) { runningTotal++; } } }); } }); 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! 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,"const fs = require('fs'); // Read the input file and create the grid const data = fs.readFileSync('input.txt', 'utf8'); const lines = data.trim().split('\n'); const grid = lines.map(line => line.trim().split('')); const numRows = grid.length; const numCols = grid[0].length; let count = 0; // Directions for diagonals const dir1 = [-1, -1]; // Top-left to bottom-right const dir2 = [-1, 1]; // Top-right to bottom-left for (let row = 0; row < numRows; row++) { for (let col = 0; col < numCols; col++) { if (grid[row][col] === 'A') { let valid1 = false; let valid2 = false; // Check diagonal from top-left to bottom-right // Check diagonal from top-left to bottom-right if ( row - 1 >= 0 && col - 1 >= 0 && row + 1 < numRows && col + 1 < numCols && ( (grid[row - 1][col - 1] === 'M' && grid[row + 1][col + 1] === 'S') || (grid[row - 1][col - 1] === 'S' && grid[row + 1][col + 1] === 'M') ) ) { valid1 = true; } // Check diagonal from top-right to bottom-left if ( row - 1 >= 0 && col + 1 < numCols && row + 1 < numRows && col - 1 >= 0 && ( (grid[row - 1][col + 1] === 'M' && grid[row + 1][col - 1] === 'S') || (grid[row - 1][col + 1] === 'S' && grid[row + 1][col - 1] === 'M') ) ) { valid2 = true; } // If both diagonals form 'MAS' or 'SAM', increment count if (valid1 && valid2) { count++; } } } } 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. 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,"const fs = require('fs'); // Read the input file const input = fs.readFileSync('input.txt', 'utf8').trim(); const map = input.split('\n'); // Directions: Up, Right, Down, Left const directions = ['^', '>', 'v', '<']; let direction = ''; let position = { x: 0, y: 0 }; // Parse the map to find the initial position and direction of the guard for (let y = 0; y < map.length; y++) { for (let x = 0; x < map[y].length; x++) { if (directions.includes(map[y][x])) { position = { x, y }; direction = map[y][x]; break; } } if (direction) break; } // Directions mapping for movement const movement = { '^': { dx: 0, dy: -1 }, // Up '>': { dx: 1, dy: 0 }, // Right 'v': { dx: 0, dy: 1 }, // Down '<': { dx: -1, dy: 0 }, // Left }; // Set to track the visited positions const visited = new Set(); visited.add(`${position.x},${position.y}`); // Function to turn right const turnRight = (currentDirection) => { const idx = directions.indexOf(currentDirection); return directions[(idx + 1) % 4]; }; let guardRunning = true; while (guardRunning) { // Calculate the next position const nextX = position.x + movement[direction].dx; const nextY = position.y + movement[direction].dy; // Check if the next position is outside the map if ( nextX < 0 || nextX >= map[0].length || nextY < 0 || nextY >= map.length ) { guardRunning = false; // Guard leaves the map } else { // Check if the next position is an obstacle if (map[nextY][nextX] === '#') { // Turn right direction = turnRight(direction); } else { // Move forward position.x = nextX; position.y = nextY; visited.add(`${position.x},${position.y}`); } } } 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error('Error reading file:', err); return; } const rows = data.split(""\n"").map(row => row.split("""")); let guardLocation = rows .map((row, i) => { if (row.includes(""^"")) { // Turn guard icon into a normal traversable space const guardLocation = row.indexOf(""^"") rows[i][guardLocation] = "".""; return { x: i, y: guardLocation } } }) .filter(row => row)[0]; console.log(part1(rows, guardLocation)); console.log(part2(rows, guardLocation)); }); const directions = { ""up"": { dx: -1, dy: 0, next: ""right"" }, ""right"": { dx: 0, dy: 1, next: ""down"" }, ""down"": { dx: 1, dy: 0, next: ""left"" }, ""left"": { dx: 0, dy: -1, next: ""up"" }, }; // Get all places guard visits const getPlacesVisited = (rows, guardLocation) => { let placesVisited = new Set(); let guardDirection = ""up""; let nextGuardLocation; while (nextGuardLocation !== null) { const { x, y } = guardLocation; const { dx, dy} = directions[guardDirection]; let possibleNextCoords = { x: x + dx, y: y + dy }; // Check if in bounds if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1|| possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) { placesVisited.add(`${x}, ${y}`); nextGuardLocation = null; break; } if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ""."") { guardDirection = directions[guardDirection].next; } else { guardLocation = possibleNextCoords; nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y]; placesVisited.add(`${x}, ${y}`); } } return placesVisited; } const checkInfiniteLoop = (rows, guardLocation) => { const placesVisited = new Set(); let guardDirection = ""up""; let nextGuardLocation; while (true) { const { x, y } = guardLocation; const { dx, dy} = directions[guardDirection]; let possibleNextCoords = { x: x + dx, y: y + dy }; // Check if guard has been here before, and in the same direction, indicating an infinite loop const currentPosition = `${x}, ${y}, ${guardDirection}` if (placesVisited.has(currentPosition)) { return true; } placesVisited.add(currentPosition); // Check if in bounds if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1|| possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) { return false; } if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ""."") { guardDirection = directions[guardDirection].next; } else { guardLocation = possibleNextCoords; nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y]; } } } const part1 = (rows, guardLocation) => getPlacesVisited(rows, guardLocation).size; const part2 = (rows, guardLocation) => { // All the places the guard would normally visit (minus starting location) const placesVisited = [...getPlacesVisited(rows, guardLocation)].slice(1); let infiniteLoops = 0; for (let i = 0; i < placesVisited.length; i++) { const [ obstacleX, obstacleY ] = placesVisited[i].split("", "").map(Number); // Temporarily change normal tile to obstacle rows[obstacleX][obstacleY] = ""#""; if (checkInfiniteLoop(rows, guardLocation)) infiniteLoops++; // Return obstacle to normal tile rows[obstacleX][obstacleY] = "".""; } return infiniteLoops; }",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. 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,"const fs = require('fs'); // Directions: Up, Right, Down, Left const DIRECTIONS = ['^', '>', 'v', '<']; // Movement offsets for each direction const MOVEMENT = { '^': { dx: 0, dy: -1 }, // Up '>': { dx: 1, dy: 0 }, // Right 'v': { dx: 0, dy: 1 }, // Down '<': { dx: -1, dy: 0 }, // Left }; // Function to find the guard's starting position and direction const findGuard = (map) => { for (let y = 0; y < map.length; y++) { for (let x = 0; x < map[y].length; x++) { if (DIRECTIONS.includes(map[y][x])) { return { x, y, direction: map[y][x] }; } } } throw new Error('Guard not found on the map!'); }; // Function to turn the guard 90 degrees to the right const turnRight = (direction) => { const currentIndex = DIRECTIONS.indexOf(direction); return DIRECTIONS[(currentIndex + 1) % 4]; }; // Function to get the next position based on the current position and direction const getNextPosition = (x, y, direction) => { const { dx, dy } = MOVEMENT[direction]; return { x: x + dx, y: y + dy }; }; // Function to check if a position is within the map boundaries const isWithinBounds = (x, y, map) => { return x >= 0 && x < map[0].length && y >= 0 && y < map.length; }; // Function to check if a position is an obstacle const isObstacle = (x, y, map) => { return map[y][x] === '#'; }; // Function to simulate the guard's movement const simulateGuardMovement = (map) => { const { x, y, direction } = findGuard(map); let currentDirection = direction; let currentPosition = { x, y }; const visited = new Set(); visited.add(`${currentPosition.x},${currentPosition.y}`); while (true) { const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); // Check if the guard is leaving the map if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { break; } // Check if the next position is an obstacle if (isObstacle(nextPosition.x, nextPosition.y, map)) { currentDirection = turnRight(currentDirection); // Turn right } else { currentPosition = nextPosition; // Move forward visited.add(`${currentPosition.x},${currentPosition.y}`); } } return visited.size; }; // Read the input file const input = fs.readFileSync('input.txt', 'utf8').trim(); 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}`);",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. 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,"const fs = require('fs'); // Class to represent the Guard class Guard { constructor(x, y, direction) { this.x = x; this.y = y; this.direction = direction; this.directions = ['^', '>', 'v', '<']; // Up, Right, Down, Left this.movement = { '^': { dx: 0, dy: -1 }, // Up '>': { dx: 1, dy: 0 }, // Right 'v': { dx: 0, dy: 1 }, // Down '<': { dx: -1, dy: 0 }, // Left }; } // Turn the guard 90 degrees to the right turnRight() { const currentIndex = this.directions.indexOf(this.direction); this.direction = this.directions[(currentIndex + 1) % 4]; } // Move the guard forward in the current direction moveForward() { const { dx, dy } = this.movement[this.direction]; this.x += dx; this.y += dy; } // Get the next position without actually moving getNextPosition() { const { dx, dy } = this.movement[this.direction]; return { x: this.x + dx, y: this.y + dy }; } } // Class to represent the Map class Map { constructor(grid) { this.grid = grid; this.width = grid[0].length; this.height = grid.length; } // Check if a position is within the map boundaries isWithinBounds(x, y) { return x >= 0 && x < this.width && y >= 0 && y < this.height; } // Check if a position is an obstacle isObstacle(x, y) { return this.grid[y][x] === '#'; } // Find the guard's starting position and direction findGuard() { for (let y = 0; y < this.height; y++) { for (let x = 0; x < this.width; x++) { if ('^>v<'.includes(this.grid[y][x])) { return { x, y, direction: this.grid[y][x] }; } } } throw new Error('Guard not found on the map!'); } } // Main function to simulate the guard's movement function simulateGuardMovement(map) { const guardMap = new Map(map); const { x, y, direction } = guardMap.findGuard(); const guard = new Guard(x, y, direction); const visited = new Set(); visited.add(`${guard.x},${guard.y}`); while (true) { const nextPosition = guard.getNextPosition(); // Check if the guard is leaving the map if (!guardMap.isWithinBounds(nextPosition.x, nextPosition.y)) { break; } // Check if the next position is an obstacle if (guardMap.isObstacle(nextPosition.x, nextPosition.y)) { guard.turnRight(); // Turn right if there's an obstacle } else { guard.moveForward(); // Move forward visited.add(`${guard.x},${guard.y}`); } } return visited.size; } // Read the input file const input = fs.readFileSync('input.txt', 'utf8').trim(); 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}`);",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. 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,"const fs = require('fs'); // Read the input file const input = fs.readFileSync('input.txt', 'utf8'); // Parse the grid into a 2D array let grid = input.split('\n').map(line => line.split('')); const numRows = grid.length; const numCols = grid[0].length; // Define directions and their corresponding movements const directions = ['up', 'right', 'down', 'left']; const moves = { 'up': [-1, 0], 'right': [0, 1], 'down': [1, 0], 'left': [0, -1] }; // Map symbols to directions const dirSymbols = { '^': 'up', '>': 'right', 'v': 'down', '<': 'left' }; // Find the starting position and direction of the guard let posRow, posCol, dir; outerLoop: for (let i = 0; i < numRows; i++) { for (let j = 0; j < numCols; j++) { let cell = grid[i][j]; if (cell in dirSymbols) { posRow = i; posCol = j; dir = dirSymbols[cell]; grid[i][j] = '.'; // Replace the starting symbol with empty space break outerLoop; } } } // Set to keep track of visited positions let visited = new Set(); visited.add(`${posRow},${posCol}`); while (true) { // Compute the next position let [dRow, dCol] = moves[dir]; let newRow = posRow + dRow; let newCol = posCol + dCol; // Check if the guard is about to leave the grid if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) { break; } let cellAhead = grid[newRow][newCol]; if (cellAhead === '#') { // Turn right 90 degrees let dirIndex = directions.indexOf(dir); dirIndex = (dirIndex + 1) % 4; dir = directions[dirIndex]; } else { // Move forward posRow = newRow; posCol = newCol; visited.add(`${posRow},${posCol}`); } } // Output the number of distinct positions visited 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. 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,"const fs = require('fs'); // Directions: Up, Right, Down, Left const DIRECTIONS = ['^', '>', 'v', '<']; // Movement offsets for each direction const MOVEMENT = { '^': { dx: 0, dy: -1 }, // Up '>': { dx: 1, dy: 0 }, // Right 'v': { dx: 0, dy: 1 }, // Down '<': { dx: -1, dy: 0 }, // Left }; // Function to find the guard's starting position and direction const findGuard = (map) => { for (let y = 0; y < map.length; y++) { for (let x = 0; x < map[y].length; x++) { if (DIRECTIONS.includes(map[y][x])) { return { x, y, direction: map[y][x] }; } } } throw new Error('Guard not found on the map!'); }; // Function to turn the guard 90 degrees to the right const turnRight = (direction) => { const currentIndex = DIRECTIONS.indexOf(direction); return DIRECTIONS[(currentIndex + 1) % 4]; }; // Function to get the next position based on the current position and direction const getNextPosition = (x, y, direction) => { const { dx, dy } = MOVEMENT[direction]; return { x: x + dx, y: y + dy }; }; // Function to check if a position is within the map boundaries const isWithinBounds = (x, y, map) => { return x >= 0 && x < map[0].length && y >= 0 && y < map.length; }; // Function to check if a position is an obstacle const isObstacle = (x, y, map) => { return map[y][x] === '#'; }; // Function to simulate the guard's movement and check for loops const simulateGuardMovement = (map, startX, startY, startDirection) => { let currentDirection = startDirection; let currentPosition = { x: startX, y: startY }; const visited = new Set(); visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`); while (true) { const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); // Check if the guard is leaving the map if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { return false; // No loop, guard leaves the map } // Check if the next position is an obstacle if (isObstacle(nextPosition.x, nextPosition.y, map)) { currentDirection = turnRight(currentDirection); // Turn right } else { currentPosition = nextPosition; // Move forward const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`; // Check if the guard has been here before with the same direction if (visited.has(key)) { return true; // Loop detected } visited.add(key); } } }; // Function to count valid obstruction positions const countValidObstructionPositions = (map) => { const { x: startX, y: startY, direction: startDirection } = findGuard(map); let validPositions = 0; for (let y = 0; y < map.length; y++) { for (let x = 0; x < map[y].length; x++) { // Skip the guard's starting position and non-empty positions if ((x === startX && y === startY) || map[y][x] !== '.') { continue; } // Create a copy of the map with the new obstruction const newMap = map.map((row) => row.split('')); newMap[y][x] = '#'; const newMapString = newMap.map((row) => row.join('')); // Simulate the guard's movement and check for loops if (simulateGuardMovement(newMapString, startX, startY, startDirection)) { validPositions++; } } } return validPositions; }; // Read the input file const input = fs.readFileSync('input.txt', 'utf8').trim(); 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}`);",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. 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,"const fs = require('fs'); // Constants for directions and movement offsets const DIRECTIONS = ['^', '>', 'v', '<']; const MOVEMENT = { '^': { dx: 0, dy: -1 }, '>': { dx: 1, dy: 0 }, 'v': { dx: 0, dy: 1 }, '<': { dx: -1, dy: 0 }, }; // Class representing the Guard class Guard { constructor(map) { this.map = map; const { x, y, direction } = this.findGuard(); this.position = { x, y }; this.direction = direction; } // Find the guard's initial position and direction findGuard() { for (let y = 0; y < this.map.length; y++) { for (let x = 0; x < this.map[y].length; x++) { if (DIRECTIONS.includes(this.map[y][x])) { return { x, y, direction: this.map[y][x] }; } } } throw new Error('Guard not found on the map!'); } // Turn the guard 90 degrees to the right turnRight() { const index = DIRECTIONS.indexOf(this.direction); this.direction = DIRECTIONS[(index + 1) % 4]; } // Get the next position based on the current position and direction getNextPosition() { const { dx, dy } = MOVEMENT[this.direction]; return { x: this.position.x + dx, y: this.position.y + dy }; } // Check if a position is within the map boundaries isWithinBounds(x, y) { return x >= 0 && x < this.map[0].length && y >= 0 && y < this.map.length; } // Check if a position is an obstacle isObstacle(x, y) { return this.map[y][x] === '#'; } // Simulate the guard's movement simulateMovement() { const visited = new Set(); visited.add(`${this.position.x},${this.position.y},${this.direction}`); while (true) { const nextPosition = this.getNextPosition(); // Check if the guard is leaving the map if (!this.isWithinBounds(nextPosition.x, nextPosition.y)) { return false; // Guard exits the map } // Check if the next position is an obstacle if (this.isObstacle(nextPosition.x, nextPosition.y)) { this.turnRight(); // Turn right if there's an obstacle } else { this.position = nextPosition; // Move forward const key = `${this.position.x},${this.position.y},${this.direction}`; // Check if the guard has been here before if (visited.has(key)) { return true; // Loop detected } visited.add(key); } } } } // Class to solve the problem class Solution { constructor(filePath) { this.map = this.readInput(filePath); this.guard = new Guard(this.map); } // Read the input file and parse the map readInput(filePath) { return fs.readFileSync(filePath, 'utf8').trim().split('\n'); } // Count valid obstruction positions countValidObstructionPositions() { const { x: startX, y: startY } = this.guard.position; let validPositions = 0; for (let y = 0; y < this.map.length; y++) { for (let x = 0; x < this.map[y].length; x++) { // Skip the guard's starting position and non-empty positions if ((x === startX && y === startY) || this.map[y][x] !== '.') { continue; } // Create a copy of the map with the new obstruction const newMap = this.map.map((row) => row.split('')); newMap[y][x] = '#'; const newMapString = newMap.map((row) => row.join('')); // Simulate the guard's movement and check for loops const guardWithNewMap = new Guard(newMapString); if (guardWithNewMap.simulateMovement()) { validPositions++; } } } return validPositions; } // Main method to solve the problem solve() { const validPositions = this.countValidObstructionPositions(); console.log(`Number of valid obstruction positions: ${validPositions}`); } } // Instantiate the solution class and solve the problem const solution = new Solution('input.txt'); 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. 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,"const fs = require('fs'); const {log} = require('console'); let lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); function findPosition() { for (let i = 0; i < lines.length; i++) { for (let j = 0; j < lines[0].length; j++) { if (lines[i][j] === '^') { return [j, i]; } } } } let [columnStart, rowStart] = findPosition(); let [columnCurrent, rowCurrent] = [columnStart, rowStart]; let [columnDirection, rowDirection] = [0, -1]; let visited = new Set(); const key = (c, r) => `${c},${r}`; visited.add(key(columnStart, rowStart)); while (true) { let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection]; if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) { break; } if (lines[rowNext][columnNext] === '#') { // turn right [columnDirection, rowDirection] = [-rowDirection, columnDirection]; } else { visited.add(key(columnNext, rowNext)); [columnCurrent, rowCurrent] = [columnNext, rowNext]; } } log(visited.size); function isEndless(columnStart, rowStart, columnDirection, rowDirection, grid) { let [columnCurrent, rowCurrent] = [columnStart, rowStart]; let visited = {}; visited[key(columnStart, rowStart)] = [[columnDirection, rowDirection]]; while (true) { let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection]; if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) { return false; } if (grid[rowNext][columnNext] === '#') { // turn right [columnDirection, rowDirection] = [-rowDirection, columnDirection]; } else { let k = key(columnNext, rowNext); let dk = key(columnDirection, rowDirection); if (visited[k]) { if (visited[k].includes(dk)) { // loop confirmed return true; } visited[k].push(dk); } else { visited[k] = [dk]; } [columnCurrent, rowCurrent] = [columnNext, rowNext]; } } } // part 2 let blocks = new Set(); // change every visited coordinate (except start) to # and check if it results in a loop. for (let k of visited) { const [c, r] = k.split(',').map(x => parseInt(x)) if (!(c === columnStart && r === rowStart)) { // clone grid with added # on next direction and check isEndless const copy = JSON.parse(JSON.stringify(lines)); copy[r] = copy[r].slice(0, c) + '#' + copy[r].slice(c + 1); if (isEndless(columnStart, rowStart, -1, 0, copy)) { blocks.add(key(c, r)); } } } 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. 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,"const fs = require('fs'); // Read the input file const input = fs.readFileSync('input.txt', 'utf8'); // Parse the grid into a 2D array let originalGrid = input.split('\n').map(line => line.split('')); const numRows = originalGrid.length; const numCols = originalGrid[0].length; // Define directions and their corresponding movements const directions = ['up', 'right', 'down', 'left']; const moves = { 'up': [-1, 0], 'right': [0, 1], 'down': [1, 0], 'left': [0, -1] }; // Map symbols to directions const dirSymbols = { '^': 'up', '>': 'right', 'v': 'down', '<': 'left' }; // Find the starting position and direction of the guard let startRow, startCol, startDir; outerLoop: for (let i = 0; i < numRows; i++) { for (let j = 0; j < numCols; j++) { let cell = originalGrid[i][j]; if (cell in dirSymbols) { startRow = i; startCol = j; startDir = dirSymbols[cell]; break outerLoop; } } } // Function to simulate the guard's movement function simulate(grid) { let posRow = startRow; let posCol = startCol; let dir = startDir; // Visited positions with direction let visitedStates = new Set(); visitedStates.add(`${posRow},${posCol},${dir}`); while (true) { let [dRow, dCol] = moves[dir]; let newRow = posRow + dRow; let newCol = posCol + dCol; // Check if the guard is about to leave the grid if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) { return false; // Guard leaves the grid } let cellAhead = grid[newRow][newCol]; if (cellAhead === '#') { // Turn right 90 degrees let dirIndex = directions.indexOf(dir); dirIndex = (dirIndex + 1) % 4; dir = directions[dirIndex]; } else { // Move forward posRow = newRow; posCol = newCol; } let state = `${posRow},${posCol},${dir}`; if (visitedStates.has(state)) { return true; // Guard is in a loop } visitedStates.add(state); } } // Count the number of positions where adding an obstruction causes the guard to loop let count = 0; for (let i = 0; i < numRows; i++) { for (let j = 0; j < numCols; j++) { // Skip if cell is not empty or is the starting position if (originalGrid[i][j] !== '.' || (i === startRow && j === startCol)) { continue; } // Create a copy of the grid let grid = originalGrid.map(row => row.slice()); // Place an obstruction at (i, j) grid[i][j] = '#'; // Simulate the guard's movement if (simulate(grid)) { count++; } } } // Output the total count 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. 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,"const fs = require('fs'); // Constants for directions and movement offsets const DIRECTIONS = ['^', '>', 'v', '<']; const MOVEMENT = { '^': { dx: 0, dy: -1 }, // Up '>': { dx: 1, dy: 0 }, // Right 'v': { dx: 0, dy: 1 }, // Down '<': { dx: -1, dy: 0 }, // Left }; // Read the input file and parse the map const readInput = (filePath) => { return fs.readFileSync(filePath, 'utf8').trim().split('\n'); }; // Find the guard's starting position and direction const findGuard = (map) => { for (let y = 0; y < map.length; y++) { for (let x = 0; x < map[y].length; x++) { if (DIRECTIONS.includes(map[y][x])) { return { x, y, direction: map[y][x] }; } } } throw new Error('Guard not found on the map!'); }; // Turn the guard 90 degrees to the right const turnRight = (direction) => { const currentIndex = DIRECTIONS.indexOf(direction); return DIRECTIONS[(currentIndex + 1) % 4]; }; // Get the next position based on the current position and direction const getNextPosition = (x, y, direction) => { const { dx, dy } = MOVEMENT[direction]; return { x: x + dx, y: y + dy }; }; // Check if a position is within the map boundaries const isWithinBounds = (x, y, map) => { return x >= 0 && x < map[0].length && y >= 0 && y < map.length; }; // Check if a position is an obstacle const isObstacle = (x, y, map) => { return map[y][x] === '#'; }; // Simulate the guard's movement and check for loops const simulateGuardMovement = (map, startX, startY, startDirection) => { let currentDirection = startDirection; let currentPosition = { x: startX, y: startY }; const visited = new Set(); visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`); while (true) { const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); // Check if the guard is leaving the map if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { return false; // No loop, guard leaves the map } // Check if the next position is an obstacle if (isObstacle(nextPosition.x, nextPosition.y, map)) { currentDirection = turnRight(currentDirection); // Turn right } else { currentPosition = nextPosition; // Move forward const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`; // Check if the guard has been here before with the same direction if (visited.has(key)) { return true; // Loop detected } visited.add(key); } } }; // Count valid obstruction positions const countValidObstructionPositions = (map) => { const { x: startX, y: startY, direction: startDirection } = findGuard(map); let validPositions = 0; for (let y = 0; y < map.length; y++) { for (let x = 0; x < map[y].length; x++) { // Skip the guard's starting position and non-empty positions if ((x === startX && y === startY) || map[y][x] !== '.') { continue; } // Create a copy of the map with the new obstruction const newMap = map.map((row) => row.split('')); newMap[y][x] = '#'; const newMapString = newMap.map((row) => row.join('')); // Simulate the guard's movement and check for loops if (simulateGuardMovement(newMapString, startX, startY, startDirection)) { validPositions++; } } } return validPositions; }; // Main function to solve the problem const solve = (filePath) => { const map = readInput(filePath); const validPositions = countValidObstructionPositions(map); console.log(`Number of valid obstruction positions: ${validPositions}`); }; // Run the solution 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. 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8').trim(); const lines = input.split('\n'); const height = lines.length; const width = lines[0].length; const antennas = {}; // Collect antennas by frequency for (let y = 0; y < height; y++) { const line = lines[y]; for (let x = 0; x < width; x++) { const char = line[x]; if (/[a-zA-Z0-9]/.test(char)) { if (!antennas[char]) antennas[char] = []; antennas[char].push({ x, y }); } } } const antinodes = new Set(); for (const freq in antennas) { const positions = antennas[freq]; const n = positions.length; for (let i = 0; i < n; i++) { const A = positions[i]; for (let j = i + 1; j < n; j++) { const B = positions[j]; const dx = A.x - B.x; const dy = A.y - B.y; const D = { x: dx, y: dy }; // Antinodes occur at positions where one antenna is twice as far as the other const tValues = [-1, 2]; for (const t of tValues) { const Px = B.x + t * D.x; const Py = B.y + t * D.y; if ( Number.isInteger(Px) && Number.isInteger(Py) && Px >= 0 && Px < width && Py >= 0 && Py < height ) { const key = `${Px},${Py}`; antinodes.add(key); } } } } } 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. 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,"const fs = require('fs'); // Read and parse the input file const input = fs.readFileSync('input.txt', 'utf8').trim(); const mapLines = input.split('\n'); const mapHeight = mapLines.length; const mapWidth = mapLines[0].length; // Function to locate antennas by frequency in the map function extractAntennas(mapLines) { const antennas = {}; mapLines.forEach((line, y) => { Array.from(line).forEach((char, x) => { if (/[a-zA-Z0-9]/.test(char)) { if (!antennas[char]) { antennas[char] = []; } antennas[char].push({ x, y }); } }); }); return antennas; } // Function to calculate all antinode positions function findAntinodePositions(antennas, mapWidth, mapHeight) { const antinodes = new Set(); Object.entries(antennas).forEach(([freq, positions]) => { for (let i = 0; i < positions.length; i++) { const firstPos = positions[i]; for (let j = i + 1; j < positions.length; j++) { const secondPos = positions[j]; // Calculate the difference between the two positions const dx = firstPos.x - secondPos.x; const dy = firstPos.y - secondPos.y; // Check for potential antinodes [-1, 2].forEach(t => { const Px = secondPos.x + t * dx; const Py = secondPos.y + t * dy; // Check if the calculated position is within bounds if (Px >= 0 && Px < mapWidth && Py >= 0 && Py < mapHeight && Number.isInteger(Px) && Number.isInteger(Py)) { antinodes.add(`${Px},${Py}`); } }); } } }); return antinodes; } // Main execution function function main() { const antennas = extractAntennas(mapLines); const antinodes = findAntinodePositions(antennas, mapWidth, mapHeight); console.log(antinodes.size); } main();",javascript 287,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,"const fs = require('fs'); // Read input file and split into lines const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); // Parse the map into a grid of characters const grid = input.map(line => line.split('')); // Function to calculate the greatest common divisor (GCD) of two numbers const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); // Function to calculate all unique antinode positions const calculateAntinodes = (grid) => { const antinodes = new Set(); const rows = grid.length; const cols = grid[0].length; // Iterate over all pairs of antennas for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { const frequency1 = grid[i][j]; if (frequency1 === '.') continue; // Skip empty spaces for (let k = 0; k < rows; k++) { for (let l = 0; l < cols; l++) { const frequency2 = grid[k][l]; if (frequency2 !== frequency1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies // Calculate the differences in positions const dx = k - i; const dy = l - j; // Calculate the GCD to simplify the direction vector const divisor = gcd(Math.abs(dx), Math.abs(dy)); const stepX = dx / divisor; const stepY = dy / divisor; // Calculate the two antinode positions const antinode1X = i - stepX; const antinode1Y = j - stepY; const antinode2X = k + stepX; const antinode2Y = l + stepY; // Check if the antinodes are within the grid bounds if (antinode1X >= 0 && antinode1X < rows && antinode1Y >= 0 && antinode1Y < cols) { antinodes.add(`${antinode1X},${antinode1Y}`); } if (antinode2X >= 0 && antinode2X < rows && antinode2Y >= 0 && antinode2Y < cols) { antinodes.add(`${antinode2X},${antinode2Y}`); } } } } } return antinodes.size; }; // Calculate and print the number of unique antinode locations 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. 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,"const fs = require('fs'); // Utility function to read and split input into lines function getInput(filePath) { return fs.readFileSync(filePath, 'utf8').trim().split('\n'); } // Utility function to find antennas by frequency function findAntennas(lines) { const antennas = {}; lines.forEach((line, y) => { Array.from(line).forEach((char, x) => { if (/[a-zA-Z0-9]/.test(char)) { antennas[char] = antennas[char] || []; antennas[char].push({ x, y }); } }); }); return antennas; } // Function to calculate antinodes from antenna pairs function calculateAntinodes(antennas, width, height) { const antinodes = new Set(); Object.keys(antennas).forEach((freq) => { const positions = antennas[freq]; const n = positions.length; for (let i = 0; i < n; i++) { const A = positions[i]; for (let j = i + 1; j < n; j++) { const B = positions[j]; const dx = A.x - B.x; const dy = A.y - B.y; // Check antinode conditions for both t = -1 and t = 2 [-1, 2].forEach((t) => { const Px = B.x + t * dx; const Py = B.y + t * dy; // Ensure that Px and Py are within bounds and valid positions if (Number.isInteger(Px) && Number.isInteger(Py) && Px >= 0 && Px < width && Py >= 0 && Py < height) { const key = `${Px},${Py}`; antinodes.add(key); } }); } } }); return antinodes; } // Main function to execute the solution function solve(filePath) { const lines = getInput(filePath); const height = lines.length; const width = lines[0].length; const antennas = findAntennas(lines); const antinodes = calculateAntinodes(antennas, width, height); console.log(antinodes.size); } // Run the solution 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. 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,"const fs = require('fs'); // Read and parse the input file into a grid const grid = fs.readFileSync('input.txt', 'utf8') .trim() .split('\n') .map(line => line.split('')); // Helper function to compute the greatest common divisor (GCD) const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b); // Function to find all unique antinode positions const findAntinodes = (grid) => { const rows = grid.length; const cols = grid[0].length; const antinodeSet = new Set(); // Iterate through all pairs of antennas for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { const freq1 = grid[i][j]; if (freq1 === '.') continue; // Skip empty spaces for (let k = 0; k < rows; k++) { for (let l = 0; l < cols; l++) { const freq2 = grid[k][l]; if (freq2 !== freq1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies // Calculate the direction vector between the two antennas const deltaX = k - i; const deltaY = l - j; const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY)); const stepX = deltaX / gcd; const stepY = deltaY / gcd; // Calculate the two antinode positions const antinode1 = { x: i - stepX, y: j - stepY }; const antinode2 = { x: k + stepX, y: l + stepY }; // Check if the antinodes are within the grid bounds if (antinode1.x >= 0 && antinode1.x < rows && antinode1.y >= 0 && antinode1.y < cols) { antinodeSet.add(`${antinode1.x},${antinode1.y}`); } if (antinode2.x >= 0 && antinode2.x < rows && antinode2.y >= 0 && antinode2.y < cols) { antinodeSet.add(`${antinode2.x},${antinode2.y}`); } } } } } return antinodeSet.size; }; // Main function to calculate and log the result const main = () => { const antinodeCount = findAntinodes(grid); console.log(antinodeCount); }; // Execute the main function main();",javascript 290,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,"const fs = require('fs'); const grid = fs.readFileSync('input.txt', 'utf8').trim().split('\n').map(line => line.split('')); const rows = grid.length; const cols = grid[0].length; const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b); const findAntinodes = (grid) => { const antinodeSet = new Set(); for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { const freq1 = grid[i][j]; if (freq1 === '.') continue; for (let k = 0; k < rows; k++) { for (let l = 0; l < cols; l++) { const freq2 = grid[k][l]; if (freq2 !== freq1 || (i === k && j === l)) continue; const deltaX = k - i; const deltaY = l - j; const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY)); const stepX = deltaX / gcd; const stepY = deltaY / gcd; let x = i + stepX; let y = j + stepY; while (x >= 0 && x < rows && y >= 0 && y < cols) { antinodeSet.add(`${x},${y}`); x += stepX; y += stepY; } x = i - stepX; y = j - stepY; while (x >= 0 && x < rows && y >= 0 && y < cols) { antinodeSet.add(`${x},${y}`); x -= stepX; y -= stepY; } } } } } return antinodeSet.size; }; 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. 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,"const fs = require('fs'); // Load the grid from the input file const loadGrid = (filePath) => { return fs.readFileSync(filePath, 'utf8') .trim() .split('\n') .map(row => row.split('')); }; // Calculate the greatest common divisor (GCD) of two numbers const gcd = (a, b) => { while (b !== 0) [a, b] = [b, a % b]; return a; }; // Find all unique antinode positions in the grid const findAntinodes = (grid) => { const rows = grid.length; const cols = grid[0].length; const antinodes = new Set(); // Iterate through all pairs of antennas for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { const freq = grid[i][j]; if (freq === '.') continue; // Skip empty spaces for (let k = 0; k < rows; k++) { for (let l = 0; l < cols; l++) { if (grid[k][l] !== freq || (i === k && j === l)) continue; // Skip same antenna or different frequencies // Calculate the direction vector const dx = k - i; const dy = l - j; const divisor = gcd(Math.abs(dx), Math.abs(dy)); const stepX = dx / divisor; const stepY = dy / divisor; // Traverse in the direction of the vector let x = i + stepX; let y = j + stepY; while (x >= 0 && x < rows && y >= 0 && y < cols) { antinodes.add(`${x},${y}`); x += stepX; y += stepY; } // Traverse in the opposite direction x = i - stepX; y = j - stepY; while (x >= 0 && x < rows && y >= 0 && y < cols) { antinodes.add(`${x},${y}`); x -= stepX; y -= stepY; } } } } } return antinodes.size; }; // Main function to execute the solution const main = () => { const grid = loadGrid('input.txt'); const result = findAntinodes(grid); console.log(result); }; // Run the program main();",javascript 292,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,"const fs = require('fs'); // Helper function to compute the greatest common divisor (GCD) of two numbers const computeGCD = (a, b) => { while (b !== 0) { [a, b] = [b, a % b]; } return Math.abs(a); }; // Function to extract antennas from the input grid and organize them by frequency const parseAntennas = (grid) => { const antennas = {}; grid.forEach((line, y) => { [...line].forEach((char, x) => { if (/[a-zA-Z0-9]/.test(char)) { if (!antennas[char]) { antennas[char] = []; } antennas[char].push({ x, y }); } }); }); return antennas; }; // Function to gather all unique antinode positions in the grid const calculateAntinodes = (antennas, width, height) => { const antinodes = new Set(); Object.entries(antennas).forEach(([freq, positions]) => { const numPositions = positions.length; for (let i = 0; i < numPositions; i++) { const first = positions[i]; for (let j = i + 1; j < numPositions; j++) { const second = positions[j]; let dx = second.x - first.x; let dy = second.y - first.y; // Reduce the differences by the greatest common divisor (gcd) const gcdValue = computeGCD(dx, dy); dx /= gcdValue; dy /= gcdValue; // Add antinodes along the line in both directions addAntinodesAlongLine(first.x, first.y, dx, dy, width, height, antinodes); addAntinodesAlongLine(first.x - dx, first.y - dy, -dx, -dy, width, height, antinodes); } } }); return antinodes; }; // Function to add antinode positions along a specific line direction const addAntinodesAlongLine = (startX, startY, dx, dy, width, height, antinodes) => { let x = startX; let y = startY; // Add positions while moving along the line while (x >= 0 && x < width && y >= 0 && y < height) { const key = `${x},${y}`; antinodes.add(key); x += dx; y += dy; } }; // Main execution function const main = () => { const input = fs.readFileSync('input.txt', 'utf8').trim(); const grid = input.split('\n'); const height = grid.length; const width = grid[0].length; // Parse the antennas from the grid const antennas = parseAntennas(grid); // Calculate all unique antinode positions const antinodes = calculateAntinodes(antennas, width, height); // Output the number of unique antinodes console.log(antinodes.size); }; // Run the program main();",javascript 293,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,"const fs = require('fs'); // Load and parse the input file into a grid const loadGrid = () => { return fs.readFileSync('input.txt', 'utf8') .trim() .split('\n') .map(line => line.split('')); }; // Compute the greatest common divisor (GCD) of two numbers const calculateGCD = (a, b) => { while (b !== 0) { [a, b] = [b, a % b]; } return a; }; // Find all unique antinode positions in the grid const calculateAntinodes = (grid) => { const rows = grid.length; const cols = grid[0].length; const antinodes = new Set(); // Iterate through all pairs of antennas for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { const frequency = grid[i][j]; if (frequency === '.') continue; // Skip empty spaces for (let k = 0; k < rows; k++) { for (let l = 0; l < cols; l++) { if (grid[k][l] !== frequency || (i === k && j === l)) continue; // Skip same antenna or different frequencies // Calculate the direction vector between the two antennas const dx = k - i; const dy = l - j; const gcd = calculateGCD(Math.abs(dx), Math.abs(dy)); const stepX = dx / gcd; const stepY = dy / gcd; // Traverse in the direction of the vector to find antinodes let x = i + stepX; let y = j + stepY; while (x >= 0 && x < rows && y >= 0 && y < cols) { antinodes.add(`${x},${y}`); x += stepX; y += stepY; } // Traverse in the opposite direction to find antinodes x = i - stepX; y = j - stepY; while (x >= 0 && x < rows && y >= 0 && y < cols) { antinodes.add(`${x},${y}`); x -= stepX; y -= stepY; } } } } } return antinodes.size; }; // Main function to execute the solution const main = () => { const grid = loadGrid(); const antinodeCount = calculateAntinodes(grid); console.log(antinodeCount); }; // Run the main function main();",javascript 294,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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8').trim(); const lines = input.split('\n'); const height = lines.length; const width = lines[0].length; const antennas = {}; // Collect antennas by frequency for (let y = 0; y < height; y++) { const line = lines[y]; for (let x = 0; x < width; x++) { const char = line[x]; if (/[a-zA-Z0-9]/.test(char)) { if (!antennas[char]) antennas[char] = []; antennas[char].push({ x, y }); } } } const antinodes = new Set(); function gcd(a, b) { while (b !== 0) { [a, b] = [b, a % b]; } return Math.abs(a); } for (const freq in antennas) { const positions = antennas[freq]; const n = positions.length; for (let i = 0; i < n; i++) { const A = positions[i]; for (let j = i + 1; j < n; j++) { const B = positions[j]; let dx = B.x - A.x; let dy = B.y - A.y; const stepGCD = gcd(dx, dy); dx /= stepGCD; dy /= stepGCD; // Include positions along the line in both directions const points = []; // From A towards B let x = A.x; let y = A.y; while (x >= 0 && x < width && y >= 0 && y < height) { const key = `${x},${y}`; antinodes.add(key); x += dx; y += dy; } // From A in the opposite direction x = A.x - dx; y = A.y - dy; while (x >= 0 && x < width && y >= 0 && y < height) { const key = `${x},${y}`; antinodes.add(key); x -= dx; y -= dy; } } } } 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. 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,"const fs = require('fs'); // Load the disk map from the input file const loadDiskMap = (filePath) => { return fs.readFileSync(filePath, 'utf8').trim(); }; // Parse the disk map into a list of blocks const parseDiskMap = (diskMap) => { const blocks = []; let isFile = true; let fileId = 0; for (const char of diskMap) { const length = parseInt(char, 10); if (isFile) { // Add file blocks with the current file ID for (let i = 0; i < length; i++) { blocks.push(fileId); } fileId++; } else { // Add free space blocks represented by -1 for (let i = 0; i < length; i++) { blocks.push(-1); } } // Alternate between file and free space isFile = !isFile; } return blocks; }; // Compact the disk by moving file blocks to the leftmost free space const compactDisk = (blocks) => { while (true) { const leftmostFreeIndex = blocks.indexOf(-1); if (leftmostFreeIndex === -1) break; // No free space left let lastFileIndex = blocks.length - 1; while (lastFileIndex > leftmostFreeIndex && blocks[lastFileIndex] === -1) { lastFileIndex--; } if (lastFileIndex <= leftmostFreeIndex) break; // No file blocks to move // Move the last file block to the leftmost free space blocks[leftmostFreeIndex] = blocks[lastFileIndex]; blocks[lastFileIndex] = -1; } return blocks; }; // Calculate the filesystem checksum const calculateChecksum = (blocks) => { return blocks.reduce((sum, block, index) => { return block !== -1 ? sum + index * block : sum; }, 0); }; // Main function to execute the solution const main = () => { const diskMap = loadDiskMap('input.txt'); const blocks = parseDiskMap(diskMap); const compactedBlocks = compactDisk(blocks); const checksum = calculateChecksum(compactedBlocks); console.log(checksum); }; // Run the program 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. 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,"const fs = require('fs'); // Helper function to parse the input disk map into an array of file lengths and free space lengths const parseDiskMap = (input) => { const diskLengths = input.split('').map(Number); let disk = []; let fileId = 0; let isFile = true; // Build the initial disk representation by alternating between file blocks and free space blocks diskLengths.forEach((length) => { if (isFile) { // Add file blocks disk.push(...Array(length).fill(fileId)); fileId++; } else { // Add free space blocks represented by -1 disk.push(...Array(length).fill(-1)); } isFile = !isFile; // Toggle between file and free space }); return disk; }; // Helper function to simulate the compaction of files on the disk const compactDisk = (disk) => { let moved = true; while (moved) { moved = false; // Find the leftmost free space index let leftmostFreeIndex = disk.indexOf(-1); if (leftmostFreeIndex === -1) { // No free space left, disk is compacted break; } // Find the last file block index let lastFileIndex = disk.length - 1; while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { lastFileIndex--; } if (lastFileIndex <= leftmostFreeIndex) { // No file blocks to move break; } // Move the last file block to the leftmost free space disk[leftmostFreeIndex] = disk[lastFileIndex]; disk[lastFileIndex] = -1; // Set moved flag to true to keep going moved = true; } return disk; }; // Helper function to calculate the checksum of the compacted disk const calculateChecksum = (disk) => { return disk.reduce((checksum, block, index) => { if (block !== -1) { checksum += index * block; // Sum the product of position and file ID } return checksum; }, 0); }; // Main function to orchestrate the solution const calculateDiskChecksum = (filePath) => { const input = fs.readFileSync(filePath, 'utf-8').trim(); // Step 1: Parse the disk map into the initial disk representation let disk = parseDiskMap(input); // Step 2: Compact the disk by moving file blocks to the leftmost free space disk = compactDisk(disk); // Step 3: Calculate and return the checksum return calculateChecksum(disk); }; // Output the resulting checksum const checksum = calculateDiskChecksum('input.txt'); 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. 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,"const fs = require('fs'); // Read and parse the input from the file const getInput = (filePath) => { const input = fs.readFileSync(filePath, 'utf-8').trim(); return input.split('').map(Number); // Convert the input to an array of numbers }; // Build the initial disk state (alternating files and free spaces) const buildDiskState = (diskLengths) => { let disk = []; let fileId = 0; let isFile = true; for (let length of diskLengths) { if (isFile) { disk.push(...Array(length).fill(fileId)); // Add file blocks fileId++; } else { disk.push(...Array(length).fill(-1)); // Add free space blocks } isFile = !isFile; // Toggle between file and free space } return disk; }; // Compact the disk by moving file blocks to the leftmost available free space const compactDisk = (disk) => { let moved = true; while (moved) { moved = false; const leftmostFreeIndex = disk.indexOf(-1); if (leftmostFreeIndex === -1) break; // No free space left to move files into // Find the last file block's index let lastFileIndex = disk.length - 1; while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { lastFileIndex--; } // If no file blocks to move, stop the process if (lastFileIndex <= leftmostFreeIndex) break; // Move the last file block to the leftmost free space disk[leftmostFreeIndex] = disk[lastFileIndex]; disk[lastFileIndex] = -1; // Mark the last file block position as free moved = true; // Continue compacting } return disk; }; // Calculate the checksum by summing the product of positions and file IDs const calculateChecksum = (disk) => { return disk.reduce((checksum, fileId, index) => { if (fileId !== -1) { checksum += index * fileId; // Multiply position by file ID and sum } return checksum; }, 0); }; // Main function to orchestrate the disk processing and checksum calculation const processDisk = (filePath) => { const diskLengths = getInput(filePath); // Step 1: Get and parse the disk map let disk = buildDiskState(diskLengths); // Step 2: Build the initial disk state disk = compactDisk(disk); // Step 3: Compact the disk to remove free space const checksum = calculateChecksum(disk); // Step 4: Calculate the checksum return checksum; }; // Run the function and print the resulting checksum const checksum = processDisk('input.txt'); 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. 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,"const fs = require('fs'); // Load the disk map from the input file const loadInput = (filePath) => fs.readFileSync(filePath, 'utf8').trim(); // Parse the disk map into blocks const parseBlocks = (diskMap) => { const blocks = []; let isFile = true; let fileId = 0; for (const char of diskMap) { const length = parseInt(char, 10); if (isFile) { for (let i = 0; i < length; i++) blocks.push(fileId); fileId++; } else { for (let i = 0; i < length; i++) blocks.push(-1); } isFile = !isFile; } return blocks; }; // Compact the disk by moving file blocks to the leftmost free space const compactBlocks = (blocks) => { while (true) { const freeIndex = blocks.indexOf(-1); if (freeIndex === -1) break; let lastFileIndex = blocks.length - 1; while (lastFileIndex > freeIndex && blocks[lastFileIndex] === -1) lastFileIndex--; if (lastFileIndex <= freeIndex) break; blocks[freeIndex] = blocks[lastFileIndex]; blocks[lastFileIndex] = -1; } return blocks; }; // Calculate the checksum of the compacted disk const computeChecksum = (blocks) => { return blocks.reduce((sum, block, index) => (block !== -1 ? sum + index * block : sum), 0); }; // Main function to execute the solution const main = () => { const diskMap = loadInput('input.txt'); const blocks = parseBlocks(diskMap); const compactedBlocks = compactBlocks(blocks); const checksum = computeChecksum(compactedBlocks); console.log(checksum); }; // Run the program 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. 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,"// Read the input disk map as a string const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf-8').trim(); // Parse the disk map into file lengths and free space lengths const diskLengths = input.split('').map(Number); let disk = []; let fileId = 0; let isFile = true; // Build the initial disk representation for (let i = 0; i < diskLengths.length; i++) { const length = diskLengths[i]; if (isFile) { // Add blocks for the current file with the file ID for (let j = 0; j < length; j++) { disk.push(fileId); } fileId++; } else { // Add free space blocks represented by -1 for (let j = 0; j < length; j++) { disk.push(-1); } } // Alternate between file and free space isFile = !isFile; } // Simulate moving file blocks one at a time from the end to the leftmost free space while (true) { // Find the leftmost free space index let leftmostFreeIndex = disk.indexOf(-1); if (leftmostFreeIndex === -1) { // No free space left, disk is compacted break; } // Find the last file block index let lastFileIndex = disk.length - 1; while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { lastFileIndex--; } if (lastFileIndex <= leftmostFreeIndex) { // No file blocks to move break; } // Move the last file block to the leftmost free space disk[leftmostFreeIndex] = disk[lastFileIndex]; disk[lastFileIndex] = -1; } // Calculate the filesystem checksum let checksum = 0; for (let i = 0; i < disk.length; i++) { if (disk[i] !== -1) { // Sum the product of position and file ID checksum += i * disk[i]; } } // Output the resulting checksum 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. 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,"const fs = require('fs'); const path = require('path'); // Parse the disk map into a memory map array, alternating between files and free space function parseDiskMap(input) { if (!input) return []; let memoryMap = []; let isFile = true; let fileID = 0; for (const char of input) { const length = Number(char); if (isNaN(length)) { console.error(`Invalid character in disk map: ${char}`); process.exit(1); } if (isFile) { memoryMap.push(...Array(length).fill(fileID)); fileID++; } else { memoryMap.push(...Array(length).fill(-1)); // Free space } isFile = !isFile; // Alternate between file and free space } return memoryMap; } // Part 2: Compact the disk by moving entire files to the leftmost free space function compactify2(memoryMap) { let files = []; let currentFileID = null; let currentSize = 0; // Extract files from the memory map for (let i = 0; i <= memoryMap.length; i++) { const block = memoryMap[i]; if (block !== currentFileID && currentFileID !== null) { files.push({ id: currentFileID, size: currentSize }); currentFileID = null; currentSize = 0; } if (block !== -1 && currentFileID === null) { currentFileID = block; currentSize = 1; } else if (block === currentFileID) { currentSize++; } } // Sort files by descending ID files.sort((a, b) => b.id - a.id); // Move files to the leftmost available free space files.forEach(file => { const { id, size } = file; let targetStart = -1; let gapLength = 0; // Find the leftmost space for the file for (let i = 0; i < memoryMap.length; i++) { if (memoryMap[i] === -1) { gapLength++; if (gapLength === size) { targetStart = i - size + 1; break; } } else { gapLength = 0; } } if (targetStart === -1) return; // No space found // Move the file blocks to the found space const filePositions = []; for (let i = 0; i < memoryMap.length; i++) { if (memoryMap[i] === id) filePositions.push(i); } if (filePositions.length !== size) { console.error(`Mismatch in file size for file ID ${id}`); process.exit(1); } const firstFileBlock = filePositions[0]; if (firstFileBlock < targetStart) return; // No need to move for (let j = 0; j < size; j++) { memoryMap[targetStart + j] = id; memoryMap[filePositions[j]] = -1; } }); return memoryMap; } // Calculate the checksum of the memory map function calculateChecksum(memoryMap, skipFree = false) { return memoryMap.reduce((checksum, value, index) => { if (skipFree && value === -1) return checksum; if (!skipFree || value !== -1) { checksum += index * value; } return checksum; }, 0); } // Main function function main() { const filePath = path.join(__dirname, 'input.txt'); // Read input file let content; try { content = fs.readFileSync(filePath, 'utf-8').trim(); } catch (err) { console.error(`Error reading input file: ${err.message}`); process.exit(1); } // Parse the disk map const memoryMap = parseDiskMap(content); // Prepare separate copies for part 1 and part 2 const memoryMapPart1 = [...memoryMap]; const memoryMapPart2 = [...memoryMap]; // Part 2: Compact by moving entire files compactify2(memoryMapPart2); // Part 2 Checksum Calculation const part2Checksum = calculateChecksum(memoryMapPart2, true); console.log(`Part 2 Checksum: ${part2Checksum}`); } // Execute the program 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error('Error reading file:', err); return; } data = data.split("""").map(Number); console.log(part1(data)); console.log(part2(data)); }); const checkSum = data => { let checkSum = 0; for (let i = 0; i < data.length; i++) { if (!isNaN(data[i])) { checkSum += Number(data[i]) * i; } } return checkSum; } const part1 = (data) => { let rawData = []; for (let i = 0; i < data.length; i++) { const char = i % 2 === 0 ? (i/2).toString() : ""."" rawData.push(...Array(data[i]).fill(char)); } for (let i = 0; i < rawData.length; i++) { if (rawData[i] === ""."" && rawData[i + 1]) { if (rawData[rawData.length -1] === ""."") { while (rawData[rawData.length - 1] === ""."") { rawData.pop(); } } rawData[i] = rawData.pop(); } } return checkSum(rawData.filter(num => !isNaN(Number(num)))); } const part2 = (data) => { let rawData = []; for (let i = 0; i < data.length; i++) { const char = i % 2 === 0 ? (i/2).toString() : ""."" rawData.push(new Array(data[i]).fill(char)) } if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); for (let i = rawData.length - 1; i >= 0; i--) { if (!rawData[i].length || rawData[i][0] === ""."") continue; let firstMatchingIndex = rawData.findIndex((item, index) => item.length >= rawData[i].length && item[0] === ""."" && index < i); if (firstMatchingIndex === -1) { continue; } else { // if it can be swapped directly, swap it if (rawData[i].length === rawData[firstMatchingIndex].length) { [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; } else { const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); // i is the numbers, firstMatchingINdex is the dots let numsToMove = rawData[i]; rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); rawData[firstMatchingIndex] = numsToMove; rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); } } } return checkSum(rawData.flat()); }",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. 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,"const fs = require('fs'); const path = require('path'); /** * Parses the disk map string into an array of blocks. * Files are represented by their unique ID, and free spaces by -1. * @param {string} input - The disk map string. * @returns {number[]} - The memory map array. */ function parseDiskMap(input) { if (input === '') { return []; } const memoryMap = []; let isFile = true; // Flag to alternate between file and free space let fileID = 0; for (const char of input) { const length = parseInt(char, 10); if (isNaN(length)) { console.error(`Invalid character in disk map: ${char}`); process.exit(1); } if (isFile) { // Assign fileID to the next 'length' blocks for (let i = 0; i < length; i++) { memoryMap.push(fileID); } fileID++; } else { // Assign -1 (free space) to the next 'length' blocks for (let i = 0; i < length; i++) { memoryMap.push(-1); } } // Toggle between file and free space isFile = !isFile; } return memoryMap; } /** * Part 2: Move entire files to the leftmost possible free space that can fit them. * Files are processed in order of decreasing file ID. * @param {number[]} memoryMap - The memory map array. * @returns {number[]} - The updated memory map after compaction. */ function compactify2(memoryMap) { // Identify all files with their IDs and sizes const files = []; let currentFileID = null; let currentSize = 0; for (let i = 0; i <= memoryMap.length; i++) { const block = memoryMap[i]; if (block !== currentFileID && currentFileID !== null) { // End of the current file files.push({ id: currentFileID, size: currentSize }); currentFileID = null; currentSize = 0; } if (block !== -1 && currentFileID === null) { // Start of a new file currentFileID = block; currentSize = 1; } else if (block === currentFileID) { // Continuation of the current file currentSize++; } } // Sort files by decreasing file ID files.sort((a, b) => b.id - a.id); for (const file of files) { const { id, size } = file; // Find the leftmost span of free space that can fit the entire file let targetStart = -1; let gapLength = 0; for (let i = 0; i < memoryMap.length; i++) { if (memoryMap[i] === -1) { gapLength++; if (gapLength === size) { targetStart = i - size + 1; break; } } else { gapLength = 0; } } if (targetStart === -1) { // No suitable free space found continue; } // Find the current positions of the file blocks const filePositions = []; for (let i = 0; i < memoryMap.length; i++) { if (memoryMap[i] === id) { filePositions.push(i); } } if (filePositions.length !== size) { console.error(`Mismatch in file size for file ID ${id}`); process.exit(1); } const firstFileBlock = filePositions[0]; if (firstFileBlock < targetStart) { // The file is already to the left; no need to move continue; } // Move the file blocks to the targetStart for (let j = 0; j < size; j++) { memoryMap[targetStart + j] = id; memoryMap[filePositions[j]] = -1; } } return memoryMap; } /** * Calculates the filesystem checksum. * @param {number[]} memoryMap - The memory map array. * @param {boolean} skipFree - Whether to skip free spaces (-1). * @returns {number} - The calculated checksum. */ function calculateChecksum(memoryMap, skipFree = false) { let checksum = 0; for (let i = 0; i < memoryMap.length; i++) { const value = memoryMap[i]; if (skipFree && value === -1) { continue; } if (!skipFree || value !== -1) { checksum += i * value; } } return checksum; } /** * Main function to execute the disk compaction and checksum calculation. */ function main() { // Read the input disk map from 'input.txt' const filePath = path.join(__dirname, 'input.txt'); let content; try { content = fs.readFileSync(filePath, 'utf-8').trim(); } catch (err) { console.error(`Error reading input file: ${err.message}`); process.exit(1); } // Parse the disk map const memoryMap = parseDiskMap(content); // Clone the memory map for Part 1 and Part 2 const oneMemoryMap = [...memoryMap]; const twoMemoryMap = [...memoryMap]; console.log(`\nInitial Memory Map:`); console.log(oneMemoryMap.map(block => (block === -1 ? '.' : block)).join('')); // Part 2: Compact by moving entire files console.log(`\n--- Part 2: Moving Entire Files ---`); console.log(`Started Memory Map Length: ${twoMemoryMap.length}`); compactify2(twoMemoryMap); console.log(`Ended Memory Map Length: ${twoMemoryMap.length}`); console.log(`Final Memory Map after Part 2:`); console.log(twoMemoryMap.map(block => (block === -1 ? '.' : block)).join('')); // Calculate Part 2 Checksum let sumPart2 = 0; for (let pos = 0; pos < twoMemoryMap.length; pos++) { const value = twoMemoryMap[pos]; if (value === -1) { continue; // Skip free spaces } sumPart2 += pos * value; } console.log(`Part 2 Checksum: ${sumPart2}`); } // Execute the main function 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; // Asynchronous file reading and processing const processFile = (filePath) => { fs.readFile(filePath, ""utf8"", (err, data) => { if (err) { console.error(""Error reading file:"", err); return; } const parsedData = parseInputData(data); console.log(computePart1(parsedData)); console.log(computePart2(parsedData)); }); }; // Parse the input data into an array of numbers const parseInputData = (data) => { return data.split("""").map(Number); }; // Helper function to compute checksum const calculateChecksum = (data) => { return data.reduce((sum, value, index) => { if (!isNaN(value)) { return sum + value * index; } return sum; }, 0); }; // Part 1 computation logic const computePart1 = (data) => { let rawData = createInitialRawData(data); // Perform the file-block shifting logic rawData = moveFileBlocks(rawData); // Filter out non-numeric values and calculate checksum const numericData = rawData.filter(value => !isNaN(Number(value))); return calculateChecksum(numericData); }; // Helper function to create the initial raw data const createInitialRawData = (data) => { let rawData = []; for (let i = 0; i < data.length; i++) { const char = i % 2 === 0 ? (i / 2).toString() : "".""; rawData.push(...Array(data[i]).fill(char)); } return rawData; }; // Helper function to shift file blocks const moveFileBlocks = (rawData) => { for (let i = 0; i < rawData.length; i++) { if (rawData[i] === ""."" && rawData[i + 1]) { if (rawData[rawData.length - 1] === ""."") { while (rawData[rawData.length - 1] === ""."") { rawData.pop(); } } rawData[i] = rawData.pop(); } } return rawData; }; // Part 2 computation logic const computePart2 = (data) => { let rawData = create2DInitialRawData(data); // Remove unnecessary trailing empty slots if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); // Perform file swapping and shifting rawData = swapAndShiftFiles(rawData); // Flatten the 2D array and calculate checksum return calculateChecksum(rawData.flat()); }; // Helper function to create the initial 2D raw data for part 2 const create2DInitialRawData = (data) => { let rawData = []; for (let i = 0; i < data.length; i++) { const char = i % 2 === 0 ? (i / 2).toString() : "".""; rawData.push(new Array(data[i]).fill(char)); } return rawData; }; // Helper function to swap and shift file blocks const swapAndShiftFiles = (rawData) => { for (let i = rawData.length - 1; i >= 0; i--) { if (!rawData[i].length || rawData[i][0] === ""."") continue; const firstMatchingIndex = findMatchingFreeSpace(rawData, i); if (firstMatchingIndex === -1) continue; if (rawData[i].length === rawData[firstMatchingIndex].length) { [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; } else { const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); let numsToMove = rawData[i]; rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); rawData[firstMatchingIndex] = numsToMove; rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); } } return rawData; }; // Helper function to find the first matching free space large enough to fit a file const findMatchingFreeSpace = (rawData, currentIndex) => { return rawData.findIndex((item, index) => item.length >= rawData[currentIndex].length && item[0] === ""."" && index < currentIndex); }; // Execute the program 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; // Read the input file and handle errors function readInputFile(filePath) { return new Promise((resolve, reject) => { fs.readFile(filePath, ""utf8"", (err, data) => { if (err) { reject(`Error reading file: ${err}`); } else { resolve(data); } }); }); } // Helper function to calculate the checksum function calculateChecksum(data) { return data.reduce((checksum, value, index) => { if (!isNaN(value)) { checksum += Number(value) * index; } return checksum; }, 0); } // Part 1 logic: Process data into a new array, then calculate checksum function processPart1(data) { const rawData = []; data.forEach((value, index) => { const char = index % 2 === 0 ? (index / 2).toString() : "".""; rawData.push(...Array(value).fill(char)); }); // Cleanup rawData by removing trailing dots and adjusting positions for (let i = 0; i < rawData.length; i++) { if (rawData[i] === ""."" && rawData[i + 1]) { if (rawData[rawData.length - 1] === ""."") { while (rawData[rawData.length - 1] === ""."") { rawData.pop(); } } rawData[i] = rawData.pop(); } } return calculateChecksum(rawData.filter(num => !isNaN(Number(num)))); } // Part 2 logic: Compact the array by moving file blocks to free space function processPart2(data) { const rawData = []; data.forEach((value, index) => { const char = index % 2 === 0 ? (index / 2).toString() : "".""; rawData.push(new Array(value).fill(char)); }); if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); // Move files into the leftmost available spaces for (let i = rawData.length - 1; i >= 0; i--) { if (!rawData[i].length || rawData[i][0] === ""."") continue; const firstMatchingIndex = rawData.findIndex((item, index) => { return item.length >= rawData[i].length && item[0] === ""."" && index < i; }); if (firstMatchingIndex !== -1) { if (rawData[i].length === rawData[firstMatchingIndex].length) { [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; } else { const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); const numsToMove = rawData[i]; rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); rawData[firstMatchingIndex] = numsToMove; rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); } } } return calculateChecksum(rawData.flat()); } // Main function to execute the program async function main() { try { const data = await readInputFile(inputText); const parsedData = data.split("""").map(Number); console.log(""Part 1 Checksum:"", processPart1(parsedData)); console.log(""Part 2 Checksum:"", processPart2(parsedData)); } catch (error) { console.error(error); } } // Run the main function 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. 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,"const fs = require('fs'); class Position { constructor(row, col, height) { this.row = row; this.col = col; this.height = height; } toString() { return `${this.row},${this.col}`; } } class HikingMap { constructor(grid) { this.grid = grid; this.rows = grid.length; this.cols = grid[0].length; this.directions = [ { dx: 0, dy: 1 }, // right { dx: 1, dy: 0 }, // down { dx: 0, dy: -1 }, // left { dx: -1, dy: 0 } // up ]; } getHeight(row, col) { return this.grid[row][col]; } isValidPosition(row, col) { return row >= 0 && row < this.rows && col >= 0 && col < this.cols; } findTrailheads() { const trailheads = []; for (let row = 0; row < this.rows; row++) { for (let col = 0; col < this.cols; col++) { if (this.getHeight(row, col) === 0) { trailheads.push(new Position(row, col, 0)); } } } return trailheads; } getNeighbors(position) { return this.directions .map(({ dx, dy }) => ({ row: position.row + dx, col: position.col + dy })) .filter(({ row, col }) => this.isValidPosition(row, col)) .map(({ row, col }) => new Position(row, col, this.getHeight(row, col))); } } class TrailFinder { constructor(hikingMap) { this.map = hikingMap; this.reachableNines = new Set(); this.visited = new Set(); } findTrailsFromPosition(position) { this.reachableNines.clear(); this.visited.clear(); this.visited.add(position.toString()); this.explorePaths(position); return this.reachableNines.size; } explorePaths(currentPos) { if (currentPos.height === 9) { this.reachableNines.add(currentPos.toString()); return; } const neighbors = this.map.getNeighbors(currentPos); for (const neighbor of neighbors) { const key = neighbor.toString(); if (!this.visited.has(key) && neighbor.height === currentPos.height + 1) { this.visited.add(key); this.explorePaths(neighbor); this.visited.delete(key); } } } } class HikingTrailSolver { static solve(inputFile) { try { const grid = this.parseInput(inputFile); const hikingMap = new HikingMap(grid); const trailFinder = new TrailFinder(hikingMap); return hikingMap.findTrailheads() .map(trailhead => trailFinder.findTrailsFromPosition(trailhead)) .reduce((sum, score) => sum + score, 0); } catch (error) { console.error('Error solving hiking trails:', error); throw error; } } static parseInput(filename) { const content = fs.readFileSync(filename, 'utf8').trim(); return content.split('\n').map(line => line.split('').map(Number) ); } } // Execute solution try { const result = HikingTrailSolver.solve('input.txt'); console.log(`Sum of trailhead scores: ${result}`); } catch (error) { console.error('Failed to solve puzzle:', error); process.exit(1); }",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. 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,"const fs = require('fs'); function findTrailheadScores(map) { const rows = map.length; const cols = map[0].length; const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up let totalScore = 0; // Find all trailheads (positions with height 0) for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { if (map[r][c] === 0) { const score = calculateTrailheadScore(r, c, map); totalScore += score; } } } return totalScore; } function calculateTrailheadScore(startRow, startCol, map) { const rows = map.length; const cols = map[0].length; const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; const reachableNines = new Set(); // Store unique positions of reachable 9s // Use DFS to find all possible paths function dfs(row, col, currentHeight, visited) { // If we reached height 9, add position to reachableNines if (map[row][col] === 9) { reachableNines.add(`${row},${col}`); return; } // Try all directions for (const [dr, dc] of directions) { const newRow = row + dr; const newCol = col + dc; // Check if new position is valid if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && !visited.has(`${newRow},${newCol}`)) { // Check if height increases by exactly 1 if (map[newRow][newCol] === currentHeight + 1) { visited.add(`${newRow},${newCol}`); dfs(newRow, newCol, currentHeight + 1, visited); visited.delete(`${newRow},${newCol}`); } } } } // Start DFS from the trailhead const visited = new Set([`${startRow},${startCol}`]); dfs(startRow, startCol, 0, visited); return reachableNines.size; } // Read and parse input function parseInput(filename) { const input = fs.readFileSync(filename, 'utf8').trim(); return input.split('\n').map(line => line.split('').map(Number) ); } // Main execution try { const map = parseInput('input.txt'); const result = findTrailheadScores(map); console.log(`Sum of trailhead scores: ${result}`); } catch (error) { console.error('Error:', error.message); }",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. 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,"const fs = require('fs'); // Function to parse the input map into a 2D array of integers const parseInput = (filename) => { try { const input = fs.readFileSync(filename, 'utf8').trim(); return input.split('\n').map(line => line.split('').map(Number)); } catch (error) { console.error('Error parsing input:', error.message); throw error; } }; // Helper function to check if a given position is within bounds and valid for hiking const isValidMove = (row, col, currentHeight, rows, cols, visited, map) => { return ( row >= 0 && row < rows && col >= 0 && col < cols && !visited.has(`${row},${col}`) && map[row][col] === currentHeight + 1 ); }; // Depth First Search (DFS) to explore hiking trails from a given start position const dfs = (row, col, currentHeight, visited, rows, cols, directions, map, reachableNines) => { if (map[row][col] === 9) { reachableNines.add(`${row},${col}`); return; } // Explore in all 4 directions (right, down, left, up) for (const [dr, dc] of directions) { const newRow = row + dr; const newCol = col + dc; if (isValidMove(newRow, newCol, currentHeight, rows, cols, visited, map)) { visited.add(`${newRow},${newCol}`); dfs(newRow, newCol, currentHeight + 1, visited, rows, cols, directions, map, reachableNines); visited.delete(`${newRow},${newCol}`); } } }; // Function to calculate the score of a trailhead const calculateTrailheadScore = (startRow, startCol, map) => { const rows = map.length; const cols = map[0].length; const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up const reachableNines = new Set(); // Store unique positions of reachable 9s const visited = new Set([`${startRow},${startCol}`]); // Initialize visited set with the trailhead // Start DFS to explore hiking paths from the trailhead dfs(startRow, startCol, 0, visited, rows, cols, directions, map, reachableNines); return reachableNines.size; // Return the number of reachable '9' heights }; // Function to find the sum of trailhead scores on the map const findTrailheadScores = (map) => { const rows = map.length; const cols = map[0].length; let totalScore = 0; // Loop through each position on the map to find trailheads (height 0) for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { if (map[r][c] === 0) { // Found a trailhead totalScore += calculateTrailheadScore(r, c, map); // Add score from this trailhead } } } return totalScore; }; // Main function to execute the program const main = () => { const map = parseInput('input.txt'); // Read and parse the map const result = findTrailheadScores(map); // Calculate the sum of trailhead scores console.log(`Sum of trailhead scores: ${result}`); // Output the result }; 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. 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,"const fs = require('fs'); // Step 1: Parse the Input const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n').map(line => line.split('').map(Number)); const numRows = input.length; const numCols = input[0].length; // Directions: up, down, left, right const dirs = [ [-1, 0], [1, 0], [0, -1], [0, 1] ]; // Step 2: Identify Trailheads const trailheads = []; for (let i = 0; i < numRows; i++) { for (let j = 0; j < numCols; j++) { if (input[i][j] === 0) { trailheads.push([i, j]); } } } // Step 3: DFS to find reachable 9s function dfs(x, y, currentHeight, visited) { if (currentHeight === 9) { return new Set([[x, y].toString()]); } let reachable = new Set(); for (const [dx, dy] of dirs) { const nx = x + dx; const ny = y + dy; if ( nx >= 0 && nx < numRows && ny >= 0 && ny < numCols && input[nx][ny] === currentHeight + 1 && !visited.has([nx, ny].toString()) ) { visited.add([nx, ny].toString()); const result = dfs(nx, ny, input[nx][ny], visited); for (const pos of result) { reachable.add(pos); } } } return reachable; } // Step 4 & 5: Calculate Scores and Sum let totalScore = 0; for (const [i, j] of trailheads) { const reachable9s = dfs(i, j, 0, new Set([`${i},${j}`])); totalScore += reachable9s.size; } 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. 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,"const fs = require(""fs""); // Constants const DIRECTIONS = [ [0, 1], // Right [1, 0], // Down [0, -1], // Left [-1, 0], // Up ]; // Helper function to parse the input file into a 2D map const parseInput = (filename) => { const input = fs.readFileSync(filename, ""utf8"").trim(); return input.split(""\n"").map((line) => line.split("""").map(Number)); }; // Helper function to check if a position is valid on the map const isValidPosition = (row, col, rows, cols) => { return row >= 0 && row < rows && col >= 0 && col < cols; }; // Depth-First Search (DFS) to find reachable 9s from a trailhead const dfs = (row, col, currentHeight, map, visited, reachableNines) => { const rows = map.length; const cols = map[0].length; // If we reach a height of 9, add it to the reachableNines set if (map[row][col] === 9) { reachableNines.add(`${row},${col}`); return; } // Explore all four directions for (const [dr, dc] of DIRECTIONS) { const newRow = row + dr; const newCol = col + dc; // Check if the new position is valid and not visited if (isValidPosition(newRow, newCol, rows, cols) && !visited.has(`${newRow},${newCol}`)) { // Ensure the height increases by exactly 1 if (map[newRow][newCol] === currentHeight + 1) { visited.add(`${newRow},${newCol}`); dfs(newRow, newCol, currentHeight + 1, map, visited, reachableNines); visited.delete(`${newRow},${newCol}`); } } } }; // Calculate the score for a single trailhead const calculateTrailheadScore = (startRow, startCol, map) => { const reachableNines = new Set(); // Track unique positions of reachable 9s const visited = new Set([`${startRow},${startCol}`]); // Track visited positions // Perform DFS to find all reachable 9s dfs(startRow, startCol, 0, map, visited, reachableNines); return reachableNines.size; // The score is the number of unique reachable 9s }; // Find the sum of scores for all trailheads on the map const findTrailheadScores = (map) => { const rows = map.length; const cols = map[0].length; let totalScore = 0; // Iterate through the map to find all trailheads (height 0) for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { if (map[r][c] === 0) { const score = calculateTrailheadScore(r, c, map); totalScore += score; } } } return totalScore; }; // Main function to execute the program const main = () => { try { const map = parseInput(""input.txt""); // Parse the input file const result = findTrailheadScores(map); // Calculate the total score console.log(`Sum of trailhead scores: ${result}`); } catch (error) { console.error(""Error:"", error.message); } }; // Run the program 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log(""Part 1:"", getTotalValidTrails(data)); console.log(""Part 2:"", getTotalValidTrails(data, true)); }); const getZeroLocations = data => { const zeroLocations = []; for (let i = 0; i < data.length; i++) { const line = data[i]; for (let j = 0; j < line.length; j++) { const item = line[j]; if (item === 0) { zeroLocations.push([i, j]); } } } return zeroLocations; } const getValidTrails = (mapArr, startLocation, cumulative) => { const directions = [[-1, 0], [0, -1], [1, 0],[0, 1]]; const visited = new Set(); let validTrails = 0; const queue = [startLocation]; if (!cumulative) visited.add(`${startLocation[0]}, ${startLocation[1]}`) while (queue.length > 0) { const [currX, currY] = queue.shift(); if (mapArr[currX][currY] === 9) { validTrails++; } for (let [dx, dy] of directions) { const nextX = currX + dx; const nextY = currY + dy; // Check if next coord is within the map if (nextX >= 0 && nextY >= 0 && nextX < mapArr.length && nextY < mapArr[0].length) { if (mapArr[nextX][nextY] !== (mapArr[currX][currY] + 1)) continue; const nextCoordStr = `${nextX}, ${nextY}`; // Part2 is cumulative, part1 requires that this coord has not yet been visited if (cumulative || !visited.has(nextCoordStr)) { queue.push([nextX, nextY]); visited.add(nextCoordStr); } } } } return validTrails; } const getTotalValidTrails = (data, cumulative) => { let totalValidTrails = 0; const mapArr = data.split(""\n"").map(line => line.split("""").map(Number)); const zeros = getZeroLocations(mapArr); for (let zero of zeros) { const validTrails = getValidTrails(mapArr, zero, cumulative); totalValidTrails += validTrails; } return totalValidTrails; }",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. 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,"const fs = require('fs'); class HikingTrails { constructor(grid) { this.grid = grid; this.rows = grid.length; this.cols = grid[0].length; this.directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up } findTrailheadRatings() { let totalRating = 0; // Find all trailheads (height 0) for (let r = 0; r < this.rows; r++) { for (let c = 0; c < this.cols; c++) { if (this.grid[r][c] === 0) { const rating = this.calculateTrailheadRating(r, c); totalRating += rating; } } } return totalRating; } calculateTrailheadRating(startRow, startCol) { const paths = new Set(); const visited = new Set(); const buildPath = (path) => { return path.join(','); }; const dfs = (row, col, currentHeight, currentPath) => { // If we reached height 9, we found a complete path if (this.grid[row][col] === 9) { paths.add(buildPath(currentPath)); return; } // Try all directions for (const [dr, dc] of this.directions) { const newRow = row + dr; const newCol = col + dc; const newPos = `${newRow},${newCol}`; if (this.isValidMove(newRow, newCol) && !visited.has(newPos) && this.grid[newRow][newCol] === currentHeight + 1) { visited.add(newPos); currentPath.push(newPos); dfs(newRow, newCol, currentHeight + 1, currentPath); visited.delete(newPos); currentPath.pop(); } } }; // Start DFS from the trailhead const startPos = `${startRow},${startCol}`; visited.add(startPos); dfs(startRow, startCol, 0, [startPos]); return paths.size; } isValidMove(row, col) { return row >= 0 && row < this.rows && col >= 0 && col < this.cols; } } function parseInput(filename) { try { const input = fs.readFileSync(filename, 'utf8').trim(); return input.split('\n').map(line => line.split('').map(Number) ); } catch (error) { console.error('Error reading input file:', error); process.exit(1); } } function solve(filename) { const grid = parseInput(filename); const hikingTrails = new HikingTrails(grid); return hikingTrails.findTrailheadRatings(); } // Execute solution try { const result = solve('input.txt'); console.log(`Sum of trailhead ratings: ${result}`); } catch (error) { console.error('Error:', error); process.exit(1); }",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. 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,"const fs = require('fs'); class HikingTrails { constructor(grid) { this.grid = grid; this.rows = grid.length; this.cols = grid[0].length; this.directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up } // Main function to compute the sum of trailhead ratings calculateTotalTrailheadRatings() { let totalRating = 0; for (let r = 0; r < this.rows; r++) { for (let c = 0; c < this.cols; c++) { if (this.grid[r][c] === 0) { // Found a trailhead totalRating += this.calculateTrailheadRating(r, c); } } } return totalRating; } // Calculate the rating for a specific trailhead (height 0) calculateTrailheadRating(startRow, startCol) { const paths = new Set(); // Store unique paths const visited = new Set(); // Store visited positions const dfs = (row, col, currentHeight, currentPath) => { // If we reached height 9, we found a valid path if (this.grid[row][col] === 9) { paths.add(currentPath.join(',')); // Store path as a string return; } // Explore all four possible directions (right, down, left, up) for (const [dr, dc] of this.directions) { const newRow = row + dr; const newCol = col + dc; const newPos = `${newRow},${newCol}`; if (this.isValidMove(newRow, newCol) && !visited.has(newPos) && this.grid[newRow][newCol] === currentHeight + 1) { visited.add(newPos); currentPath.push(newPos); // Continue DFS dfs(newRow, newCol, currentHeight + 1, currentPath); visited.delete(newPos); // Backtrack currentPath.pop(); } } }; // Start DFS from the trailhead const startPos = `${startRow},${startCol}`; visited.add(startPos); dfs(startRow, startCol, 0, [startPos]); return paths.size; // Return number of unique paths to height 9 } // Check if a position is within bounds isValidMove(row, col) { return row >= 0 && row < this.rows && col >= 0 && col < this.cols; } } // Read and parse the input file into a 2D grid const parseInput = (filename) => { try { const input = fs.readFileSync(filename, 'utf8').trim(); return input.split('\n').map(line => line.split('').map(Number) // Convert each character to a number ); } catch (error) { console.error('Error reading input file:', error); process.exit(1); } }; // Solve the problem and return the result const solve = (filename) => { const grid = parseInput(filename); const hikingTrails = new HikingTrails(grid); return hikingTrails.calculateTotalTrailheadRatings(); }; // Main execution try { const result = solve('input.txt'); console.log(`Sum of trailhead ratings: ${result}`); } catch (error) { console.error('Error:', error); process.exit(1); }",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. 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,"const fs = require('fs'); const {log} = require('console'); const lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); const trailheads = []; for (let r = 0; r < lines.length; r++) { for (let c = 0; c < lines[r].length; c++) { if (lines[r][c] === '0') { trailheads.push([c, r]); } } } const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; function isInBounds(nextC, nextR) { return nextC >= 0 && nextR >= 0 && nextC < lines[0].length && nextR < lines.length; } function getScore(trailhead, distinct) { let score = []; let queue = directions.map(d => [...trailhead, trailhead[0] + d[0], trailhead[1] + d[1]]); while (queue.length > 0) { let [c, r, nextC, nextR] = queue.shift(); if (isInBounds(nextC, nextR) && parseInt(lines[nextR][nextC]) - parseInt(lines[r][c]) === 1) { if (lines[nextR][nextC] === '9') { score.push(`${nextC}-${nextR}`); } else { directions.forEach(d => queue.push([nextC, nextR, nextC + d[0], nextR + d[1]])) } } } if (distinct) { return score.length; } else { return new Set(score).size; } } let part1 = 0; for (let trailhead of trailheads) { part1 += getScore(trailhead, false); } log(part1); let part2 = 0; for (let trailhead of trailheads) { part2 += getScore(trailhead, true); } 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. 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,"const fs = require('fs'); // Step 1: Parse the Input const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n').map(line => line.split('').map(Number)); const numRows = input.length; const numCols = input[0].length; // Directions: up, down, left, right const dirs = [ [-1, 0], [1, 0], [0, -1], [0, 1] ]; // Step 2: Identify Trailheads const trailheads = []; for (let i = 0; i < numRows; i++) { for (let j = 0; j < numCols; j++) { if (input[i][j] === 0) { trailheads.push([i, j]); } } } // Step 3: Memoization Map const memo = Array.from({ length: numRows }, () => Array(numCols).fill(null)); // Step 4: DFS to count distinct trails function countTrails(x, y) { if (input[x][y] === 9) { return 1; } if (memo[x][y] !== null) { return memo[x][y]; } let totalPaths = 0; for (const [dx, dy] of dirs) { const nx = x + dx; const ny = y + dy; if ( nx >= 0 && nx < numRows && ny >= 0 && ny < numCols && input[nx][ny] === input[x][y] + 1 ) { totalPaths += countTrails(nx, ny); } } memo[x][y] = totalPaths; return totalPaths; } // Step 5 & 6: Calculate Ratings and Sum let totalRating = 0; for (const [i, j] of trailheads) { totalRating += countTrails(i, j); } 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. 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,"const fs = require('fs'); class PlutonianPebbles { constructor(stones) { this.stones = stones; } // Perform one blink operation on the stones blink() { const newStones = this.stones.reduce((acc, stone) => { if (stone === 0) { acc.push(1); } else if (this.hasEvenDigits(stone)) { const digits = String(stone); const mid = Math.floor(digits.length / 2); const left = parseInt(digits.slice(0, mid)); const right = parseInt(digits.slice(mid)); acc.push(left, right); } else { acc.push(stone * 2024); } return acc; }, []); this.stones = newStones; return this.stones.length; } // Check if a number has an even number of digits hasEvenDigits(num) { return String(num).length % 2 === 0; } // Simulate a number of blink operations and return the final stone count simulateBlinks(count) { let stoneCount; for (let i = 0; i < count; i++) { stoneCount = this.blink(); } return stoneCount; } } // Function to read and parse the input file function parseInput(filename) { const input = fs.readFileSync(filename, 'utf8').trim(); return input.split(/\s+/).map(Number); } // Main logic to solve the problem function solve(filename) { const initialStones = parseInput(filename); const pebbles = new PlutonianPebbles(initialStones); return pebbles.simulateBlinks(25); } // Execution block try { const result = solve('input.txt'); console.log(`Number of stones after 25 blinks: ${result}`); } catch (error) { console.error('Error:', error); process.exit(1); }",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. 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,"const fs = require('fs'); let stones = fs.readFileSync('input.txt', 'utf-8').trim().split(/\s+/); const blinks = 25; for (let i = 0; i < blinks; i++) { let newStones = []; for (let stone of stones) { if (stone === '0') { newStones.push('1'); } else if (stone.length % 2 === 0) { let half = stone.length / 2; let left = stone.slice(0, half).replace(/^0+/, '') || '0'; let right = stone.slice(half).replace(/^0+/, '') || '0'; newStones.push(left, right); } else { let num = BigInt(stone); let newNum = num * 2024n; newStones.push(newNum.toString()); } } stones = newStones; } 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. 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,"const fs = require('fs'); class PlutonianPebbles { constructor(stones) { this.stones = stones; } blink() { let newStones = []; for (const stone of this.stones) { if (stone === 0) { newStones.push(1); } else if (this.hasEvenDigits(stone)) { const digits = String(stone); const mid = Math.floor(digits.length / 2); const left = parseInt(digits.slice(0, mid)); const right = parseInt(digits.slice(mid)); newStones.push(left, right); } else { newStones.push(stone * 2024); } } this.stones = newStones; return this.stones.length; } hasEvenDigits(num) { return String(num).length % 2 === 0; } simulateBlinks(count) { let stoneCount; for (let i = 0; i < count; i++) { stoneCount = this.blink(); } return stoneCount; } } function solve(filename) { const input = fs.readFileSync(filename, 'utf8').trim(); const initialStones = input.split(/\s+/).map(Number); const pebbles = new PlutonianPebbles(initialStones); return pebbles.simulateBlinks(25); } try { const result = solve('input.txt'); console.log(`Number of stones after 25 blinks: ${result}`); } catch (error) { console.error('Error:', error); process.exit(1); }",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. 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,"const fs = require(""fs""); // Function to apply transformation rules to a single stone const applyTransformation = (stone) => { if (stone === 0) return [1]; const numDigits = String(stone).length; if (numDigits % 2 === 0) { const half = numDigits / 2; const left = parseInt(String(stone).slice(0, half)); const right = parseInt(String(stone).slice(half)); return [left, right]; } return [stone * 2024]; }; // Function to simulate blinking for all stones const simulateBlinking = (stones, blinks) => { for (let i = 0; i < blinks; i++) { stones = stones.flatMap(applyTransformation); } return stones; }; // Main function to read input, simulate blinking, and output the result const main = () => { const input = fs.readFileSync(""input.txt"", ""utf8"").trim(); let stones = input.split("" "").map(Number); const finalStones = simulateBlinking(stones, 25); console.log(finalStones.length); }; // Execute the program 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. 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,"const fs = require(""fs""); const transformStone = (stone) => { if (stone === 0) return [1]; const numDigits = String(stone).length; if (numDigits % 2 === 0) { const half = numDigits / 2; const left = parseInt(String(stone).slice(0, half)); const right = parseInt(String(stone).slice(half)); return [left, right]; } return [stone * 2024]; }; const blinkStones = (stones) => { let newStones = []; for (const stone of stones) { newStones.push(...transformStone(stone)); } return newStones; }; const main = () => { const input = fs.readFileSync(""input.txt"", ""utf8"").trim(); let stones = input.split("" "").map(Number); for (let i = 0; i < 25; i++) { stones = blinkStones(stones); } console.log(stones.length); }; 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. 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,"const fs = require('fs'); // Function to read and parse the input from the file const readStonesFromFile = (filePath) => { return fs.readFileSync(filePath, 'utf-8') .trim() .split(/\s+/); }; // Function to count the occurrences of each stone const countStones = (stones) => { return stones.reduce((counts, stone) => { counts[stone] = (counts[stone] || 0n) + 1n; return counts; }, {}); }; // Function to transform a single stone based on the given rules const transformStone = (stone) => { if (stone === '0') { return ['1']; // '0' transforms to '1' } if (stone.length % 2 === 0) { // If the stone length is even, split it into two parts const mid = stone.length / 2; const left = stone.slice(0, mid).replace(/^0+/, '') || '0'; const right = stone.slice(mid).replace(/^0+/, '') || '0'; return [left, right]; } // For odd length, multiply by 2024 const num = BigInt(stone); const newStone = (num * 2024n).toString(); return [newStone]; }; // Function to simulate the transformation for all stones const transformAllStones = (stoneCounts) => { let newStoneCounts = {}; Object.entries(stoneCounts).forEach(([stone, count]) => { const transformedStones = transformStone(stone); transformedStones.forEach(newStone => { newStoneCounts[newStone] = (newStoneCounts[newStone] || 0n) + count; }); }); return newStoneCounts; }; // Function to simulate multiple blinks by applying the transformation repeatedly const simulateBlinks = (stoneCounts, numberOfBlinks) => { let currentStoneCounts = stoneCounts; for (let i = 0; i < numberOfBlinks; i++) { currentStoneCounts = transformAllStones(currentStoneCounts); } return currentStoneCounts; }; // Function to calculate the total number of stones const getTotalStones = (stoneCounts) => { return Object.values(stoneCounts).reduce((total, count) => total + count, 0n); }; // Main function to read the input, simulate the process, and calculate the result const main = () => { const inputFilePath = 'input.txt'; const numberOfBlinks = 75; // Step 1: Read and parse the stones from the file const stones = readStonesFromFile(inputFilePath); // Step 2: Count the initial occurrences of each stone const initialStoneCounts = countStones(stones); // Step 3: Simulate the blinking process for the given number of blinks const finalStoneCounts = simulateBlinks(initialStoneCounts, numberOfBlinks); // Step 4: Calculate and output the total number of stones const totalStones = getTotalStones(finalStoneCounts); console.log(totalStones.toString()); }; // Execute the main function 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. 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,"const fs = require('fs'); class PlutonianPebbleSimulation { constructor(initialStones, blinks = 75) { this.stones = initialStones; this.blinks = blinks; this.stoneCounts = this.initializeStoneCounts(); } // Initialize the stone counts initializeStoneCounts() { return this.stones.reduce((counts, stone) => { counts[stone] = (counts[stone] || 0n) + 1n; return counts; }, {}); } // Process a single blink iteration processBlink() { const newStoneCounts = {}; Object.entries(this.stoneCounts).forEach(([stone, count]) => { const updatedStones = this.updateStone(stone, count); updatedStones.forEach(newStone => { newStoneCounts[newStone] = (newStoneCounts[newStone] || 0n) + count; }); }); this.stoneCounts = newStoneCounts; } // Determine the next stones based on the current one updateStone(stone, count) { if (stone === '0') { return ['1']; } else if (stone.length % 2 === 0) { return this.splitStone(stone); } else { return [this.multiplyStone(stone)]; } } // Split an even-length stone into two parts splitStone(stone) { const half = stone.length / 2; const left = stone.slice(0, half).replace(/^0+/, '') || '0'; const right = stone.slice(half).replace(/^0+/, '') || '0'; return [left, right]; } // Multiply an odd-length stone by 2024 multiplyStone(stone) { const num = BigInt(stone); return (num * 2024n).toString(); } // Simulate the blinking process for a set number of times simulate() { for (let i = 0; i < this.blinks; i++) { this.processBlink(); } return this.getTotalStones(); } // Calculate the total number of stones getTotalStones() { return Object.values(this.stoneCounts).reduce((sum, count) => sum + count, 0n); } } // Read input and initialize simulation function readInput(filename) { const input = fs.readFileSync(filename, 'utf-8').trim(); return input.split(/\s+/); } // Main function to run the simulation function main() { const initialStones = readInput('input.txt'); const simulation = new PlutonianPebbleSimulation(initialStones, 75); const result = simulation.simulate(); console.log(result.toString()); } // Execute the solution 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. 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,"const fs = require('fs'); // Read and parse the input file const readInput = (filePath) => { return fs.readFileSync(filePath, 'utf-8') .trim() .split(/\s+/); }; // Initialize stone counts using a Map const initializeStoneCounts = (stones) => { return stones.reduce((counts, stone) => { counts.set(stone, (counts.get(stone) || 0n) + 1n); return counts; }, new Map()); }; // Transform a single stone based on the rules const transformStone = (stone) => { if (stone === '0') { return ['1']; } else if (stone.length % 2 === 0) { const half = stone.length / 2; const left = stone.slice(0, half).replace(/^0+/, '') || '0'; const right = stone.slice(half).replace(/^0+/, '') || '0'; return [left, right]; } else { const num = BigInt(stone); const newNum = num * 2024n; return [newNum.toString()]; } }; // Simulate a single blink const simulateBlink = (stoneCounts) => { const newStoneCounts = new Map(); for (const [stone, count] of stoneCounts.entries()) { const transformedStones = transformStone(stone); transformedStones.forEach(newStone => { newStoneCounts.set(newStone, (newStoneCounts.get(newStone) || 0n) + count); }); } return newStoneCounts; }; // Simulate multiple blinks const simulateBlinks = (stoneCounts, blinks) => { let currentCounts = stoneCounts; for (let i = 0; i < blinks; i++) { currentCounts = simulateBlink(currentCounts); } return currentCounts; }; // Calculate the total number of stones const calculateTotalStones = (stoneCounts) => { return Array.from(stoneCounts.values()).reduce((total, count) => total + count, 0n); }; // Main function const main = () => { const filePath = 'input.txt'; const blinks = 75; // Read and parse the input const stones = readInput(filePath); // Initialize stone counts const initialStoneCounts = initializeStoneCounts(stones); // Simulate blinks const finalStoneCounts = simulateBlinks(initialStoneCounts, blinks); // Calculate and print the total number of stones const totalStones = calculateTotalStones(finalStoneCounts); console.log(totalStones.toString()); }; // Run the program 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. 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,"const fs = require('fs'); // Function to read and parse the input file function readInput(filePath) { const data = fs.readFileSync(filePath, 'utf-8').trim(); return data.split(/\s+/); } // Function to initialize stone counts function initializeStoneCounts(stones) { const stoneCounts = {}; for (const stone of stones) { stoneCounts[stone] = (stoneCounts[stone] || 0n) + 1n; } return stoneCounts; } // Function to transform a single stone function transformStone(stone) { if (stone === '0') { return ['1']; } else if (stone.length % 2 === 0) { const half = stone.length / 2; const left = stone.slice(0, half).replace(/^0+/, '') || '0'; const right = stone.slice(half).replace(/^0+/, '') || '0'; return [left, right]; } else { const num = BigInt(stone); const newNum = num * 2024n; return [newNum.toString()]; } } // Function to simulate blinks function simulateBlinks(stoneCounts, blinks) { for (let i = 0; i < blinks; i++) { const newStoneCounts = {}; for (const stone in stoneCounts) { const count = stoneCounts[stone]; const transformedStones = transformStone(stone); for (const newStone of transformedStones) { newStoneCounts[newStone] = (newStoneCounts[newStone] || 0n) + count; } } stoneCounts = newStoneCounts; } return stoneCounts; } // Function to calculate the total number of stones function calculateTotalStones(stoneCounts) { return Object.values(stoneCounts).reduce((total, count) => total + count, 0n); } // Main function function main() { const filePath = 'input.txt'; const blinks = 75; // Read and parse the input const stones = readInput(filePath); // Initialize stone counts let stoneCounts = initializeStoneCounts(stones); // Simulate blinks stoneCounts = simulateBlinks(stoneCounts, blinks); // Calculate and print the total number of stones const totalStones = calculateTotalStones(stoneCounts); console.log(totalStones.toString()); } // Run the program 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. 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,"const fs = require('fs'); let stones = fs.readFileSync('input.txt', 'utf-8').trim().split(/\s+/); const blinks = 75; let stoneCounts = {}; // Initialize the stone counts for (let stone of stones) { stoneCounts[stone] = (stoneCounts[stone] || 0n) + 1n; } for (let i = 0; i < blinks; i++) { let newStoneCounts = {}; for (let stone in stoneCounts) { let count = stoneCounts[stone]; if (stone === '0') { newStoneCounts['1'] = (newStoneCounts['1'] || 0n) + count; } else if (stone.length % 2 === 0) { let half = stone.length / 2; let left = stone.slice(0, half).replace(/^0+/, '') || '0'; let right = stone.slice(half).replace(/^0+/, '') || '0'; newStoneCounts[left] = (newStoneCounts[left] || 0n) + count; newStoneCounts[right] = (newStoneCounts[right] || 0n) + count; } else { let num = BigInt(stone); let newNum = num * 2024n; let newStone = newNum.toString(); newStoneCounts[newStone] = (newStoneCounts[newStone] || 0n) + count; } } stoneCounts = newStoneCounts; } let totalStones = Object.values(stoneCounts).reduce((a, b) => a + b, 0n); 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. 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,"const fs = require('fs'); function main() { const input = fs.readFileSync('input.txt', 'utf8'); const lines = input.split('\n'); const grid = []; for (let line of lines) { if (line.startsWith('#') || !line.trim()) { continue; } grid.push(line.trim().split('')); } const rows = grid.length; const cols = grid[0].length; const visited = Array.from(Array(rows), () => Array(cols).fill(false)); let totalPrice = 0; for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { if (!visited[i][j]) { const plantType = grid[i][j]; let area = 0; let perimeter = 0; const queue = []; queue.push([i, j]); visited[i][j] = true; while (queue.length > 0) { const [ci, cj] = queue.shift(); area += 1; const directions = [[-1,0], [1,0], [0,-1], [0,1]]; for (const [dx, dy] of directions) { const ni = ci + dx; const nj = cj + dy; if (ni < 0 || nj < 0 || ni >= rows || nj >= cols) { perimeter += 1; } else if (grid[ni][nj] !== plantType) { perimeter += 1; } else if (!visited[ni][nj]) { queue.push([ni, nj]); visited[ni][nj] = true; } } } totalPrice += area * perimeter; } } } console.log(totalPrice); } 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. 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,"const fs = require('fs'); // Read and parse the input file const readInput = filename => fs.readFileSync(filename, 'utf8') .split('\n') .filter(line => line.trim() && !line.startsWith('#')) .map(line => line.trim().split('')); // Calculate the area and perimeter of a region const calculateAreaAndPerimeter = (grid, visited, i, j, plantType) => { const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; const queue = [[i, j]]; visited[i][j] = true; let area = 0; let perimeter = 0; while (queue.length > 0) { const [ci, cj] = queue.shift(); area += 1; directions.forEach(([dx, dy]) => { const ni = ci + dx; const nj = cj + dy; if (ni < 0 || nj < 0 || ni >= grid.length || nj >= grid[0].length || grid[ni][nj] !== plantType) { perimeter += 1; } else if (!visited[ni][nj]) { visited[ni][nj] = true; queue.push([ni, nj]); } }); } return { area, perimeter }; }; // Explore the entire grid and calculate the total cost const calculateTotalCost = grid => { const rows = grid.length; const cols = grid[0].length; const visited = Array.from({ length: rows }, () => Array(cols).fill(false)); const getUnvisitedPlot = () => { for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { if (!visited[i][j]) { return [i, j]; } } } return null; }; const totalCost = [...Array(rows)].map(() => Array(cols).fill(0)).reduce((total, _, rowIndex) => { return total + [...Array(cols)].reduce((rowTotal, _, colIndex) => { if (!visited[rowIndex][colIndex]) { const plantType = grid[rowIndex][colIndex]; const { area, perimeter } = calculateAreaAndPerimeter(grid, visited, rowIndex, colIndex, plantType); return rowTotal + area * perimeter; } return rowTotal; }, 0); }, 0); return totalCost; }; // Main function to orchestrate the logic const main = () => { const grid = readInput('input.txt'); const totalCost = calculateTotalCost(grid); console.log(totalCost); }; 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. 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,"const fs = require('fs'); // Read and parse the input file function readInput(filename) { return fs.readFileSync(filename, 'utf8') .split('\n') .filter(line => line.trim() && !line.startsWith('#')) .map(line => line.trim().split('')); } // Create a visited grid initialized to false function createVisitedGrid(rows, cols) { return Array.from({ length: rows }, () => Array(cols).fill(false)); } // Perform breadth-first search to calculate area and perimeter function exploreRegion(grid, visited, startRow, startCol, plantType) { const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; const queue = [[startRow, startCol]]; visited[startRow][startCol] = true; let area = 0; let perimeter = 0; while (queue.length > 0) { const [row, col] = queue.shift(); area += 1; directions.forEach(([dx, dy]) => { const newRow = row + dx; const newCol = col + dy; if (newRow < 0 || newCol < 0 || newRow >= grid.length || newCol >= grid[0].length || grid[newRow][newCol] !== plantType) { perimeter += 1; } else if (!visited[newRow][newCol]) { visited[newRow][newCol] = true; queue.push([newRow, newCol]); } }); } return { area, perimeter }; } // Calculate the total cost by iterating over all unvisited plots function calculateTotalCost(grid) { const rows = grid.length; const cols = grid[0].length; const visited = createVisitedGrid(rows, cols); let totalCost = 0; for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { if (!visited[i][j]) { const plantType = grid[i][j]; const { area, perimeter } = exploreRegion(grid, visited, i, j, plantType); totalCost += area * perimeter; } } } return totalCost; } // Main function to execute the logic function main() { const grid = readInput('input.txt'); const totalCost = calculateTotalCost(grid); console.log(totalCost); } 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. 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,"const fs = require('fs'); class PlantGrid { constructor(filename) { this.grid = this.readInput(filename); this.rows = this.grid.length; this.cols = this.grid[0].length; this.visited = Array.from({ length: this.rows }, () => Array(this.cols).fill(false)); this.totalCost = 0; } // Read and parse the input file readInput(filename) { return fs.readFileSync(filename, 'utf8') .split('\n') .filter(line => line.trim() && !line.startsWith('#')) .map(line => line.trim().split('')); } // Explore a plot to calculate area and perimeter explorePlot(i, j, plantType) { const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; const queue = [[i, j]]; this.visited[i][j] = true; let area = 0; let perimeter = 0; while (queue.length > 0) { const [ci, cj] = queue.shift(); area += 1; directions.forEach(([dx, dy]) => { const ni = ci + dx; const nj = cj + dy; if (ni < 0 || nj < 0 || ni >= this.rows || nj >= this.cols || this.grid[ni][nj] !== plantType) { perimeter += 1; } else if (!this.visited[ni][nj]) { this.visited[ni][nj] = true; queue.push([ni, nj]); } }); } return { area, perimeter }; } // Calculate the total cost by exploring the grid calculateTotalCost() { for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.cols; j++) { if (!this.visited[i][j]) { const plantType = this.grid[i][j]; const { area, perimeter } = this.explorePlot(i, j, plantType); this.totalCost += area * perimeter; } } } return this.totalCost; } } // Main function to orchestrate the logic function main() { const plantGrid = new PlantGrid('input.txt'); const totalCost = plantGrid.calculateTotalCost(); console.log(totalCost); } 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. 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,"const fs = require('fs'); // Read input and parse into grid function readInput(filename) { const input = fs.readFileSync(filename, 'utf8'); return input.split('\n').filter(line => line.trim() && !line.startsWith('#')) .map(line => line.trim().split('')); } // Explore a plot and calculate its area and perimeter function explorePlot(grid, visited, i, j, plantType) { const rows = grid.length; const cols = grid[0].length; let area = 0; let perimeter = 0; const queue = [[i, j]]; visited[i][j] = true; const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; while (queue.length > 0) { const [ci, cj] = queue.shift(); area += 1; for (const [dx, dy] of directions) { const ni = ci + dx; const nj = cj + dy; if (ni < 0 || nj < 0 || ni >= rows || nj >= cols || grid[ni][nj] !== plantType) { perimeter += 1; } else if (!visited[ni][nj]) { visited[ni][nj] = true; queue.push([ni, nj]); } } } return { area, perimeter }; } // Main function to calculate total price function calculateTotalPrice(grid) { const rows = grid.length; const cols = grid[0].length; const visited = Array.from(Array(rows), () => Array(cols).fill(false)); let totalPrice = 0; for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { if (!visited[i][j]) { const plantType = grid[i][j]; const { area, perimeter } = explorePlot(grid, visited, i, j, plantType); totalPrice += area * perimeter; } } } return totalPrice; } // Main entry point function main() { const grid = readInput('input.txt'); const totalPrice = calculateTotalPrice(grid); console.log(totalPrice); } 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. 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,"// solution for https://adventofcode.com/2024/day/12 part 2 ""use strict"" const input = Deno.readTextFileSync(""day12-input.txt"").trim() const garden = [ ] const processed = [ ] var width = 0 var height = 0 var currentSymbol = """" var areaSize = 0 var topBorderPlots = { } // by row var bottomBorderPlots = { } // by row var leftBorderPlots = { } // by col var rightBorderPlots = { } // by col var result = 0 function main() { processInput() for (let row = 0; row < height; row++) { for (let col = 0; col < width; col++) { processPlot(row, col) } } console.log(""the answer is"", result) } function processInput() { const lines = input.split(""\n"") for (const line of lines) { garden.push(line.trim()) } height = garden.length width = garden[0].length for (const line of garden) { const doneLine = [ ] processed.push(doneLine) for (const symbol of line) { doneLine.push(false) } } } /////////////////////////////////////////////////////////////////////////////// function processPlot(row, col) { if (processed[row][col]) { return } processed[row][col] = true currentSymbol = garden[row][col] areaSize = 0 topBorderPlots = { } bottomBorderPlots = { } leftBorderPlots = { } rightBorderPlots = { } walkFrom(row, col) result += areaSize * findNumberOfSides() } function walkFrom(row, col) { const pointsToWalk = [ createPoint(row, col) ] while (true) { const point = pointsToWalk.pop() if (point == undefined) { return } areaSize += 1 const row = point.row const col = point.col tryCatchNeighbor(row, col, -1, 0, pointsToWalk) tryCatchNeighbor(row, col, +1, 0, pointsToWalk) tryCatchNeighbor(row, col, 0, -1, pointsToWalk) tryCatchNeighbor(row, col, 0, +1, pointsToWalk) } } function tryCatchNeighbor(baseRow, baseCol, deltaRow, deltaCol, pointsToWalk) { const neighborRow = baseRow + deltaRow const neighborCol = baseCol + deltaCol if (neighborRow < 0) { pushToTopBorderPlots(baseRow, baseCol); return } if (neighborCol < 0) { pushToLeftBorderPlots(baseRow, baseCol); return } if (neighborRow == height) { pushToBottomBorderPlots(baseRow, baseCol); return } if (neighborCol == width) { pushToRightBorderPlots(baseRow, baseCol); return } if (garden[neighborRow][neighborCol] != currentSymbol) { if (neighborRow < baseRow) { pushToTopBorderPlots(baseRow, baseCol); return } if (neighborCol < baseCol) { pushToLeftBorderPlots(baseRow, baseCol); return } if (neighborRow > baseRow) { pushToBottomBorderPlots(baseRow, baseCol); return } if (neighborCol > baseCol) { pushToRightBorderPlots(baseRow, baseCol); return } } if (processed[neighborRow][neighborCol]) { return } processed[neighborRow][neighborCol] = true pointsToWalk.push(createPoint(neighborRow, neighborCol)) } function createPoint(row, col) { return { ""row"": row, ""col"": col } } function pushToTopBorderPlots(row, col) { if (topBorderPlots[row] == undefined) { topBorderPlots[row] = [ ] } topBorderPlots[row].push(col) } function pushToBottomBorderPlots(row, col) { if (bottomBorderPlots[row] == undefined) { bottomBorderPlots[row] = [ ] } bottomBorderPlots[row].push(col) } function pushToLeftBorderPlots(row, col) { if (leftBorderPlots[col] == undefined) { leftBorderPlots[col] = [ ] } leftBorderPlots[col].push(row) } function pushToRightBorderPlots(row, col) { if (rightBorderPlots[col] == undefined) { rightBorderPlots[col] = [ ] } rightBorderPlots[col].push(row) } /////////////////////////////////////////////////////////////////////////////// function findNumberOfSides() { let sides = 0 for (const dict of [ topBorderPlots, bottomBorderPlots, leftBorderPlots, rightBorderPlots ]) { sides += findNumberOfSidesThis(dict) } return sides } function findNumberOfSidesThis(dict) { let sides = 0 for (const list of Object.values(dict)) { sides += findNumberOfSidesThisList(list) } return sides } function findNumberOfSidesThisList(list) { list.sort(function (a, b) { return a - b }) const newList = [ ] while (true) { const candidate = list.shift() if (candidate == undefined) { break } const previous = newList.at(-1) if (previous == undefined) { newList.push(candidate); continue } if (candidate - previous == 1) { newList.pop() } // removing neighbor on same same side newList.push(candidate) } return newList.length } console.time(""execution time"") main() 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. 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,"const fs = require('fs'); // Read and prepare the input data const data = fs.readFileSync('input.txt', 'utf-8').split('\n'); const xmax = data[0].length; const ymax = data.length; const totalSeen = new Set(); // Helper function to count corners around a given plant at coordinates (x, y) const countCorners = (plant, x, y) => { const up = y > 0 ? data[y - 1][x] : null; const down = y < ymax - 1 ? data[y + 1][x] : null; const left = x > 0 ? data[y][x - 1] : null; const right = x < xmax - 1 ? data[y][x + 1] : null; let corners = 0; const count = [up, down, left, right].filter(i => i === plant).length; if (count === 0) return 4; if (count === 1) return 2; if (count === 2) { if ((left === right && left === plant) || (up === down && up === plant)) return 0; corners += 1; } // Check for corner conditions if (up === left && up === plant && y > 0 && x > 0 && data[y - 1][x - 1] !== plant) corners += 1; if (up === right && up === plant && y > 0 && x < xmax - 1 && data[y - 1][x + 1] !== plant) corners += 1; if (down === left && down === plant && y < ymax - 1 && x > 0 && data[y + 1][x - 1] !== plant) corners += 1; if (down === right && down === plant && y < ymax - 1 && x < xmax - 1 && data[y + 1][x + 1] !== plant) corners += 1; return corners; }; // Function to calculate the area and perimeter of a plot at coordinates (x, y) const calcPlot = (x, y) => { const plant = data[y][x]; let perimeter = 0; let area = 0; let corners = 0; const seen = new Set(); const queue = [[x, y]]; while (queue.length > 0) { const [xi, yi] = queue.shift(); if (seen.has(`${xi},${yi}`)) continue; if (xi < 0 || xi >= xmax || yi < 0 || yi >= ymax || data[yi][xi] !== plant) { perimeter += 1; continue; } seen.add(`${xi},${yi}`); area += 1; corners += countCorners(plant, xi, yi); // Add neighboring coordinates to the queue queue.push([xi + 1, yi]); queue.push([xi - 1, yi]); queue.push([xi, yi + 1]); queue.push([xi, yi - 1]); } // Update the global totalSeen set seen.forEach(loc => totalSeen.add(loc)); return area * corners; }; // Main loop to calculate the total cost let totalCost = 0; for (let yi = 0; yi < ymax; yi++) { for (let xi = 0; xi < xmax; xi++) { if (totalSeen.has(`${xi},${yi}`)) continue; totalCost += calcPlot(xi, yi); } } 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. 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,"const fs = require('fs'); // Read the input file and split it into lines const grid = fs.readFileSync('input.txt', 'utf-8').split('\n').map(line => line.split('')); function addToRegionFrom(grid, loc, region, visited) { region.add(loc.toString()); visited.add(loc.toString()); const neighbors = [ [loc[0] - 1, loc[1]], [loc[0] + 1, loc[1]], [loc[0], loc[1] - 1], [loc[0], loc[1] + 1] ]; const validNeighbors = neighbors.filter(pt => pt[0] >= 0 && pt[0] < grid.length && pt[1] >= 0 && pt[1] < grid[0].length); for (const neighbor of validNeighbors) { if (grid[loc[0]][loc[1]] === grid[neighbor[0]][neighbor[1]] && !visited.has(neighbor.toString())) { addToRegionFrom(grid, neighbor, region, visited); } } } function getArea(region) { return region.size; } function getSides(region) { let sides = 0; const visitedEdges = new Set(); const sortedRegion = Array.from(region).sort(); for (const locStr of sortedRegion) { const loc = locStr.split(',').map(Number); const above = [loc[0] - 1, loc[1]]; if (!region.has(above.toString())) { visitedEdges.add(above.toString() + '-bottom'); if (!visitedEdges.has([above[0], above[1] - 1].toString() + '-bottom') && !visitedEdges.has([above[0], above[1] + 1].toString() + '-bottom')) { sides++; } } const below = [loc[0] + 1, loc[1]]; if (!region.has(below.toString())) { visitedEdges.add(below.toString() + '-top'); if (!visitedEdges.has([below[0], below[1] - 1].toString() + '-top') && !visitedEdges.has([below[0], below[1] + 1].toString() + '-top')) { sides++; } } const left = [loc[0], loc[1] - 1]; if (!region.has(left.toString())) { visitedEdges.add(left.toString() + '-right'); if (!visitedEdges.has([left[0] - 1, left[1]].toString() + '-right') && !visitedEdges.has([left[0] + 1, left[1]].toString() + '-right')) { sides++; } } const right = [loc[0], loc[1] + 1]; if (!region.has(right.toString())) { visitedEdges.add(right.toString() + '-left'); if (!visitedEdges.has([right[0] - 1, right[1]].toString() + '-left') && !visitedEdges.has([right[0] + 1, right[1]].toString() + '-left')) { sides++; } } } return sides; } function getCorners(region) { let corners = 0; for (const locStr of region) { const loc = locStr.split(',').map(Number); const outerTopLeft = [[0, -1, false], [-1, 0, false]]; const outerTopRight = [[0, 1, false], [-1, 0, false]]; const outerBottomRight = [[0, 1, false], [1, 0, false]]; const outerBottomLeft = [[0, -1, false], [1, 0, false]]; const innerTopLeft = [[0, 1, true], [1, 0, true], [1, 1, false]]; const innerTopRight = [[0, -1, true], [1, 0, true], [1, -1, false]]; const innerBottomRight = [[0, -1, true], [-1, 0, true], [-1, -1, false]]; const innerBottomLeft = [[0, 1, true], [-1, 0, true], [-1, 1, false]]; const allNeighbors = [ outerTopLeft, outerTopRight, outerBottomRight, outerBottomLeft, innerTopLeft, innerTopRight, innerBottomRight, innerBottomLeft ]; corners += allNeighbors.reduce((acc, neighbor) => { return acc + (neighbor.every(([dx, dy, isInner]) => { const neighborLoc = [loc[0] + dx, loc[1] + dy]; return (region.has(neighborLoc.toString()) === isInner); }) ? 1 : 0); }, 0); } return corners; } function getPerimeter(region) { let perimeter = 0; for (const locStr of region) { const loc = locStr.split(',').map(Number); const neighbors = [ [loc[0] - 1, loc[1]], [loc[0] + 1, loc[1]], [loc[0], loc[1] - 1], [loc[0], loc[1] + 1] ]; perimeter += neighbors.filter(pt => !region.has(pt.toString())).length; } return perimeter; } // Main logic let visited = new Set(); let regions = []; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (!visited.has([i, j].toString())) { let region = new Set(); addToRegionFrom(grid, [i, j], region, visited); regions.push(region); } visited.add([i, j].toString()); } } let totalPrice = 0; for (const region of regions) { const price = getArea(region) * getCorners(region); totalPrice += price; } 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. 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,"const fs = require('fs'); // Read the input file and split it into lines const data = fs.readFileSync('input.txt', 'utf-8').split('\n'); const xmax = data[0].length; const ymax = data.length; const totalSeen = new Set(); function countCorners(plant, x, y) { const up = y - 1 >= 0 ? data[y - 1][x] : null; const down = y + 1 < ymax ? data[y + 1][x] : null; const left = x - 1 >= 0 ? data[y][x - 1] : null; const right = x + 1 < xmax ? data[y][x + 1] : null; let count = [up, down, left, right].filter(i => i === plant).length; let corners = 0; if (count === 0) return 4; if (count === 1) return 2; if (count === 2) { if ((left === right && left === plant) || (up === down && up === plant)) return 0; corners += 1; } if (up === left && up === plant && y - 1 >= 0 && x - 1 >= 0 && data[y - 1][x - 1] !== plant) corners += 1; if (up === right && up === plant && y - 1 >= 0 && x + 1 < xmax && data[y - 1][x + 1] !== plant) corners += 1; if (down === left && down === plant && y + 1 < ymax && x - 1 >= 0 && data[y + 1][x - 1] !== plant) corners += 1; if (down === right && down === plant && y + 1 < ymax && x + 1 < xmax && data[y + 1][x + 1] !== plant) corners += 1; return corners; } function calcPlot(x, y) { const plant = data[y][x]; let perimeter = 0; let area = 0; let corners = 0; const seen = new Set(); const q = []; q.push([x, y]); while (q.length > 0) { const [xi, yi] = q.shift(); if (seen.has(`${xi},${yi}`)) continue; if (xi < 0 || xi >= xmax || yi < 0 || yi >= ymax || data[yi][xi] !== plant) { perimeter += 1; continue; } seen.add(`${xi},${yi}`); area += 1; corners += countCorners(plant, xi, yi); q.push([xi + 1, yi]); q.push([xi - 1, yi]); q.push([xi, yi + 1]); q.push([xi, yi - 1]); } // Add the seen cells to the totalSeen set seen.forEach(loc => totalSeen.add(loc)); return area * corners; } let total = 0; for (let yi = 0; yi < ymax; yi++) { for (let xi = 0; xi < xmax; xi++) { if (totalSeen.has(`${xi},${yi}`)) continue; total += calcPlot(xi, yi); } } 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. 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,"const fs = require('fs'); // Read the input file and split it into lines const data = fs.readFileSync('input.txt', 'utf-8').split('\n'); const xmax = data[0].length; const ymax = data.length; const totalSeen = new Set(); function countCorners(plant, x, y) { const up = y - 1 >= 0 ? data[y - 1][x] : null; const down = y + 1 < ymax ? data[y + 1][x] : null; const left = x - 1 >= 0 ? data[y][x - 1] : null; const right = x + 1 < xmax ? data[y][x + 1] : null; let count = [up, down, left, right].filter(i => i === plant).length; let corners = 0; if (count === 0) return 4; if (count === 1) return 2; if (count === 2) { if ((left === right && left === plant) || (up === down && up === plant)) return 0; corners += 1; } if (up === left && up === plant && y - 1 >= 0 && x - 1 >= 0 && data[y - 1][x - 1] !== plant) corners += 1; if (up === right && up === plant && y - 1 >= 0 && x + 1 < xmax && data[y - 1][x + 1] !== plant) corners += 1; if (down === left && down === plant && y + 1 < ymax && x - 1 >= 0 && data[y + 1][x - 1] !== plant) corners += 1; if (down === right && down === plant && y + 1 < ymax && x + 1 < xmax && data[y + 1][x + 1] !== plant) corners += 1; return corners; } function calcPlot(x, y) { const plant = data[y][x]; let perimeter = 0; let area = 0; let corners = 0; const seen = new Set(); const q = []; q.push([x, y]); while (q.length > 0) { const [xi, yi] = q.shift(); if (seen.has(`${xi},${yi}`)) continue; if (xi < 0 || xi >= xmax || yi < 0 || yi >= ymax || data[yi][xi] !== plant) { perimeter += 1; continue; } seen.add(`${xi},${yi}`); area += 1; corners += countCorners(plant, xi, yi); q.push([xi + 1, yi]); q.push([xi - 1, yi]); q.push([xi, yi + 1]); q.push([xi, yi - 1]); } seen.forEach(loc => totalSeen.add(loc)); return area * corners; } let total = 0; for (let yi = 0; yi < ymax; yi++) { for (let xi = 0; xi < xmax; xi++) { if (totalSeen.has(`${xi},${yi}`)) continue; total += calcPlot(xi, yi); } } 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. 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); let totalTokens = 0; input.forEach(machine => { const lines = machine.split('\n'); const aButton = lines[0].match(/-?\d+/g).map(Number); const bButton = lines[1].match(/-?\d+/g).map(Number); const prize = lines[2].match(/-?\d+/g).map(Number); let minTokens = Infinity; for (let a = 0; a <= 100; a++) { for (let b = 0; b <= 100; b++) { const x = a * aButton[0] + b * bButton[0]; const y = a * aButton[1] + b * bButton[1]; if (x === prize[0] && y === prize[1]) { const tokens = a * 3 + b * 1; if (tokens < minTokens) { minTokens = tokens; } } } } if (minTokens !== Infinity) { totalTokens += minTokens; } }); 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. 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,"const fs = require('fs'); function parseInput(data) { const machines = []; const lines = data.split('\n').filter(line => line.trim() !== ''); for (let i = 0; i < lines.length; i += 3) { const buttonA = lines[i].match(/Button A: X\+(\d+), Y\+(\d+)/); const buttonB = lines[i+1].match(/Button B: X\+(\d+), Y\+(\d+)/); const prize = lines[i+2].match(/Prize: X=(\d+), Y=(\d+)/); if (buttonA && buttonB && prize) { machines.push({ A: {x: parseInt(buttonA[1]), y: parseInt(buttonA[2]), cost: 3}, B: {x: parseInt(buttonB[1]), y: parseInt(buttonB[2]), cost: 1}, prize: {x: parseInt(prize[1]), y: parseInt(prize[2])} }); } } return machines; } function findMinCost(machine) { let minCost = Infinity; for (let a = 0; a <= 100; a++) { for (let b = 0; b <= 100; b++) { if ( machine.A.x * a + machine.B.x * b === machine.prize.x && machine.A.y * a + machine.B.y * b === machine.prize.y ) { const cost = machine.A.cost * a + machine.B.cost * b; if (cost < minCost) { minCost = cost; } } } } return minCost; } function calculateTotalMinTokens(filePath) { const data = fs.readFileSync(filePath, 'utf-8'); const machines = parseInput(data); let totalTokens = 0; machines.forEach(machine => { const cost = findMinCost(machine); if (cost !== Infinity) { totalTokens += cost; } }); return totalTokens; } const total = calculateTotalMinTokens('input.txt'); 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. 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,"const fs = require('fs'); // Parse input data and return machine configurations const parseMachineData = (data) => { return data.split('\n') .filter(line => line.trim() !== '') .reduce((machines, line, index, lines) => { if (index % 3 === 0) { const buttonA = lines[index].match(/Button A: X\+(\d+), Y\+(\d+)/); const buttonB = lines[index + 1].match(/Button B: X\+(\d+), Y\+(\d+)/); const prize = lines[index + 2].match(/Prize: X=(\d+), Y=(\d+)/); if (buttonA && buttonB && prize) { machines.push({ A: { x: parseInt(buttonA[1]), y: parseInt(buttonA[2]), cost: 3 }, B: { x: parseInt(buttonB[1]), y: parseInt(buttonB[2]), cost: 1 }, prize: { x: parseInt(prize[1]), y: parseInt(prize[2]) }, }); } } return machines; }, []); }; // Calculate the minimum cost to win the prize for a given machine const calculateMinCostForMachine = ({ A, B, prize }) => { let minCost = Infinity; for (let a = 0; a <= 100; a++) { for (let b = 0; b <= 100; b++) { const xPos = A.x * a + B.x * b; const yPos = A.y * a + B.y * b; if (xPos === prize.x && yPos === prize.y) { const cost = A.cost * a + B.cost * b; minCost = Math.min(minCost, cost); } } } return minCost === Infinity ? null : minCost; }; // Main function to read the input and calculate the total minimum tokens const calculateTotalTokens = (filePath) => { const data = fs.readFileSync(filePath, 'utf-8'); const machines = parseMachineData(data); return machines.reduce((totalTokens, machine) => { const cost = calculateMinCostForMachine(machine); return cost ? totalTokens + cost : totalTokens; }, 0); }; const totalTokens = calculateTotalTokens('input.txt'); 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. 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,"const fs = require('fs'); class ClawMachine { constructor(aButton, bButton, prize) { this.aButton = aButton; this.bButton = bButton; this.prize = prize; } findMinimumTokens() { let minTokens = Infinity; for (let a = 0; a <= 100; a++) { for (let b = 0; b <= 100; b++) { const x = a * this.aButton[0] + b * this.bButton[0]; const y = a * this.aButton[1] + b * this.bButton[1]; if (x === this.prize[0] && y === this.prize[1]) { const tokens = a * 3 + b * 1; minTokens = Math.min(minTokens, tokens); } } } return minTokens !== Infinity ? minTokens : 0; } } function parseInput(data) { return data.split('\n\n').map(machine => { const [aButton, bButton, prize] = machine.split('\n').map(line => line.match(/-?\d+/g).map(Number) ); return new ClawMachine(aButton, bButton, prize); }); } function main() { const data = fs.readFileSync('input.txt', 'utf8').trim(); const machines = parseInput(data); const totalTokens = machines.reduce((sum, machine) => sum + machine.findMinimumTokens(), 0); console.log(totalTokens); } 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. 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,"const fs = require('fs'); function calculateMinimumTokens(machines) { return machines.reduce((totalTokens, machine) => { const [aButton, bButton, prize] = machine.split('\n').map(line => line.match(/-?\d+/g).map(Number) ); let minTokens = Infinity; for (let aPresses = 0; aPresses <= 100; aPresses++) { for (let bPresses = 0; bPresses <= 100; bPresses++) { const xPosition = aPresses * aButton[0] + bPresses * bButton[0]; const yPosition = aPresses * aButton[1] + bPresses * bButton[1]; if (xPosition === prize[0] && yPosition === prize[1]) { const tokensSpent = aPresses * 3 + bPresses * 1; minTokens = Math.min(minTokens, tokensSpent); } } } return totalTokens + (minTokens !== Infinity ? minTokens : 0); }, 0); } const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); const result = calculateMinimumTokens(input); 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. 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,"const fs = require('fs'); function parseInput(data) { const machines = []; const lines = data.split('\n').filter(line => line.trim() !== ''); for (let i = 0; i < lines.length; i += 3) { const buttonA = lines[i].match(/Button A: X\+(\d+), Y\+(\d+)/); const buttonB = lines[i+1].match(/Button B: X\+(\d+), Y\+(\d+)/); const prize = lines[i+2].match(/Prize: X=(\d+), Y=(\d+)/); if (buttonA && buttonB && prize) { machines.push({ A: {x: parseInt(buttonA[1]), y: parseInt(buttonA[2]), cost: 3}, B: {x: parseInt(buttonB[1]), y: parseInt(buttonB[2]), cost: 1}, prize: {x: parseInt(prize[1]) + 10000000000000, y: parseInt(prize[2]) + 10000000000000} }); } } return machines; } function findMinCost(machine) { const { A, B, prize } = machine; const Xp = prize.x; const Yp = prize.y; const det = A.x * B.y - A.y * B.x; if (det === 0) { return Infinity; } // Calculate determinants for Cramer's rule const detA = Xp * B.y - Yp * B.x; const detB = A.x * Yp - A.y * Xp; if (det === 0) return Infinity; const a = detA / det; const b = detB / det; if (!Number.isInteger(a) || !Number.isInteger(b) || a < 0 || b < 0) { return Infinity; } return A.cost * a + B.cost * b; } function calculateTotalMinTokens(filePath) { const data = fs.readFileSync(filePath, 'utf-8'); const machines = parseInput(data); let totalTokens = 0; machines.forEach(machine => { const cost = findMinCost(machine); if (cost !== Infinity) { totalTokens += cost; } }); return totalTokens; } const total = calculateTotalMinTokens('input.txt'); 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. 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,"const fs = require('fs'); function solveClawMachines(input, partTwo = false) { const machines = input.split('\n\n').map(machine => { const [aButton, bButton, prize] = machine.split('\n').map(line => line.match(/-?\d+/g).map(Number) ); return { aButton, bButton, prize }; }); let totalTokens = 0; machines.forEach(({ aButton, bButton, prize }) => { if (partTwo) { prize[0] += 10000000000000; prize[1] += 10000000000000; } let minTokens = Infinity; // Use a mathematical approach to solve the system of equations: // a * aButton[0] + b * bButton[0] = prize[0] // a * aButton[1] + b * bButton[1] = prize[1] const determinant = aButton[0] * bButton[1] - aButton[1] * bButton[0]; if (determinant !== 0) { const a = (prize[0] * bButton[1] - prize[1] * bButton[0]) / determinant; const b = (aButton[0] * prize[1] - aButton[1] * prize[0]) / determinant; if (Number.isInteger(a) && Number.isInteger(b) && a >= 0 && b >= 0) { const tokens = a * 3 + b * 1; minTokens = Math.min(minTokens, tokens); } } if (minTokens !== Infinity) { totalTokens += minTokens; } }); return totalTokens; } const input = fs.readFileSync('input.txt', 'utf8').trim(); // Part One console.log(""Part One:"", solveClawMachines(input)); // Part Two 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. 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,"const fs = require('fs'); const { log } = require('console'); // Read and parse the input file const readAndParseInput = (filePath) => { return fs.readFileSync(filePath, 'utf-8') .split('\n\n') .map(machine => machine .split('\n') .map(line => line .split(': ') .slice(1) .map(p => p.split(', ')) ) ); }; // Brute-force function to find the minimum cost const bruteForce = (ax, ay, bx, by, pricex, pricey) => { let minCosts = Infinity; for (let i = 0; i <= 100; i++) { for (let j = 0; j <= 100; j++) { if (ax * i + bx * j === pricex && ay * i + by * j === pricey) { const costs = i * 3 + j; minCosts = Math.min(minCosts, costs); } } } return minCosts; }; // Extract machine parameters from raw data const extractMachineParams = (machine) => { const [aRaw, bRaw, prizeRaw] = machine.flat(); return { ax: parseInt(aRaw[0].split('+')[1]), ay: parseInt(aRaw[1].split('+')[1]), bx: parseInt(bRaw[0].split('+')[1]), by: parseInt(bRaw[1].split('+')[1]), prizex: parseInt(prizeRaw[0].split('=')[1]), prizey: parseInt(prizeRaw[1].split('=')[1]), }; }; // Calculate part 1 solution const calculatePart1 = (machines) => { let totalCost = 0; machines.forEach(machine => { const { ax, ay, bx, by, prizex, prizey } = extractMachineParams(machine); const cost = bruteForce(ax, ay, bx, by, prizex, prizey); if (cost !== Infinity) { totalCost += cost; } }); return totalCost; }; // Calculate part 2 solution const calculatePart2 = (machines) => { let totalCost = 0; machines.forEach(machine => { const { ax, ay, bx, by, prizex, prizey } = extractMachineParams(machine); const adjustedPrizex = prizex + 10000000000000; const adjustedPrizey = prizey + 10000000000000; const ca = (adjustedPrizex * by - adjustedPrizey * bx) / (ax * by - ay * bx); const cb = (adjustedPrizex - ax * ca) / bx; if (ca % 1 === 0 && cb % 1 === 0) { totalCost += ca * 3 + cb; } }); return totalCost; }; // Main function const main = () => { const machines = readAndParseInput('input.txt'); const part1 = calculatePart1(machines); log(`Part 1: ${part1}`); const part2 = calculatePart2(machines); log(`Part 2: ${part2}`); }; // Run the program 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. 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,"const fs = require('fs'); const {log} = require('console'); const machines = fs.readFileSync('input.txt', 'utf-8') .split('\n\n') .map(machine => machine .split('\n') .map(line => line .split(': ') .slice(1) .map(p => p.split(', ')) )); function bruteForce(ax, ay, bx, by, pricex, pricey) { let minCosts = Infinity; for (let i = 0; i <= 100; i++) { for (let j = 0; j <= 100; j++) { if (ax * i + bx * j === pricex && ay * i + by * j === pricey) { const costs = i * 3 + j; minCosts = Math.min(minCosts, costs); } } } return minCosts; } let part1 = 0; machines.forEach(machine => { const [aRaw, bRaw, prizeRaw] = machine.flat(); const ax = parseInt(aRaw[0].split('+')[1]); const ay = parseInt(aRaw[1].split('+')[1]); const bx = parseInt(bRaw[0].split('+')[1]); const by = parseInt(bRaw[1].split('+')[1]); const prizex = parseInt(prizeRaw[0].split('=')[1]); const prizey = parseInt(prizeRaw[1].split('=')[1]); let sum = bruteForce(ax, ay, bx, by, prizex, prizey); if (sum !== Infinity) { part1 += sum; } }) console.log(part1); let part2 = 0; machines.forEach(machine => { const [aRaw, bRaw, prizeRaw] = machine.flat(); const ax = parseInt(aRaw[0].split('+')[1]); const ay = parseInt(aRaw[1].split('+')[1]); const bx = parseInt(bRaw[0].split('+')[1]); const by = parseInt(bRaw[1].split('+')[1]); const prizex = parseInt(prizeRaw[0].split('=')[1]) + 10000000000000; const prizey = parseInt(prizeRaw[1].split('=')[1]) + 10000000000000; // solution is not mine, but from hyperneutrino youtube channel. const ca = (prizex * by - prizey * bx) / (ax * by - ay * bx); const cb = (prizex - ax * ca) / bx; if (ca % 1 === 0 && cb % 1 === 0) { part2 += ca * 3 + cb; } }) 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. 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,"const fs = require('fs'); const { log } = require('console'); // Read and parse input file const parseMachines = (filePath) => { const data = fs.readFileSync(filePath, 'utf-8'); return data.split('\n\n').map(machine => machine.split('\n').map(line => line.split(': ').slice(1).map(p => p.split(', ')) ) ); }; const bruteForce = (ax, ay, bx, by, pricex, pricey) => { let minCosts = Infinity; for (let i = 0; i <= 100; i++) { for (let j = 0; j <= 100; j++) { if (ax * i + bx * j === pricex && ay * i + by * j === pricey) { const costs = i * 3 + j; minCosts = Math.min(minCosts, costs); } } } return minCosts; }; const calculatePart1 = (machines) => { let totalCost = 0; machines.forEach(machine => { const [aRaw, bRaw, prizeRaw] = machine.flat(); const ax = parseInt(aRaw[0].split('+')[1]); const ay = parseInt(aRaw[1].split('+')[1]); const bx = parseInt(bRaw[0].split('+')[1]); const by = parseInt(bRaw[1].split('+')[1]); const prizex = parseInt(prizeRaw[0].split('=')[1]); const prizey = parseInt(prizeRaw[1].split('=')[1]); let sum = bruteForce(ax, ay, bx, by, prizex, prizey); if (sum !== Infinity) { totalCost += sum; } }); return totalCost; }; const calculatePart2 = (machines) => { let totalCost = 0; machines.forEach(machine => { const [aRaw, bRaw, prizeRaw] = machine.flat(); const ax = parseInt(aRaw[0].split('+')[1]); const ay = parseInt(aRaw[1].split('+')[1]); const bx = parseInt(bRaw[0].split('+')[1]); const by = parseInt(bRaw[1].split('+')[1]); const prizex = parseInt(prizeRaw[0].split('=')[1]) + 1e13; const prizey = parseInt(prizeRaw[1].split('=')[1]) + 1e13; const ca = (prizex * by - prizey * bx) / (ax * by - ay * bx); const cb = (prizex - ax * ca) / bx; if (Number.isInteger(ca) && Number.isInteger(cb)) { totalCost += ca * 3 + cb; } }); return totalCost; }; // Main execution const machines = parseMachines('input.txt'); const part1 = calculatePart1(machines); const part2 = calculatePart2(machines); log(part1); 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. 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,"const fs = require('fs'); // Read input from file const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); // Parse input const robots = input.map(line => { const [p, v] = line.split(' '); const [x, y] = p.slice(2).split(',').map(Number); const [vx, vy] = v.slice(2).split(',').map(Number); return { x, y, vx, vy }; }); // Grid dimensions const width = 101; const height = 103; // Function to simulate robot movement function simulate(robots, seconds) { return robots.map(robot => { let x = (robot.x + robot.vx * seconds) % width; let y = (robot.y + robot.vy * seconds) % height; if (x < 0) x += width; if (y < 0) y += height; return { x, y }; }); } // Function to count robots in each quadrant function countQuadrants(positions) { const midX = Math.floor(width / 2); const midY = Math.floor(height / 2); const counts = [0, 0, 0, 0]; // [Q1, Q2, Q3, Q4] positions.forEach(pos => { if (pos.x > midX && pos.y < midY) counts[0]++; // Q1 else if (pos.x <= midX && pos.y < midY) counts[1]++; // Q2 else if (pos.x <= midX && pos.y >= midY) counts[2]++; // Q3 else if (pos.x > midX && pos.y >= midY) counts[3]++; // Q4 }); return counts; } // Part 1: Safety Factor after 100 seconds 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}`);",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. 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); const robots = input.map(line => { const parts = line.split(' '); const p = parts[0].slice(2).split(',').map(Number); const v = parts[1].slice(2).split(',').map(Number); return { px: p[0], py: p[1], vx: v[0], vy: v[1] }; }); let q1 = 0, q2 = 0, q3 = 0, q4 = 0; for (const robot of robots) { let x = robot.px + robot.vx * 100; x %= 101; if (x < 0) x += 101; let y = robot.py + robot.vy * 100; y %= 103; if (y < 0) y += 103; if (x === 50 || y === 51) { continue; } if (x < 50) { if (y < 51) { q1++; } else { q3++; } } else { if (y < 51) { q2++; } else { q4++; } } } const safetyFactor = q1 * q2 * q3 * q4; 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. 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,"const fs = require('fs'); // Helper function to parse robot data from a line function parseRobot(line) { const [position, velocity] = line.split(' '); const [px, py] = position.slice(2).split(',').map(Number); const [vx, vy] = velocity.slice(2).split(',').map(Number); return { px, py, vx, vy }; } // Helper function to calculate the new position after 100 steps function calculateNewPosition(robot) { const modX = (value) => ((value % 101) + 101) % 101; // Ensure positive modulo const modY = (value) => ((value % 103) + 103) % 103; const x = modX(robot.px + robot.vx * 100); const y = modY(robot.py + robot.vy * 100); return { x, y }; } // Helper function to determine the quadrant of a robot function determineQuadrant(x, y) { if (x === 50 || y === 51) return null; // Skip if on the boundary if (x < 50) { return y < 51 ? 'q1' : 'q3'; } else { return y < 51 ? 'q2' : 'q4'; } } // Main function to calculate the safety factor function calculateSafetyFactor(input) { const robots = input.map(parseRobot); const quadrantCounts = { q1: 0, q2: 0, q3: 0, q4: 0 }; for (const robot of robots) { const { x, y } = calculateNewPosition(robot); const quadrant = determineQuadrant(x, y); if (quadrant) { quadrantCounts[quadrant]++; } } return quadrantCounts.q1 * quadrantCounts.q2 * quadrantCounts.q3 * quadrantCounts.q4; } // Read input, process, and output the result const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); const safetyFactor = calculateSafetyFactor(input); 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. 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,"const fs = require('fs'); // Reading the input and parsing the robot data const parseRobots = (input) => { return input.map(line => { const [position, velocity] = line.split(' '); const px = position.slice(2).split(',').map(Number); const vx = velocity.slice(2).split(',').map(Number); return { px: px[0], py: px[1], vx: vx[0], vy: vx[1] }; }); }; // Calculating the quadrant count const calculateQuadrants = (robots, time = 100, width = 101, height = 103) => { let quadrants = { q1: 0, q2: 0, q3: 0, q4: 0 }; robots.forEach(robot => { const x = ((robot.px + robot.vx * time) % width + width) % width; const y = ((robot.py + robot.vy * time) % height + height) % height; if (x === 50 || y === 51) return; if (x < 50) { if (y < 51) quadrants.q1++; else quadrants.q3++; } else { if (y < 51) quadrants.q2++; else quadrants.q4++; } }); return quadrants; }; // Main execution const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); const robots = parseRobots(input); const quadrants = calculateQuadrants(robots); const safetyFactor = quadrants.q1 * quadrants.q2 * quadrants.q3 * quadrants.q4; 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. 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,"const fs = require('fs'); // Grid dimensions const width = 101; const height = 103; // Read input from 'input.txt' const input = fs.readFileSync('input.txt', 'utf-8'); // Parse the input const robots = input.trim().split('\n').map(line => { const parts = line.split(' '); const p = parts[0].slice(2).split(',').map(Number); const v = parts[1].slice(2).split(',').map(Number); return { x: p[0], y: p[1], vx: v[0], vy: v[1] }; }); // Simulate movement for 100 seconds robots.forEach(robot => { robot.x = (robot.x + robot.vx * 100) % width; robot.y = (robot.y + robot.vy * 100) % height; if (robot.x < 0) robot.x += width; if (robot.y < 0) robot.y += height; }); // Determine center lines const centerX = Math.floor(width / 2); const centerY = Math.floor(height / 2); // Initialize quadrant counts const quadrants = { Q1: 0, // Top-Left Q2: 0, // Top-Right Q3: 0, // Bottom-Left Q4: 0 // Bottom-Right }; // Count robots in each quadrant robots.forEach(robot => { if (robot.x === centerX || robot.y === centerY) return; // Ignore central lines if (robot.x < centerX && robot.y < centerY) quadrants.Q1++; else if (robot.x > centerX && robot.y < centerY) quadrants.Q2++; else if (robot.x < centerX && robot.y > centerY) quadrants.Q3++; else if (robot.x > centerX && robot.y > centerY) quadrants.Q4++; }); // Calculate safety factor const safetyFactor = quadrants.Q1 * quadrants.Q2 * quadrants.Q3 * quadrants.Q4; 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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import { readFileSync } from ""fs""; const input = readFileSync('input.txt', { encoding: 'utf-8' }) const width = 101 const height = 103 const robots = input.split(""\r\n"").filter(x => x).map(x => ({ pos: x.split("" "").at(0).split(""="").at(-1).split("","").map(x => +x).toReversed(), vel: x.split("" "").at(1).split(""="").at(-1).split("","").map(x => +x).toReversed() }) ) let matrix = Array.from({ length: height }).map(x => Array.from({ length: width }).map(x => ""."")) for (let i = 0; i < 100000; i++) { robots.forEach((x, r) => { let pos = x.pos matrix[pos[0]][pos[1]] = ""."" pos = [pos[0] + x.vel[0], pos[1] + x.vel[1]] if (pos[0] < 0) pos[0] = height + pos[0] if (pos[1] < 0) pos[1] = width + pos[1] if (pos[0] >= height) pos[0] %= height; if (pos[1] >= width) pos[1] %= width; matrix[pos[0]][pos[1]] = ""O"" x.pos = pos }) // await (() => new Promise(resolve => setTimeout(() => { // resolve() // })))() if (matrix.find(x => x.join("""").split(""."").filter(x => x).some(x => x.length > 10))) { console.log(""Segundo #"", i + 1) console.log(matrix.map(x => x.join("""")).join(""\n"") + ""\n"") break; } }",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. 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,"const fs = require(""fs""); // Read input file and split lines const lines = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n""); const ITERATIONS = 100; const WIDTH = 101; const HEIGHT = 103; const robots = []; // Parse input data lines.forEach(line => { const [x, y, vx, vy] = line.match(/-?\d+/g).map(Number); robots.push({ x, y, vx, vy }); }); const quadrants = [0, 0, 0, 0]; // Compute quadrant distribution after 100 iterations robots.forEach(({ x, y, vx, vy }) => { const newX = (x + vx * ITERATIONS) % WIDTH; const newY = (y + vy * ITERATIONS) % HEIGHT; const midX = Math.floor(WIDTH / 2); const midY = Math.floor(HEIGHT / 2); if (newX < midX && newY < midY) quadrants[0]++; else if (newX < midX && newY > midY) quadrants[1]++; else if (newX > midX && newY < midY) quadrants[2]++; else if (newX > midX && newY > midY) quadrants[3]++; }); // Compute safety factor const safetyFactor = quadrants.reduce((acc, val) => acc * val, 1); console.log(""Safety Factor:"", safetyFactor); // Find the iteration when the tree shape appears for (let i = 1; i < 100000; i++) { const seenPositions = new Set(); const board = Array.from({ length: HEIGHT }, () => Array(WIDTH).fill(0)); let collision = false; for (const { x, y, vx, vy } of robots) { let newX = (x + vx * i) % WIDTH; let newY = (y + vy * i) % HEIGHT; if (newX < 0) newX += WIDTH; if (newY < 0) newY += HEIGHT; const posKey = `${newX},${newY}`; if (seenPositions.has(posKey)) { collision = true; break; } seenPositions.add(posKey); board[newY][newX] = 1; } if (collision) continue; const maxRowSum = Math.max(...board.map(row => row.reduce((sum, cell) => sum + cell, 0))); // The tree picture has 31 robots in a single row if (maxRowSum > 30) { console.log(""Tree appears at second:"", i); break; } }",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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import { readFileSync } from 'node:fs'; // Constants const WIDTH = 101; const HEIGHT = 103; const SECONDS = 100; // Read input data const inputData = readFileSync('input.txt', { encoding: 'utf8', flag: 'r' }); // Robot class definition class Robot { constructor(initialState) { const { px, py, vx, vy } = /p=(?-{0,1}\d+),(?-{0,1}\d+) v=(?-{0,1}\d+),(?-{0,1}\d+)/.exec(initialState).groups; this.position = { x: parseInt(px), y: parseInt(py) }; this.velocity = { x: parseInt(vx), y: parseInt(vy) }; } move() { this.position.x = (this.position.x + this.velocity.x + WIDTH) % WIDTH; this.position.y = (this.position.y + this.velocity.y + HEIGHT) % HEIGHT; } isWithinBounds(topLeft, bottomRight) { return ( topLeft.x <= this.position.x && this.position.x < bottomRight.x && topLeft.y <= this.position.y && this.position.y < bottomRight.y ); } } // Parse input and initialize robots const robots = inputData .split('\n') .filter(line => line.trim()) .map(line => new Robot(line)); // Simulate robot movements for the initial period for (let i = 0; i < SECONDS; i++) { robots.forEach(robot => robot.move()); } // Calculate quadrant counts const quadrants = [ { topLeft: { x: 0, y: 0 }, bottomRight: { x: Math.floor(WIDTH / 2), y: Math.floor(HEIGHT / 2) } }, { topLeft: { x: Math.ceil(WIDTH / 2), y: 0 }, bottomRight: { x: WIDTH, y: Math.floor(HEIGHT / 2) } }, { topLeft: { x: 0, y: Math.ceil(HEIGHT / 2) }, bottomRight: { x: Math.floor(WIDTH / 2), y: HEIGHT } }, { topLeft: { x: Math.ceil(WIDTH / 2), y: Math.ceil(HEIGHT / 2) }, bottomRight: { x: WIDTH, y: HEIGHT } } ]; const quadrantCounts = quadrants.map(({ topLeft, bottomRight }) => robots.reduce((count, robot) => robot.isWithinBounds(topLeft, bottomRight) ? count + 1 : count, 0) ); console.log(quadrantCounts.reduce((product, count) => product * count, 1)); // Extended simulation to find a stable pattern for (let i = SECONDS; i < 19000; i++) { const grid = Array.from({ length: HEIGHT }, () => Array(WIDTH).fill('.')); let robotsInCentralArea = 0; robots.forEach(robot => { const { x, y } = robot.position; grid[y][x] = '#'; if (robot.isWithinBounds( { x: Math.floor(WIDTH * 0.25), y: Math.floor(HEIGHT * 0.25) }, { x: Math.floor(WIDTH * 0.75), y: Math.floor(HEIGHT * 0.75) } )) { robotsInCentralArea++; } robot.move(); }); if (robotsInCentralArea >= Math.floor(robots.length / 2)) { console.log(i); grid.forEach(row => console.log(row.join(''))); break; } }",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. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import { readFileSync } from 'node:fs'; const WIDTH = 101; const HEIGHT = 103; const SECONDS = 100; const data = readFileSync('input.txt', { encoding: 'utf8', flag: 'r' }); class Robot { constructor(s) { const { px, py, vx, vy } = /p=(?-{0,1}\d+),(?-{0,1}\d+) v=(?-{0,1}\d+),(?-{0,1}\d+)/.exec(s).groups; this.px = parseInt(px); this.py = parseInt(py); this.vx = parseInt(vx); this.vy = parseInt(vy); } move() { this.px += this.vx; this.py += this.vy; if (this.px < 0) this.px += WIDTH; if (this.py < 0) this.py += HEIGHT; if (this.px >= WIDTH) this.px -= WIDTH; if (this.py >= HEIGHT) this.py -= HEIGHT; } get position() { return [this.px, this.py]; } isBound(topLeft, bottomRight) { return topLeft[0] <= this.px && bottomRight[0] > this.px && topLeft[1] <= this.py && bottomRight[1] > this.py; } } const robots = []; data.split('\n') .filter(x => x.length > 0) .map((y) => { const r = new Robot(y); robots.push(r); return y; }); for (let i = 0; i < SECONDS; i++) { for (const robot of robots) { robot.move(); } } const q1 = robots.reduce((a, x) => { return x.isBound([0, 0], [Math.floor(WIDTH/2), Math.floor(HEIGHT/2)]) ? a + 1 : a; }, 0); const q2 = robots.reduce((a, x) => { return x.isBound([Math.ceil(WIDTH/2), 0], [WIDTH, Math.floor(HEIGHT/2)]) ? a + 1 : a; }, 0); const q3 = robots.reduce((a, x) => { return x.isBound([0, Math.ceil(HEIGHT/2)], [Math.floor(WIDTH/2), HEIGHT]) ? a + 1: a; }, 0); const q4 = robots.reduce((a, x) => { return x.isBound([Math.ceil(WIDTH/2), Math.ceil(HEIGHT/2)], [WIDTH, HEIGHT]) ? a + 1 : a; }, 0); console.log(q1*q2*q3*q4); for (let i = SECONDS; i < 19000; i++) { let count = 0; const arr = new Array(HEIGHT); for (let x = 0; x < arr.length; x++) { arr[x] = new Array(WIDTH).fill('.'); } robots.map(a => { const [x, y] = a.position; arr[y][x] = '#'; if (a.isBound([Math.floor(WIDTH*0.25), Math.floor(HEIGHT*0.25)], [Math.floor(WIDTH*0.75), Math.floor(HEIGHT*0.75)])) count = count + 1; a.move(); }); if (count >= Math.floor(robots.length/2)) { console.log(i); for (let x = 0; x < arr.length; x++) { console.log(arr[x].join('')); } } }",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. 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,"const fs = require(""fs""); // Read input file const inputText = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n""); const numX = 101; const numY = 103; let initialPositions = []; let velocities = []; // Parse input inputText.forEach(line => { let [pSec, vSec] = line.split("" ""); let position = pSec.split(""="")[1].split("","").map(Number); let velocity = vSec.split(""="")[1].split("","").map(Number); initialPositions.push(position); velocities.push(velocity); }); // Standard deviation function function standardDeviation(values) { const mean = values.reduce((a, b) => a + b, 0) / values.length; const variance = values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / values.length; return Math.sqrt(variance); } // Simulation loop for (let counter = 0; counter < 10000; counter++) { let blockCounts = new Map(); let newInitialPositions = []; initialPositions.forEach((initialPos, index) => { let velocity = velocities[index]; let newX = (initialPos[0] + velocity[0]) % numX; let newY = (initialPos[1] + velocity[1]) % numY; if (newX < 0) newX += numX; if (newY < 0) newY += numY; newInitialPositions.push([newX, newY]); let blockKey = `${Math.floor(newX / 5)},${Math.floor(newY / 5)}`; blockCounts.set(blockKey, (blockCounts.get(blockKey) || 0) + 1); }); if (blockCounts.size > 0 && standardDeviation([...blockCounts.values()]) > 3) { console.log(counter + 1); } initialPositions = newInitialPositions; }",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. 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,"const fs = require('fs'); // Dijkstra's algorithm with a priority queue (min-heap) function dijkstra(grid) { const n = grid.length; let start = null; let end = null; // Find start ('S') and end ('E') positions for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 'S') { start = [i, j]; } else if (grid[i][j] === 'E') { end = [i, j]; } } } const dd = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Directions: right, down, left, up const pq = [{ cost: 0, direction: 0, i: start[0], j: start[1] }]; const seen = new Set(); // To track visited positions while (pq.length > 0) { // Sort the priority queue by cost (min-heap) pq.sort((a, b) => a.cost - b.cost); const { cost, direction, i, j } = pq.shift(); // Skip if already visited in this direction if (seen.has(`${direction},${i},${j}`)) { continue; } seen.add(`${direction},${i},${j}`); // Skip if the current position is a wall if (grid[i][j] === '#') { continue; } // If we reach the end 'E', return the cost if (grid[i][j] === 'E') { return cost; } // Calculate the next position in the current direction const ii = i + dd[direction][0]; const jj = j + dd[direction][1]; // Possible next moves: forward, turn left, and turn right const neighbors = [ [cost + 1, direction, ii, jj], // Move forward [cost + 1000, (direction + 1) % 4, i, j], // Turn right [cost + 1000, (direction + 3) % 4, i, j] // Turn left ]; // Add valid neighbors to the priority queue for (const [nextCost, nextDirection, nextI, nextJ] of neighbors) { if (!seen.has(`${nextDirection},${nextI},${nextJ}`)) { pq.push({ cost: nextCost, direction: nextDirection, i: nextI, j: nextJ }); } } } console.log(""Could not find min path""); return null; } // Main function const filePath = 'input.txt'; fs.readFile(filePath, 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } // Convert input data into grid const grid = data.split('\n').map(line => line.split('')); const result = dijkstra(grid); console.log(result); });",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. 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 the file system module to read the input file const fs = require('fs'); // Read the input file and parse it into a 2D array const input = fs.readFileSync('input.txt', 'utf8').split('\n').map(line => line.split('')); const numRows = input.length; const numCols = input[0].length; let start = null; let end = null; // Find the starting (S) and ending (E) positions in the maze for (let y = 0; y < numRows; y++) { for (let x = 0; x < numCols; x++) { if (input[y][x] === 'S') { start = { x, y }; } if (input[y][x] === 'E') { end = { x, y }; } } } // Define the possible directions and their movements const directions = [ { dx: 0, dy: -1, name: 'N' }, // North { dx: 1, dy: 0, name: 'E' }, // East { dx: 0, dy: 1, name: 'S' }, // South { dx: -1, dy: 0, name: 'W' }, // West ]; // Helper function to create a unique key for each state function key(x, y, dirIndex) { return `${x},${y},${dirIndex}`; } // Priority queue implementation for the search algorithm class PriorityQueue { constructor() { this.heap = []; } enqueue(element) { this.heap.push(element); this.heapifyUp(); } dequeue() { if (this.size() === 0) return null; const top = this.heap[0]; const end = this.heap.pop(); if (this.size() > 0) { this.heap[0] = end; this.heapifyDown(); } return top; } size() { return this.heap.length; } // Move the last element up to maintain heap property heapifyUp() { let index = this.size() - 1; const element = this.heap[index]; while (index > 0) { let parentIndex = Math.floor((index - 1) / 2); let parent = this.heap[parentIndex]; if (element.cost >= parent.cost) break; this.heap[index] = parent; this.heap[parentIndex] = element; index = parentIndex; } } // Move the first element down to maintain heap property heapifyDown() { let index = 0; const length = this.size(); const element = this.heap[0]; while (true) { let leftChildIndex = index * 2 + 1; let rightChildIndex = index * 2 + 2; let swapIndex = null; if (leftChildIndex < length) { let leftChild = this.heap[leftChildIndex]; if (leftChild.cost < element.cost) { swapIndex = leftChildIndex; } } if (rightChildIndex < length) { let rightChild = this.heap[rightChildIndex]; if ((swapIndex === null && rightChild.cost < element.cost) || (swapIndex !== null && rightChild.cost < this.heap[swapIndex].cost)) { swapIndex = rightChildIndex; } } if (swapIndex === null) break; this.heap[index] = this.heap[swapIndex]; this.heap[swapIndex] = element; index = swapIndex; } } } let visited = new Set(); let pq = new PriorityQueue(); // Start facing East and enqueue the starting state const startDirIndex = directions.findIndex(dir => dir.name === 'E'); pq.enqueue({ x: start.x, y: start.y, dirIndex: startDirIndex, cost: 0 }); // Perform a search to find the lowest cost path while (pq.size() > 0) { const state = pq.dequeue(); const { x, y, dirIndex, cost } = state; // Check if we've reached the end position if (x === end.x && y === end.y) { console.log(cost); process.exit(0); } // Skip if this state has already been visited const stateKey = key(x, y, dirIndex); if (visited.has(stateKey)) { continue; } visited.add(stateKey); // Attempt to move forward in the current direction const dir = directions[dirIndex]; const nx = x + dir.dx; const ny = y + dir.dy; if (nx >= 0 && nx < numCols && ny >= 0 && ny < numRows && input[ny][nx] !== '#') { pq.enqueue({ x: nx, y: ny, dirIndex: dirIndex, // Keep the same direction cost: cost + 1 // Moving forward costs 1 }); } // Rotate counterclockwise (left turn) const leftDirIndex = (dirIndex + 3) % 4; const leftStateKey = key(x, y, leftDirIndex); if (!visited.has(leftStateKey)) { pq.enqueue({ x: x, y: y, dirIndex: leftDirIndex, cost: cost + 1000 // Turning costs 1000 }); } // Rotate clockwise (right turn) const rightDirIndex = (dirIndex + 1) % 4; const rightStateKey = key(x, y, rightDirIndex); if (!visited.has(rightStateKey)) { pq.enqueue({ x: x, y: y, dirIndex: rightDirIndex, cost: cost + 1000 // Turning costs 1000 }); } } // If no path is found, output a message console.log('No path found'); 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. 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,"const fs = require('fs'); // Get the lowest score from the maze function getLowestScore(maze) { const m = maze.length; const n = maze[0].length; let start = [-1, -1]; let end = [-1, -1]; // Find start ('S') and end ('E') positions for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (maze[i][j] === 'S') { start = [i, j]; } else if (maze[i][j] === 'E') { end = [i, j]; } } } maze[end[0]][end[1]] = '.'; // Mark end as empty const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]; const visited = new Set(); const heap = [{ score: 0, dI: 0, i: start[0], j: start[1] }]; // Min-heap while (heap.length > 0) { // Sort heap by score (min-heap) heap.sort((a, b) => a.score - b.score); const { score, dI, i, j } = heap.shift(); if (i === end[0] && j === end[1]) { return score; // Found the end, return the score } if (visited.has(`${dI},${i},${j}`)) { continue; } visited.add(`${dI},${i},${j}`); // Move forward in the current direction const x = i + dirs[dI][0]; const y = j + dirs[dI][1]; if (maze[x] && maze[x][y] === '.' && !visited.has(`${dI},${x},${y}`)) { heap.push({ score: score + 1, dI, i: x, j: y }); } // Turn left const left = (dI - 1 + 4) % 4; if (!visited.has(`${left},${i},${j}`)) { heap.push({ score: score + 1000, dI: left, i, j }); } // Turn right const right = (dI + 1) % 4; if (!visited.has(`${right},${i},${j}`)) { heap.push({ score: score + 1000, dI: right, i, j }); } } return -1; // Return -1 if no path is found } // Main function const filePath = 'input.txt'; fs.readFile(filePath, 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const maze = data.split('\n').map(line => line.trim().split('')); const lowestScore = getLowestScore(maze); console.log(""Lowest Score:"", lowestScore); });",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. 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,"const fs = require('fs'); // Parse the input file to extract the data function parseInput(filePath) { const data = fs.readFileSync(filePath, 'utf8').split('\n'); return data.map(line => line.trim()); } // Find the starting position marked as 'S' in the grid function findStartingPosition(grid) { for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === 'S') { return [i, j]; } } } return [-1, -1]; } // Given a grid and a current position as well as a direction, // return the list of next possible moves either moving forward in the current direction or turning left or right function getPossibleMoves(grid, i, j, direction) { const rows = grid.length; const cols = grid[0].length; const moves = { 'N': [-1, 0], 'E': [0, 1], 'S': [1, 0], 'W': [0, -1] }; const leftTurns = { 'N': 'W', 'E': 'N', 'S': 'E', 'W': 'S' }; const rightTurns = { 'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N' }; const possibleMoves = []; // Check forward move const [dx, dy] = moves[direction]; const newI = i + dx, newJ = j + dy; if (newI >= 0 && newI < rows && newJ >= 0 && newJ < cols && grid[newI][newJ] !== '#') { possibleMoves.push([newI, newJ, direction]); } // Check left turn const leftDirection = leftTurns[direction]; const [leftDx, leftDy] = moves[leftDirection]; const leftI = i + leftDx, leftJ = j + leftDy; if (leftI >= 0 && leftI < rows && leftJ >= 0 && leftJ < cols && grid[leftI][leftJ] !== '#') { possibleMoves.push([i, j, leftDirection]); } // Check right turn const rightDirection = rightTurns[direction]; const [rightDx, rightDy] = moves[rightDirection]; const rightI = i + rightDx, rightJ = j + rightDy; if (rightI >= 0 && rightI < rows && rightJ >= 0 && rightJ < cols && grid[rightI][rightJ] !== '#') { possibleMoves.push([i, j, rightDirection]); } return possibleMoves; } // Find the shortest path score to reach the target 'E' in the grid function findLowestScore(grid, i, j, direction) { const visited = new Set(); const heap = [{ score: 0, i, j, direction }]; // { score, i, j, direction } while (heap.length > 0) { heap.sort((a, b) => a.score - b.score); // Sort by score (min-heap) const { score, i, j, direction } = heap.shift(); if (visited.has(`${i},${j},${direction}`)) { continue; } visited.add(`${i},${j},${direction}`); if (grid[i][j] === 'E') { return score; } const possibleMoves = getPossibleMoves(grid, i, j, direction); for (const [newI, newJ, newDirection] of possibleMoves) { const newScore = (newDirection === direction) ? score + 1 : score + 1000; heap.push({ score: newScore, i: newI, j: newJ, direction: newDirection }); } } return Infinity; } // Main function const filePath = 'input.txt'; const parsedData = parseInput(filePath); const [i, j] = findStartingPosition(parsedData); const score = findLowestScore(parsedData, i, j, 'E'); 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. 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,"const fs = require('fs'); // Dijkstra's algorithm with a priority queue (min-heap) and path tracking function dijkstra(grid) { const n = grid.length; let start = null; let end = null; // Find start ('S') and end ('E') positions for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 'S') { start = [i, j]; } else if (grid[i][j] === 'E') { end = [i, j]; } } } const dd = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Directions: right, down, left, up const pq = [{ cost: 0, direction: 0, i: start[0], j: start[1], prevDirection: 0, prevI: start[0], prevJ: start[1] }]; const cost = new Map(); const deps = new Map(); // To track dependencies while (pq.length > 0) { // Sort the priority queue by cost (min-heap) pq.sort((a, b) => a.cost - b.cost); const { cost: currentCost, direction, i, j, prevDirection, prevI, prevJ } = pq.shift(); // Skip if we've already visited this state const stateKey = `${direction},${i},${j}`; if (cost.has(stateKey)) { if (cost.get(stateKey) === currentCost) { const prevStateKey = `${prevDirection},${prevI},${prevJ}`; if (!deps.has(stateKey)) deps.set(stateKey, []); deps.get(stateKey).push([prevDirection, prevI, prevJ]); } continue; } // Track the cost for this state cost.set(stateKey, currentCost); // Check if the current position is a wall if (grid[i][j] === '#') { continue; } // If we reach the end 'E', return the cost if (grid[i][j] === 'E') { console.log(currentCost); break; } // Calculate the next position in the current direction const ii = i + dd[direction][0]; const jj = j + dd[direction][1]; // Possible next moves: forward, turn left, and turn right const neighbors = [ [currentCost + 1, direction, ii, jj, direction, i, j], // Move forward [currentCost + 1000, (direction + 1) % 4, i, j, direction, i, j], // Turn right [currentCost + 1000, (direction + 3) % 4, i, j, direction, i, j] // Turn left ]; // Add valid neighbors to the priority queue for (const [nextCost, nextDirection, nextI, nextJ, nextPrevDirection, nextPrevI, nextPrevJ] of neighbors) { const neighborStateKey = `${nextDirection},${nextI},${nextJ}`; if (!cost.has(neighborStateKey)) { pq.push({ cost: nextCost, direction: nextDirection, i: nextI, j: nextJ, prevDirection: nextPrevDirection, prevI: nextPrevI, prevJ: nextPrevJ }); } } } console.log(""Could not find min path""); return null; } // Main function const filePath = 'input.txt'; fs.readFile(filePath, 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } // Convert input data into grid const grid = data.split('\n').map(line => line.split('')); const result = dijkstra(grid); console.log(result); });",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. 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,"const fs = require('fs'); // Read maze from file fs.readFile('input.txt', 'utf8', (error, input) => { if (error) { console.error('Error reading the file:', error); return; } const grid = input.split('\n'); const INF = Number.MAX_SAFE_INTEGER; const visited = Array.from({ length: grid.length }, () => Array.from({ length: grid[0].length }, () => Array(4).fill(INF) ) ); const moves = [ [-1, 0], // North [0, 1], // East [1, 0], // South [0, -1] // West ]; let start = null; let end = null; // Find the positions of 'S' and 'E' for (let row = 0; row < grid.length; row++) { for (let col = 0; col < grid[row].length; col++) { if (grid[row][col] === 'S') { start = [row, col]; } else if (grid[row][col] === 'E') { end = [row, col]; } } } // Initialize the priority queue with the start position, facing East const queue = [{ cost: 0, position: [...start, 1], path: [start] }]; const foundPaths = []; let optimalCost = INF; // Process the queue while (queue.length > 0 && queue[0].cost <= optimalCost) { queue.sort((a, b) => a.cost - b.cost); // Simulate a min-heap by sorting const { cost, position, path } = queue.shift(); const [y, x, direction] = position; // If we reach the end, update the optimal cost and store the path if (y === end[0] && x === end[1]) { optimalCost = cost; foundPaths.push(path); continue; } // Skip if the current position has been visited with a lower cost if (visited[y][x][direction] < cost) { continue; } visited[y][x][direction] = cost; // Explore all possible directions for (let i = 0; i < 4; i++) { const [dy, dx] = moves[i]; const newY = y + dy, newX = x + dx; if (grid[newY] && grid[newY][newX] !== '#' && !path.some(p => p[0] === newY && p[1] === newX)) { const moveCost = i === direction ? 1 : 1001; queue.push({ cost: cost + moveCost, position: [newY, newX, i], path: [...path, [newY, newX]] }); } } } // Collect all unique positions visited across all paths const uniquePositions = new Set(); foundPaths.forEach(path => { path.forEach(([y, x]) => uniquePositions.add(`${y},${x}`)); }); console.log(uniquePositions.size); });",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. 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,"const fs = require('fs'); // Function to read maze from a file fs.readFile('input.txt', 'utf8', (error, content) => { if (error) { console.error('File reading error:', error); return; } const grid = content.split('\n'); const INF = Number.MAX_SAFE_INTEGER; const visited = Array.from({ length: grid.length }, () => Array.from({ length: grid[0].length }, () => Array(4).fill(INF)) ); const directionOffsets = [ [-1, 0], // Move North [0, 1], // Move East [1, 0], // Move South [0, -1] // Move West ]; let start = null; let end = null; // Locate the start ('S') and end ('E') positions in the grid for (let row = 0; row < grid.length; row++) { for (let col = 0; col < grid[row].length; col++) { if (grid[row][col] === 'S') { start = [row, col]; } if (grid[row][col] === 'E') { end = [row, col]; } } } // Priority Queue for processing nodes, emulating heap behavior const priorityQueue = [{ score: 0, position: [...start, 1], // Start facing East path: [start] }]; const pathsFound = []; let optimalScore = INF; // Processing the priority queue while (priorityQueue.length > 0 && priorityQueue[0].score <= optimalScore) { priorityQueue.sort((a, b) => a.score - b.score); // Simulate a min-heap with sorting const { score, position, path } = priorityQueue.shift(); const [currentY, currentX, direction] = position; // Check if we reached the destination if (currentY === end[0] && currentX === end[1]) { optimalScore = score; pathsFound.push(path); continue; } // Skip if we've already visited this position with a lower score if (visited[currentY][currentX][direction] < score) { continue; } visited[currentY][currentX][direction] = score; // Explore all possible directions for (let i = 0; i < 4; i++) { const [dy, dx] = directionOffsets[i]; const newY = currentY + dy, newX = currentX + dx; // Check if the new position is valid and not visited in the current path if (grid[newY] && grid[newY][newX] !== '#' && !path.some(p => p[0] === newY && p[1] === newX)) { const moveCost = i === direction ? 1 : 1001; priorityQueue.push({ score: score + moveCost, position: [newY, newX, i], path: [...path, [newY, newX]] }); } } } // Collect unique positions from all found paths const visitedPositions = new Set(); pathsFound.forEach(path => { path.forEach(([y, x]) => visitedPositions.add(`${y},${x}`)); }); // Output the count of distinct visited positions console.log(visitedPositions.size); });",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. 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,"const fs = require('fs'); // Read the maze from file fs.readFile('input.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const maze = data.split('\n'); const maxSize = Number.MAX_SAFE_INTEGER; const seen = Array.from({ length: maze.length }, () => Array.from({ length: maze[0].length }, () => Array(4).fill(maxSize) ) ); const directions = [ [-1, 0], // North [0, 1], // East [1, 0], // South [0, -1] // West ]; let startPos = null; let endPos = null; // Locate the start ('S') and end ('E') positions for (let row = 0; row < maze.length; row++) { for (let col = 0; col < maze[row].length; col++) { if (maze[row][col] === 'S') { startPos = [row, col]; } else if (maze[row][col] === 'E') { endPos = [row, col]; } } } // Priority queue to hold our state, starting at 'S' (facing East) const pq = [{ score: 0, position: [...startPos, 1], path: [startPos] }]; // Start facing East const paths = []; let bestScore = maxSize; // Process the priority queue while (pq.length > 0 && pq[0].score <= bestScore) { pq.sort((a, b) => a.score - b.score); // Sort to simulate min-heap behavior const { score, position, path } = pq.shift(); const [y, x, dir] = position; // If we reached the end position if (y === endPos[0] && x === endPos[1]) { bestScore = score; paths.push(path); continue; } // Skip if already visited with a lower score if (seen[y][x][dir] < score) { continue; } seen[y][x][dir] = score; // Explore all directions for (let i = 0; i < 4; i++) { const [dy, dx] = directions[i]; const ny = y + dy, nx = x + dx; if (maze[ny] && maze[ny][nx] !== '#' && !path.some(p => p[0] === ny && p[1] === nx)) { const cost = i === dir ? 1 : 1001; pq.push({ score: score + cost, position: [ny, nx, i], path: [...path, [ny, nx]] }); } } } // Collect all distinct positions visited by any path const seats = new Set(); paths.forEach(path => { path.forEach(([y, x]) => seats.add(`${y},${x}`)); }); console.log(seats.size); });",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. 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,"const fs = require('fs'); // Read the maze from file fs.readFile('input.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const maze = data.split('\n'); const maxsize = Number.MAX_SAFE_INTEGER; const seen = Array.from({ length: maze.length }, () => Array.from({ length: maze[0].length }, () => Array(4).fill(maxsize)) ); const velocities = [ [-1, 0], // North [0, 1], // East [1, 0], // South [0, -1] // West ]; let startPos = null; let endPos = null; // Find start ('S') and end ('E') positions for (let j = 0; j < maze.length; j++) { for (let i = 0; i < maze[j].length; i++) { if (maze[j][i] === 'S') { startPos = [j, i]; } if (maze[j][i] === 'E') { endPos = [j, i]; } } } // Priority Queue to simulate heapq in Python const pq = [{ score: 0, position: [...startPos, 1], path: [startPos] }]; // Start facing East const paths = []; let bestScore = maxsize; // Process the priority queue while (pq.length > 0 && pq[0].score <= bestScore) { pq.sort((a, b) => a.score - b.score); // Sort to simulate min-heap behavior const { score, position, path } = pq.shift(); const [y, x, dir] = position; // If we reached the end position if (y === endPos[0] && x === endPos[1]) { bestScore = score; paths.push(path); continue; } // Skip if already visited with a lower score if (seen[y][x][dir] < score) { continue; } seen[y][x][dir] = score; // Explore all directions for (let i = 0; i < 4; i++) { const [dy, dx] = velocities[i]; const ny = y + dy, nx = x + dx; if (maze[ny] && maze[ny][nx] !== '#' && !path.some(p => p[0] === ny && p[1] === nx)) { const cost = i === dir ? 1 : 1001; pq.push({ score: score + cost, position: [ny, nx, i], path: [...path, [ny, nx]] }); } } } // Collect all distinct positions visited by any path const seats = new Set(); paths.forEach(path => { path.forEach(([y, x]) => seats.add(`${y},${x}`)); }); console.log(seats.size); });",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. 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,"const fs = require('fs'); // Part 2 of the puzzle function part2(puzzleInput) { const grid = puzzleInput.split('\n'); const m = grid.length; const n = grid[0].length; let start, end; // Find start ('S') and end ('E') positions for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 'S') { start = [i, j]; } else if (grid[i][j] === 'E') { end = [i, j]; } } } // Replace 'E' with '.' to allow traversal grid[end[0]] = grid[end[0]].replace('E', '.'); // Helper function to check if a position can be visited function canVisit(d, i, j, score) { const prevScore = visited.get(`${d},${i},${j}`); if (prevScore && prevScore < score) { return false; } visited.set(`${d},${i},${j}`, score); return true; } const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; const heap = [{ score: 0, direction: 0, i: start[0], j: start[1], path: new Set([start.toString()]) }]; const visited = new Map(); let lowestScore = null; const winningPaths = new Set(); while (heap.length > 0) { // Sort the heap by score (min-heap behavior) heap.sort((a, b) => a.score - b.score); const { score, direction, i, j, path } = heap.shift(); if (lowestScore && lowestScore < score) { break; } if (i === end[0] && j === end[1]) { lowestScore = score; path.forEach(p => winningPaths.add(p)); continue; } if (!canVisit(direction, i, j, score)) { continue; } const x = i + directions[direction][0]; const y = j + directions[direction][1]; if (grid[x][y] === '.' && canVisit(direction, x, y, score + 1)) { const newPath = new Set(path); newPath.add([x, y].toString()); heap.push({ score: score + 1, direction, i: x, j: y, path: newPath }); } // Try turning left const left = (direction - 1 + 4) % 4; if (canVisit(left, i, j, score + 1000)) { heap.push({ score: score + 1000, direction: left, i, j, path }); } // Try turning right const right = (direction + 1) % 4; if (canVisit(right, i, j, score + 1000)) { heap.push({ score: score + 1000, direction: right, i, j, path }); } } return winningPaths.size; } // Read input file fs.readFile('input.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const result = part2(data); console.log(result); });",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. 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,"const fs = require('fs'); // Parse input data into an array of reports const parseInput = (input) => { return input.trim().split('\n').map(line => line.split(' ').map(Number)); }; // Check if a report has valid adjacent differences const hasValidDifferences = (report) => { for (let i = 0; i < report.length - 1; i++) { const diff = report[i + 1] - report[i]; if (diff === 0 || diff < -3 || diff > 3) { return false; } } return true; }; // Check if a report is strictly increasing or strictly decreasing const isMonotonic = (report) => { const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); return isIncreasing || isDecreasing; }; // Check if a report is safe based on both rules const isSafe = (report) => { return hasValidDifferences(report) && isMonotonic(report); }; // Analyze all reports and count the number of safe ones const analyzeReports = (reports) => { return reports.filter(isSafe).length; }; // Main function to handle file reading and processing const main = () => { fs.readFile('input.txt', 'utf-8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const reports = parseInput(data); const safeCount = analyzeReports(reports); console.log('Number of safe reports:', safeCount); }); }; // Execute the program 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. 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,"let fs = require('fs'); let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); let safeCount = 0; puzzleInput.forEach((report) => { let levels = report.split(' '); let lastLevel = undefined; let lastDifference = undefined; let reportSafe = levels.length > 1 ? true : false; levels.forEach((level, index) => { if (!reportSafe) { return; } if (!lastLevel) { lastLevel = level; return; } let difference = parseInt(lastLevel) - parseInt(level); if (difference === 0) { reportSafe = false; return; } if (lastDifference && lastDifference > 0 && difference < 0) { reportSafe = false; return; } if (lastDifference && lastDifference < 0 && difference > 0) { reportSafe = false; return; } if (difference > 3 || difference < -3) { reportSafe = false; return; } lastLevel = level; lastDifference = difference; }); if (reportSafe) { safeCount++; } }); 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. 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,"const fs = require('fs'); class ReportAnalyzer { constructor(data) { this.reports = this.parseData(data); } // Parse the input data into an array of reports parseData(data) { return data.trim().split('\n').map(line => line.split(' ').map(Number)); } // Check if the adjacent differences in the report are valid hasValidDifferences(report) { for (let i = 0; i < report.length - 1; i++) { const diff = report[i + 1] - report[i]; if (diff === 0 || diff < -3 || diff > 3) { return false; } } return true; } // Check if the report is monotonic (either increasing or decreasing) isMonotonic(report) { const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); return isIncreasing || isDecreasing; } // Check if a report is safe isSafe(report) { return this.hasValidDifferences(report) && this.isMonotonic(report); } // Count the number of safe reports countSafeReports() { return this.reports.filter(report => this.isSafe(report)).length; } } // Main function to handle file reading and processing const main = () => { fs.readFile('input.txt', 'utf-8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const analyzer = new ReportAnalyzer(data); const safeCount = analyzer.countSafeReports(); console.log('Number of safe reports:', safeCount); }); }; // Execute the program 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. 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,"const fs = require('fs'); // Helper function to determine if a report is safe function isSafe(report) { for (let i = 0; i < report.length - 1; i++) { const diff = report[i + 1] - report[i]; if (diff === 0 || diff < -3 || diff > 3) { return false; // Adjacent levels violate the difference rule } } const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); return isIncreasing || isDecreasing; // Either strictly increasing or decreasing } // Main function to analyze the reports function analyzeReports(input) { const reports = input.trim().split('\n').map(line => line.split(' ').map(Number)); let safeCount = 0; for (const report of reports) { if (isSafe(report)) { safeCount++; } } return safeCount; } // Read the input data from a file fs.readFile('input.txt', 'utf-8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const safeReports = analyzeReports(data); console.log('Number of safe reports:', safeReports); });",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. 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,"const fs = require(""fs""); let buffer, input, rows; try { buffer = fs.readFileSync(__dirname + ""/input.txt"", ""utf8""); } catch (e) { throw e; } input = buffer.toString(); rows = input.split(""\n""); const check_levels = (report) => { let direction = true; // ascending let valid = true; for (let i = 0; i < report.length - 1; i++) { // Easy case, check for no change, short circuit if so if (report[i] == report[i + 1]) { valid = false; break; } if (i == 0) { // Define expected direction direction = report[i] < report[i + 1]; } // Test! valid = direction ? report[i] < report[i + 1] && report[i + 1] - report[i] < 4 // Ascending and diff of < 4 : report[i] > report[i + 1] && report[i] - report[i + 1] < 4; // Descending and diff of < 4 if (!valid) { // short circuit if we found an exception break; } } return valid; }; const safe_reports = rows.reduce((accumulator, row) => { if (row === """") return accumulator; // Empty row check, skip const report = row.split("" "").map(Number); const valid = check_levels(report); return accumulator + (valid ? 1 : 0); }, 0); 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. 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,"const fs = require('fs'); // Helper function to check if a report is safe function isSafe(report) { for (let i = 0; i < report.length - 1; i++) { const diff = report[i + 1] - report[i]; if (diff < -3 || diff > 3 || diff === 0) { return false; // Invalid difference } } // Check if it's strictly increasing or decreasing const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); return isIncreasing || isDecreasing; } // Helper function to check if a report can be safe by removing one level function isSafeWithDampener(report) { for (let i = 0; i < report.length; i++) { const modifiedReport = [...report.slice(0, i), ...report.slice(i + 1)]; if (isSafe(modifiedReport)) { return true; // Removing this level makes the report safe } } return false; } // Main function to analyze reports function analyzeReports(input) { const reports = input.trim().split('\n').map(line => line.split(' ').map(Number)); let safeReports = 0; let safeReportsWithDampener = 0; for (const report of reports) { if (isSafe(report)) { safeReports++; safeReportsWithDampener++; } else if (isSafeWithDampener(report)) { safeReportsWithDampener++; } } return { safeReports, safeReportsWithDampener }; } // Read input from the file and process it fs.readFile('input.txt', 'utf-8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const { safeReports, safeReportsWithDampener } = analyzeReports(data); console.log('Part 1: Safe Reports:', safeReports); console.log('Part 2: Safe Reports with Dampener:', safeReportsWithDampener); });",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. 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,"let fs = require('fs'); let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); let safeCount = 0; puzzleInput.forEach((report) => { let levels = report.split(' '); if (levels.length > 1) { let passedVariations = 0; for (let i = 0; i < levels.length; i++) { let lastLevel = undefined; let lastDifference = undefined; let variationSafe = true; levels.forEach((level, index) => { if (index === i) { return; } if (!variationSafe) { return; } if (!lastLevel) { lastLevel = level; return; } let difference = parseInt(lastLevel) - parseInt(level); if (difference === 0) { variationSafe = false; return; } if (lastDifference && lastDifference > 0 && difference < 0) { variationSafe = false; return; } if (lastDifference && lastDifference < 0 && difference > 0) { variationSafe = false; return; } if (difference > 3 || difference < -3) { variationSafe = false; return; } lastLevel = level; lastDifference = difference; }); if (variationSafe) { passedVariations++; } } if (passedVariations > 0) { safeCount++; } } }); 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. 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,"const fs = require('fs'); class Analyzer { constructor(input) { this.reports = this.parseInput(input); } // Parse input into a list of numerical arrays parseInput(input) { return input.trim().split('\n').map(line => line.split(' ').map(Number)); } // Check if a report is safe isSafe(report) { for (let i = 0; i < report.length - 1; i++) { const diff = report[i + 1] - report[i]; if (diff < -3 || diff > 3 || diff === 0) { return false; } } const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); return isIncreasing || isDecreasing; } // Check if a report can be made safe with the dampener isSafeWithDampener(report) { for (let i = 0; i < report.length; i++) { const modifiedReport = [...report.slice(0, i), ...report.slice(i + 1)]; if (this.isSafe(modifiedReport)) { return true; } } return false; } // Analyze reports and return the counts analyzeReports() { let safeReports = 0; let safeReportsWithDampener = 0; for (const report of this.reports) { if (this.isSafe(report)) { safeReports++; safeReportsWithDampener++; } else if (this.isSafeWithDampener(report)) { safeReportsWithDampener++; } } return { safeReports, safeReportsWithDampener }; } } // Main function to load the input and execute the analysis function main() { fs.readFile('input.txt', 'utf-8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } const analyzer = new Analyzer(data); const { safeReports, safeReportsWithDampener } = analyzer.analyzeReports(); console.log('Part 1: Safe Reports:', safeReports); console.log('Part 2: Safe Reports with Dampener:', safeReportsWithDampener); }); } // Run the program 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error('Error reading file:', err); return; } data = data.split(""\n"").map(line => line.split("" "").map(Number)); console.log(part1(data)); console.log(part2(data)); }); const part1 = (data) => { const allowedDifferences = new Set([-3, -2, -1, 1, 2, 3]); let safeReports = 0; for (let line of data) { if (checkIfSafe(line, allowedDifferences)) { safeReports++; } } return safeReports; } const checkIfSafe = (line, allowedDifferences) => { let increasing, decreasing; for (let i = 1; i < line.length; i++) { const difference = line[i] - line[i - 1]; if (!allowedDifferences.has(difference)) { return false; } if (difference < 0) decreasing = true; if (difference > 0) increasing = true; if (i === line.length - 1 && !(increasing && decreasing)) { return true } } return false; } const part2 = (data) => { const allowedDifferences = new Set([-3, -2, -1, 1, 2, 3]); let safeReports = 0; for (let line of data) { if (checkIfSafe(line, allowedDifferences)) { safeReports++; } else { // check permutations of line for (let j = 0; j < line.length; j++) { const lineMinusJ = line.filter((num, index) => index !== j); if (checkIfSafe(lineMinusJ, allowedDifferences)) { safeReports++; break; } } } } return safeReports; }",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. 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,"const fs = require(""fs""); const puzzleInput = fs .readFileSync(""./input.txt"") // .readFileSync(""./sample_input.txt"") .toString() .split(""\n"") function runLevelSafetyCheck(level) { let isSafeLevel = false; let decreasing = isDecreasing(level); let increasing = isIncraesing(level); if (decreasing || increasing) { isSafeLevel = isSafe(level); } return isSafeLevel; } function isDecreasing(num) { let decreasing = false; for (let i = 0; i < num.length - 1; i++) { if (num[i] > num[i + 1]) { decreasing = true; } else { decreasing = false; break; } } return decreasing; } function isIncraesing(num) { let increase = false; for (let i = 0; i < num.length - 1; i++) { if (num[i] < num[i + 1]) { increase = true; } else { increase = false; break; } } return increase; } function isSafe(num) { for (let i = 0; i < num.length - 1; i++) { const difference = Math.abs(num[i] - num[i + 1]); if (difference < 1 || difference > 3) { return false; } } return true; } let safeLevels = 0; puzzleInput.forEach(element => { let level = element.split("" "").map(x => parseInt(x)) let isSafe = runLevelSafetyCheck(level); if (isSafe) { safeLevels++; } }); console.log(`Part 1: ${safeLevels} safe levels`) function problemDampener(level) { let isDampened = false; let dampenedLevel = 0; for (let i = 0; i < level.length; i++) { let newLevel = level.slice(); newLevel.splice(i, 1); let isSafe = runLevelSafetyCheck(newLevel); if (isSafe) { isDampened = true; dampenedLevel = newLevel; break; } } return { isDampened, dampenedLevel } } let safeAfterDampening = 0; puzzleInput.forEach(element => { let level = element.split("" "").map(x => parseInt(x)) let safe = problemDampener(level); if (safe.isDampened) { safeAfterDampening++; } }); 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. 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,"const fs = require('fs'); // Read and process input const puzzleInput = fs.readFileSync('input.txt', 'utf-8').split(""\n""); // Function to separate lines into rules and updates const getRulesAndUpdates = (input) => { const rules = []; const updates = []; input.forEach((line) => { if (line.includes('|')) rules.push(line); else if (line.includes(',')) updates.push(line); }); return { rules, updates }; }; // Function to check if an update satisfies a rule const isValidUpdate = (update, rule) => { const [rule1, rule2] = rule.split('|'); if (update.includes(rule1) && update.includes(rule2)) { const firstIndex = update.indexOf(rule1); const secondIndex = update.indexOf(rule2); return firstIndex < secondIndex; } return true; }; // Function to find the middle page number from a valid update const getMiddlePageNumber = (update) => update[Math.floor(update.length / 2)]; // Main logic to calculate the sum of middle page numbers const calculateMiddlePageSum = (rules, updates) => { return updates.reduce((sum, updateString) => { const update = updateString.split(','); const allValid = rules.every((rule) => isValidUpdate(update, rule)); if (allValid) { const middlePageNumber = getMiddlePageNumber(update); sum += parseInt(middlePageNumber); } return sum; }, 0); }; // Execution const { rules, updates } = getRulesAndUpdates(puzzleInput); const result = calculateMiddlePageSum(rules, updates); 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. 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,"const fs = require('fs'); // Read and process input const puzzleInput = fs.readFileSync('input.txt', 'utf-8').split(""\n""); // Separate rules and updates from puzzle input const [rules, updates] = puzzleInput.reduce(([rules, updates], line) => { if (line.includes('|')) rules.push(line); if (line.includes(',')) updates.push(line); return [rules, updates]; }, [[], []]); // Process updates and evaluate based on rules const middlePageNumbers = updates .map((updateString) => updateString.split(',')) .filter((update) => { return rules.every((ruleString) => { const [rule1, rule2] = ruleString.split('|'); if (update.includes(rule1) && update.includes(rule2)) { const firstIndex = update.indexOf(rule1); const secondIndex = update.indexOf(rule2); return firstIndex < secondIndex; } return true; // Ignore the rule if it doesn't match }); }) .map((update) => update[Math.floor(update.length / 2)]); // Sum the middle page numbers const result = middlePageNumbers.reduce((sum, number) => sum + parseInt(number), 0); // Output the result 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. 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,"const fs = require('fs'); // Function to read input and split by lines const readInput = (filename) => fs.readFileSync(filename, 'utf-8').split(""\n""); // Function to separate rules and updates from the puzzle input const separateRulesAndUpdates = (input) => { const rules = []; const updates = []; input.forEach(line => { if (line.includes('|')) rules.push(line); if (line.includes(',')) updates.push(line); }); return { rules, updates }; }; // Function to check if an update satisfies all the rules const satisfiesRules = (update, rules) => { return rules.every(ruleString => { const [rule1, rule2] = ruleString.split('|'); if (update.includes(rule1) && update.includes(rule2)) { const firstIndex = update.indexOf(rule1); const secondIndex = update.indexOf(rule2); return firstIndex < secondIndex; } return true; }); }; // Function to extract the middle page number from a valid update const extractMiddlePageNumber = (update) => update[Math.floor(update.length / 2)]; // Function to calculate the total of middle page numbers const calculateTotal = (middlePageNumbers) => middlePageNumbers.reduce((sum, number) => sum + parseInt(number), 0); // Main execution const input = readInput('input.txt'); const { rules, updates } = separateRulesAndUpdates(input); const middlePageNumbers = updates .map(updateString => updateString.split(',')) .filter(update => satisfiesRules(update, rules)) .map(extractMiddlePageNumber); const result = calculateTotal(middlePageNumbers); 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. 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,"let fs = require('fs'); let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); let rules = []; let updates = []; puzzleInput.forEach((line) => { if (line.includes('|')) rules.push(line); if (line.includes(',')) updates.push(line); }); let middlePageNumbers = []; updates.forEach((updateString) => { let update = updateString.split(','); let testResults = []; rules.forEach((ruleString) => { rule = ruleString.split('|'); if (update.includes(rule[0]) && update.includes(rule[1])) { let firstIndex = update.indexOf(rule[0]); let secondIndex = update.indexOf(rule[1]); if (firstIndex < secondIndex) { testResults.push(true); } else { testResults.push(false); } } }); if (!testResults.includes(false)) { middlePageNumbers.push(update[Math.floor(update.length / 2)]); } }); let result = 0; middlePageNumbers.forEach((number) => { result += parseInt(number); }); 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. 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,"const fs = require(""fs""); const filename = ""input.txt""; var buffer, rows; try { buffer = fs.readFileSync(__dirname + ""/"" + filename, ""utf8""); } catch (e) { throw e; } rows = buffer.toString().split(""\n""); var after_check_object = {}, flag = false, valid_instructions = 0; for (let i = 0; i < rows.length - 1; i++) { let row = rows[i]; if (row == """") { flag = true; continue; } if (!flag) { // Store rules const [a, b] = row.split(""|""); if (after_check_object[a] == undefined) { after_check_object[a] = { after: [b] }; } else { if (!after_check_object[a].after.includes(b)) { after_check_object[a].after.push(b); } } } else { let numbers = row.split("",""); let valid_instruction = true; for (let j = 0; j < rows.length - 1; j++) { let number = numbers[j]; let remainder_numbers = numbers.slice(j + 1); for (let k = 0; k < remainder_numbers.length; k++) { if (!after_check_object[number] || !after_check_object[number].after.includes(remainder_numbers[k])) { valid_instruction = false; break; } } if (valid_instruction === false) { break; } } if (valid_instruction) { // console.log(""Valid instruction list! "", { numbers, valid_instruction }); valid_instructions += Number(numbers[Math.floor(numbers.length / 2)]); } } } // console.table(rows); // console.dir(after_check_object, { depth: null }); 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. 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,"const fs = require('fs'); // Read the input file const input = fs.readFileSync('input.txt', 'utf8'); const lines = input.trim().split('\n'); let index = 0; const rules = []; // Parse the rules while (index < lines.length && lines[index].includes('|')) { const [from, to] = lines[index].split('|').map(Number); rules.push({ from, to }); index++; } // Skip blank lines while (index < lines.length && lines[index].trim() === '') { index++; } // Parse the updates const updates = []; for (; index < lines.length; index++) { const line = lines[index].trim(); if (line !== '') { const pages = line.split(',').map(Number); updates.push(pages); } } // Function to check if an update is in correct order function isCorrectOrder(update) { const positions = new Map(); update.forEach((page, idx) => positions.set(page, idx)); for (const { from, to } of rules) { if (positions.has(from) && positions.has(to)) { if (positions.get(from) > positions.get(to)) return false; } } return true; } // Function to reorder an update according to the rules function reorderUpdate(update) { // Build a subgraph for the pages in the update const pagesSet = new Set(update); const graph = new Map(); const inDegree = new Map(); // Initialize graph and in-degree for (const page of pagesSet) { graph.set(page, []); inDegree.set(page, 0); } // Add edges based on rules for (const { from, to } of rules) { if (pagesSet.has(from) && pagesSet.has(to)) { graph.get(from).push(to); inDegree.set(to, inDegree.get(to) + 1); } } // Topological sort const queue = []; for (const [node, degree] of inDegree) { if (degree === 0) queue.push(node); } const sorted = []; while (queue.length > 0) { const node = queue.shift(); sorted.push(node); for (const neighbor of graph.get(node)) { inDegree.set(neighbor, inDegree.get(neighbor) - 1); if (inDegree.get(neighbor) === 0) { queue.push(neighbor); } } } // If sorting is not possible (cycle detected), return original update if (sorted.length !== pagesSet.size) return update; return sorted; } // Sum the middle page numbers after reordering incorrectly ordered updates let sum = 0; for (const update of updates) { if (!isCorrectOrder(update)) { const reordered = reorderUpdate(update); const middleIndex = Math.floor(reordered.length / 2); sum += reordered[middleIndex]; } } 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. 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,"let fs = require('fs'); let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); let rules = []; let updates = []; let checkRules = (update, rules) => { let updateFixed = false; let fails = 0; rules.forEach((ruleString) => { rule = ruleString.split('|'); if (update.includes(rule[0]) && update.includes(rule[1])) { let firstIndex = update.indexOf(rule[0]); let secondIndex = update.indexOf(rule[1]); if (firstIndex > secondIndex) { fails++; update[secondIndex] = rule[0]; update[firstIndex] = rule[1]; updateFixed = true; } } }); if (updateFixed && fails > 1) checkRules(update, rules); if (updateFixed) return update; return false; } puzzleInput.forEach((line) => { if (line.includes('|')) rules.push(line); if (line.includes(',')) updates.push(line); }); let fixedUpdates = []; updates.forEach((updateString) => { let update = updateString.split(','); let fixedUpdate = checkRules(update, rules); if (fixedUpdate) fixedUpdates.push(fixedUpdate); }); let result = 0; fixedUpdates.forEach((update) => result += parseInt(update[Math.floor(update.length / 2)])); 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error('Error reading file:', err); return; } const [instructions, updates] = data .split(""\n\n"") .map(section => section .split(""\n"") .map(line => line.split(/[|,]/))); const [validUpdates, invalidUpdates] = getValidInvalidUpdates(instructions, updates); console.log(part1(validUpdates)); console.log(part2(instructions, invalidUpdates)); }); const getValidInvalidUpdates = (instructions, updates) => { const validUpdates = []; const invalidUpdates = []; for (let update of updates) { let valid = true; for (let [first, second] of instructions) { const firstIndex = update.indexOf(first); const secondIndex = update.indexOf(second); if (firstIndex !== -1 && secondIndex !== -1 && firstIndex > secondIndex) { valid = false; break; } } if (valid) { validUpdates.push(update); } else { invalidUpdates.push(update); } } return [validUpdates, invalidUpdates]; } const part1 = validUpdates => { return validUpdates.reduce((validMiddlePages, update) => validMiddlePages + Number(update[Math.floor(update.length / 2)]) , 0); } const reorderUpdate = (update, instructions) => { const sortedUpdate = [...update]; let reordered = true; // If the update needs to be reordered, keep running it through the loop until it is fixed while (reordered) { reordered = false; for (let [first, second] of instructions) { const firstIndex = sortedUpdate.indexOf(first); const secondIndex = sortedUpdate.indexOf(second); if (firstIndex !== -1 && secondIndex !== -1 && firstIndex > secondIndex) { // Remove first num, reinsert it before second num sortedUpdate.splice(firstIndex, 1); sortedUpdate.splice(secondIndex, 0, first); reordered = true; } } } return sortedUpdate; }; const part2 = (instructions, invalidUpdates) => { return invalidUpdates.reduce((reorderedMiddlePages, update) => { const reorderedUpdate = reorderUpdate(update, instructions); return reorderedMiddlePages + Number(reorderedUpdate[Math.floor(reorderedUpdate.length / 2)]); }, 0); }",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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; // Read the input file asynchronously fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error(""Error reading file:"", err); return; } const [instructions, updates] = parseInputData(data); const [validUpdates, invalidUpdates] = classifyUpdates(instructions, updates); console.log(calculateValidUpdatesSum(validUpdates)); console.log(calculateReorderedUpdatesSum(instructions, invalidUpdates)); }); // Function to parse input data into instructions and updates const parseInputData = (data) => { return data.split(""\n\n"").map(section => section.split(""\n"").map(line => line.split(/[|,]/)) ); }; // Function to classify updates into valid and invalid categories const classifyUpdates = (instructions, updates) => { const validUpdates = []; const invalidUpdates = []; updates.forEach((update) => { const isValid = checkUpdateValidity(update, instructions); if (isValid) validUpdates.push(update); else invalidUpdates.push(update); }); return [validUpdates, invalidUpdates]; }; // Function to check if a given update is valid based on instructions const checkUpdateValidity = (update, instructions) => { for (let [first, second] of instructions) { const firstIndex = update.indexOf(first); const secondIndex = update.indexOf(second); if (firstIndex !== -1 && secondIndex !== -1 && firstIndex > secondIndex) { return false; } } return true; }; // Function to calculate the sum of the middle pages from valid updates const calculateValidUpdatesSum = (validUpdates) => { return validUpdates.reduce((sum, update) => sum + Number(update[Math.floor(update.length / 2)]), 0 ); }; // Function to reorder updates based on instructions const reorderUpdate = (update, instructions) => { const sortedUpdate = [...update]; let isReordered = true; // Keep reordering until no more changes are needed while (isReordered) { isReordered = false; for (let [first, second] of instructions) { const firstIndex = sortedUpdate.indexOf(first); const secondIndex = sortedUpdate.indexOf(second); if (firstIndex !== -1 && secondIndex !== -1 && firstIndex > secondIndex) { // Reorder the update by moving 'first' before 'second' sortedUpdate.splice(firstIndex, 1); sortedUpdate.splice(secondIndex, 0, first); isReordered = true; } } } return sortedUpdate; }; // Function to calculate the sum of the middle pages from reordered invalid updates const calculateReorderedUpdatesSum = (instructions, invalidUpdates) => { return invalidUpdates.reduce((sum, update) => { const reorderedUpdate = reorderUpdate(update, instructions); return sum + Number(reorderedUpdate[Math.floor(reorderedUpdate.length / 2)]); }, 0); };",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. 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,"const fs = require('fs'); // Read the input file and parse lines const input = fs.readFileSync('input.txt', 'utf8').trim(); const lines = input.split('\n'); // Function to parse rules from the input const parseRules = (lines) => { const rules = []; let index = 0; while (index < lines.length && lines[index].includes('|')) { const [from, to] = lines[index].split('|').map(Number); rules.push({ from, to }); index++; } return { rules, nextIndex: index }; }; // Function to parse updates from the input const parseUpdates = (lines, startIndex) => { const updates = []; for (let index = startIndex; index < lines.length; index++) { const line = lines[index].trim(); if (line) { const pages = line.split(',').map(Number); updates.push(pages); } } return updates; }; // Function to check if an update is in correct order const isCorrectOrder = (update, rules) => { const positions = new Map(); update.forEach((page, idx) => positions.set(page, idx)); return rules.every(({ from, to }) => { if (positions.has(from) && positions.has(to)) { return positions.get(from) < positions.get(to); } return true; }); }; // Function to reorder an update according to the rules using topological sort const reorderUpdate = (update, rules) => { const pagesSet = new Set(update); const graph = new Map(); const inDegree = new Map(); // Initialize graph and in-degree pagesSet.forEach(page => { graph.set(page, []); inDegree.set(page, 0); }); // Add edges based on rules rules.forEach(({ from, to }) => { if (pagesSet.has(from) && pagesSet.has(to)) { graph.get(from).push(to); inDegree.set(to, inDegree.get(to) + 1); } }); // Topological sort const queue = []; inDegree.forEach((degree, node) => { if (degree === 0) queue.push(node); }); const sorted = []; while (queue.length > 0) { const node = queue.shift(); sorted.push(node); for (const neighbor of graph.get(node)) { inDegree.set(neighbor, inDegree.get(neighbor) - 1); if (inDegree.get(neighbor) === 0) { queue.push(neighbor); } } } // If sorting is not possible (cycle detected), return original update return sorted.length === pagesSet.size ? sorted : update; }; // Main logic const { rules, nextIndex } = parseRules(lines); const updates = parseUpdates(lines, nextIndex); // Calculate the sum of middle page numbers after reordering incorrectly ordered updates const sum = updates.reduce((total, update) => { if (!isCorrectOrder(update, rules)) { const reordered = reorderUpdate(update, rules); const middleIndex = Math.floor(reordered.length / 2); total += reordered[middleIndex]; } return total; }, 0); 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? 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,"const fs = require('fs'); // Read the input file, parse per line const data = fs.readFileSync('input.txt', 'utf8'); const lines = data.trim().split('\n'); let totalCalibration = 0; for (const line of lines) { //Splits each line into the test value and a string of numbers. //Parses the test value as an integer. //Converts the list of number strings into an array of integers. const [testValueStr, numbersStr] = line.split(':'); const testValue = parseInt(testValueStr.trim()); const numbers = numbersStr.trim().split(' ').map(Number); // Determines the total number of possible operator combinations (2^n), since each position can be either + or * const n = numbers.length - 1; const totalCombos = 1 << n; let possible = false; // Loops through all possible combinations of + and *. // Uses bit manipulation to decide which operator to use at each position. // Evaluates the expression left to right according to the chosen operators. // Checks if the result equals the test value for (let i = 0; i < totalCombos; i++) { let result = numbers[0]; for (let j = 0; j < n; j++) { const op = (i & (1 << j)) ? '+' : '*'; if (op === '+') { result += numbers[j + 1]; } else { result *= numbers[j + 1]; } } if (result === testValue) { possible = true; break; } } //Add the value to the total calibration if (possible) { totalCalibration += testValue; } } 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? 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,"const fs = require('fs'); // Read the input file and parse the equations into an array of objects const getEquations = (filePath) => { return fs.readFileSync(filePath, 'utf8') .trim() .split('\n') .map(line => { const [testValue, numbers] = line.split(': '); return { testValue: Number(testValue), numbers: numbers.split(' ').map(Number) }; }); }; // Helper function to evaluate an equation given an operator configuration const evaluate = (numbers, operators) => { return numbers.reduce((acc, num, idx) => { if (idx === 0) return num; const operator = operators[idx - 1]; return operator === '+' ? acc + num : acc * num; }); }; // Helper function to generate all possible operator combinations for a given number of positions const generateOperators = (count) => { const result = []; const operators = ['+', '*']; const totalCombinations = Math.pow(2, count); for (let i = 0; i < totalCombinations; i++) { result.push([...Array(count)].map((_, idx) => operators[(i >> idx) & 1])); } return result; }; // Function to check if an equation can be solved with any combination of operators const isValidEquation = (testValue, numbers) => { const operatorCombinations = generateOperators(numbers.length - 1); return operatorCombinations.some(operators => evaluate(numbers, operators) === testValue); }; // Main function to calculate the total calibration result const calculateTotalCalibration = (filePath) => { const equations = getEquations(filePath); let totalCalibration = 0; equations.forEach(({ testValue, numbers }) => { if (isValidEquation(testValue, numbers)) { totalCalibration += testValue; } }); return totalCalibration; }; // Run the solution 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? 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,"const fs = require('fs'); // Read input from file and parse it const loadInput = (filePath) => { const input = fs.readFileSync(filePath, 'utf8').trim().split('\n'); return input.map(line => { const [testValue, numbers] = line.split(': '); return { testValue: parseInt(testValue), numbers: numbers.split(' ').map(Number) }; }); }; // Perform the left-to-right evaluation for a given sequence of numbers and operators const evaluateExpression = (numbers, operators) => { return numbers.reduce((result, num, index) => { if (index === 0) return num; const operator = operators[index - 1]; return operator === '+' ? result + num : result * num; }, 0); }; // Generate all combinations of operators for the given numbers const generateOperatorCombinations = (length) => { const ops = ['+', '*']; const combinations = []; const totalCombinations = Math.pow(2, length); for (let i = 0; i < totalCombinations; i++) { const combination = []; for (let j = 0; j < length; j++) { combination.push(ops[(i >> j) & 1]); } combinations.push(combination); } return combinations; }; // Check if a given test value can be achieved with the numbers and operators const isValidEquation = (testValue, numbers) => { const operatorCombinations = generateOperatorCombinations(numbers.length - 1); return operatorCombinations.some(operators => evaluateExpression(numbers, operators) === testValue); }; // Main function to calculate the total sum of valid test values const calculateTotalCalibration = (filePath) => { const equations = loadInput(filePath); return equations.reduce((sum, { testValue, numbers }) => { if (isValidEquation(testValue, numbers)) { return sum + testValue; } return sum; }, 0); }; // Call the main function and print the result const result = calculateTotalCalibration('input.txt'); 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? 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,"const fs = require('fs'); // Read the file and return the equations as an array of objects const parseInput = (path) => { const data = fs.readFileSync(path, 'utf8').trim().split('\n'); return data.map(line => { const [test, nums] = line.split(': '); return { testValue: +test, numbers: nums.split(' ').map(Number) }; }); }; // Evaluate a single expression with a list of operators applied left-to-right const calcExpression = (nums, ops) => { return nums.reduce((result, num, i) => { if (i === 0) return num; const op = ops[i - 1]; return op === '+' ? result + num : result * num; }, 0); }; // Generate all possible combinations of operators for a given number of positions const getOperatorCombinations = (n) => { const ops = ['+', '*']; const combinations = []; for (let i = 0; i < Math.pow(2, n); i++) { combinations.push([...Array(n)].map((_, j) => ops[(i >> j) & 1])); } return combinations; }; // Check if any combination of operators can satisfy the equation const checkValidEquation = (testValue, numbers) => { const operatorCombinations = getOperatorCombinations(numbers.length - 1); return operatorCombinations.some(operators => calcExpression(numbers, operators) === testValue); }; // Solve the challenge by summing up all valid test values const solveChallenge = (path) => { const equations = parseInput(path); return equations.reduce((sum, { testValue, numbers }) => { return checkValidEquation(testValue, numbers) ? sum + testValue : sum; }, 0); }; // Run the solution const result = solveChallenge('input.txt'); 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? 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,"const fs = require('fs'); // Read the input file and parse the equations const readInput = (filePath) => { return fs.readFileSync(filePath, 'utf8').trim().split('\n').map(line => { const [testValue, numbers] = line.split(': '); return { testValue: Number(testValue), numbers: numbers.split(' ').map(Number) }; }); }; // Function to evaluate an expression with a given operator configuration const evaluateExpression = (numbers, operators) => { let result = numbers[0]; for (let i = 0; i < operators.length; i++) { if (operators[i] === '+') { result += numbers[i + 1]; } else if (operators[i] === '*') { result *= numbers[i + 1]; } } return result; }; // Function to generate all possible operator combinations const generateOperatorCombinations = (length) => { const combinations = []; const operators = ['+', '*']; const totalCombinations = Math.pow(2, length); for (let i = 0; i < totalCombinations; i++) { let combo = []; for (let j = 0; j < length; j++) { combo.push(operators[(i >> j) & 1]); } combinations.push(combo); } return combinations; }; // Function to check if the equation is valid for a given set of numbers and operators const isValidEquation = (testValue, numbers) => { const operatorCombinations = generateOperatorCombinations(numbers.length - 1); for (let combo of operatorCombinations) { const result = evaluateExpression(numbers, combo); if (result === testValue) { return true; } } return false; }; // Main function to solve the problem const solve = (filePath) => { const equations = readInput(filePath); let totalCalibration = 0; for (const { testValue, numbers } of equations) { if (isValidEquation(testValue, numbers)) { totalCalibration += testValue; } } console.log(`Total calibration result: ${totalCalibration}`); }; // Run the solution 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? 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); const evaluate = (nums, ops) => { let result = nums[0]; for (let i = 0; i < ops.length; i++) { if (ops[i] === '+') { result += nums[i + 1]; } else if (ops[i] === '*') { result *= nums[i + 1]; } else if (ops[i] === '||') { result = parseInt(`${result}${nums[i + 1]}`, 10); } } return result; }; const solve = (line) => { const [target, numsStr] = line.split(':'); const nums = numsStr.trim().split(' ').map(Number); const n = nums.length; const operators = ['+', '*', '||']; const stack = [{ nums, ops: [] }]; while (stack.length > 0) { const { nums, ops } = stack.pop(); if (ops.length === n - 1) { if (evaluate(nums, ops) === parseInt(target, 10)) { return parseInt(target, 10); } } else { for (const op of operators) { stack.push({ nums, ops: [...ops, op] }); } } } return 0; }; let total = 0; for (const line of input) { total += solve(line); } 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? 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,"const fs = require('fs'); // Read the input file and convert it into an array of equations with test values and numbers const parseInputFile = (filePath) => { const inputData = fs.readFileSync(filePath, 'utf8').trim().split('\n'); return inputData.map(line => { const [testValue, numbers] = line.split(': '); return { testValue: Number(testValue), numbers: numbers.split(' ').map(Number) }; }); }; // Generate all possible operator combinations (+, *, ||) for a given length of numbers const generateOperatorCombinations = (length) => { const operators = ['+', '*', '||']; const totalCombinations = Math.pow(3, length); const combinations = []; for (let i = 0; i < totalCombinations; i++) { const combo = []; for (let j = 0; j < length; j++) { combo.push(operators[(i / Math.pow(3, j)) % 3 | 0]); } combinations.push(combo); } return combinations; }; // Function to concatenate two numbers when using the '||' operator const concatenateNumbers = (num1, num2) => { return parseInt(num1.toString() + num2.toString()); }; // Evaluate the expression considering all the operators (+, *, ||) between the numbers const evaluateWithOperators = (numbers, operators) => { return numbers.reduce((accum, num, index) => { if (index === 0) return num; const operator = operators[index - 1]; if (operator === '+') return accum + num; if (operator === '*') return accum * num; if (operator === '||') return concatenateNumbers(accum, num); return accum; }, 0); }; // Check if a given equation is valid by evaluating it with all possible operator combinations const isEquationValid = (testValue, numbers) => { const operatorCombinations = generateOperatorCombinations(numbers.length - 1); return operatorCombinations.some(operators => { return evaluateWithOperators(numbers, operators) === testValue; }); }; // Sum up the test values of all valid equations const calculateCalibrationResult = (filePath) => { const equations = parseInputFile(filePath); let totalResult = 0; equations.forEach(({ testValue, numbers }) => { if (isEquationValid(testValue, numbers)) { totalResult += testValue; } }); return totalResult; }; // Output the total calibration result const calibrationResult = calculateCalibrationResult('input.txt'); 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? 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,"const fs = require('fs'); // Read the input file const data = fs.readFileSync('input.txt', 'utf8'); const lines = data.trim().split('\n'); let totalCalibration = 0; for (const line of lines) { const [testValueStr, numbersStr] = line.split(':'); const testValue = parseInt(testValueStr.trim()); const numbers = numbersStr.trim().split(' ').map(Number); const n = numbers.length - 1; const totalCombos = Math.pow(3, n); let possible = false; for (let i = 0; i < totalCombos; i++) { let result = numbers[0]; let combo = i; for (let j = 0; j < n; j++) { const opCode = combo % 3; combo = Math.floor(combo / 3); const num = numbers[j + 1]; if (opCode === 0) { // Addition result += num; } else if (opCode === 1) { // Multiplication result *= num; } else { // Concatenation result = parseInt('' + result + num); } } if (result === testValue) { possible = true; break; } } if (possible) { totalCalibration += testValue; } } 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? 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,"const fs = require('fs'); // Read input file and split into lines const lines = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); // Function to evaluate a sequence of numbers with given operators const evaluateExpression = (numbers, operators) => { let result = numbers[0]; for (let i = 0; i < operators.length; i++) { const operator = operators[i]; const nextNumber = numbers[i + 1]; if (operator === '+') { result += nextNumber; } else if (operator === '*') { result *= nextNumber; } else if (operator === '||') { result = parseInt(`${result}${nextNumber}`, 10); } } return result; }; // Function to check if a given equation can be solved with operators const canSolveEquation = (target, numbers) => { const operatorOptions = ['+', '*', '||']; const stack = [{ numbers, operators: [] }]; while (stack.length > 0) { const { numbers, operators } = stack.pop(); // If all operators are placed, evaluate the expression if (operators.length === numbers.length - 1) { if (evaluateExpression(numbers, operators) === target) { return true; } } else { // Try adding each operator to the stack for (const op of operatorOptions) { stack.push({ numbers, operators: [...operators, op] }); } } } return false; }; // Main function to process all equations and calculate the total calibration result const calculateCalibrationResult = (lines) => { let total = 0; for (const line of lines) { const [targetStr, numbersStr] = line.split(':'); const target = parseInt(targetStr, 10); const numbers = numbersStr.trim().split(' ').map(Number); if (canSolveEquation(target, numbers)) { total += target; } } return total; }; // Output the total calibration result 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? 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,"const fs = require('fs'); // Read input file and parse it into an array of equations const readInput = (filePath) => { const data = fs.readFileSync(filePath, 'utf8').trim().split('\n'); return data.map(line => { const [testValue, numbers] = line.split(': '); return { testValue: parseInt(testValue), numbers: numbers.split(' ').map(Number) }; }); }; // Function to evaluate an expression with given numbers and operators const evaluateExpression = (numbers, operators) => { return numbers.reduce((result, num, index) => { if (index === 0) return num; const operator = operators[index - 1]; if (operator === '+') return result + num; if (operator === '*') return result * num; return result; }, 0); }; // Generate all possible combinations of operators (+, *, ||) for the numbers const generateOperatorCombinations = (length) => { const ops = ['+', '*', '||']; const combinations = []; const totalCombinations = Math.pow(3, length); for (let i = 0; i < totalCombinations; i++) { const combination = []; for (let j = 0; j < length; j++) { combination.push(ops[(i / Math.pow(3, j)) % 3 | 0]); } combinations.push(combination); } return combinations; }; // Concatenate two numbers if the operator is '||' const concatenate = (num1, num2) => { return parseInt(num1.toString() + num2.toString()); }; // Modify the evaluate function to handle '||' operator (concatenation) const evaluateExpressionWithConcatenation = (numbers, operators) => { return numbers.reduce((result, num, index) => { if (index === 0) return num; const operator = operators[index - 1]; if (operator === '+') return result + num; if (operator === '*') return result * num; if (operator === '||') return concatenate(result, num); return result; }, 0); }; // Check if an equation can be solved with the given numbers and test value const isValidEquation = (testValue, numbers) => { const operatorCombinations = generateOperatorCombinations(numbers.length - 1); return operatorCombinations.some(operators => { const result = evaluateExpressionWithConcatenation(numbers, operators); return result === testValue; }); }; // Calculate the total calibration result for valid equations const calculateTotalCalibration = (filePath) => { const equations = readInput(filePath); return equations.reduce((sum, { testValue, numbers }) => { if (isValidEquation(testValue, numbers)) { return sum + testValue; } return sum; }, 0); }; // Execute the function and output the result const result = calculateTotalCalibration('input.txt'); 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? 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,"const fs = require('fs'); const charMap = { ""^"": [0, -1], "">"": [1, 0], ""<"": [-1, 0], ""v"": [0, 1] }; let warehouse = []; let warehouseDone = false; let moves = []; let robotX = 0; let robotY = 0; let y = 0; const input = fs.readFileSync('input.txt', 'utf-8').split('\n'); input.forEach(line => { line = line.trim(); if (line !== """") { if (line.includes(""@"")) { robotX = line.indexOf(""@""); robotY = y; } if (warehouseDone) { moves.push(...line.split('').map(c => charMap[c])); } else { warehouse.push([...line]); } } else { warehouseDone = true; } y++; }); const width = warehouse[0].length; const height = warehouse.length; warehouse[robotY][robotX] = "".""; function canMove(x, y, direction) { while (0 <= x && x < width && 0 <= y && y < height) { x += direction[0]; y += direction[1]; if (warehouse[y][x] === ""#"") return false; if (warehouse[y][x] === ""."") return true; } return false; } function moveRobot(x, y) { moves.forEach(move => { if (canMove(x, y, move)) { let yy = y + move[1]; let xx = x + move[0]; if (warehouse[yy][xx] !== ""."") { while (warehouse[yy + move[1]][xx + move[0]] !== ""."") { xx += move[0]; yy += move[1]; } const temp = warehouse[yy + move[1]][xx + move[0]]; warehouse[yy + move[1]][xx + move[0]] = warehouse[y + move[1]][x + move[0]]; warehouse[y + move[1]][x + move[0]] = temp; } x += move[0]; y += move[1]; } }); } moveRobot(robotX, robotY); let result = 0; warehouse.forEach((line, y) => { line.forEach((char, x) => { if (char === ""O"") { result += 100 * y + x; } }); }); 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? 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,"const fs = require('fs'); const movementDict = { v: [1, 0], '^': [-1, 0], '>': [0, 1], '<': [0, -1] }; function readInputFile() { const data = fs.readFileSync('/Users/WW/Supahands/aoc-datasets/input.txt', 'utf8'); const lines = data.split('\n'); const warehouseMap = []; let movements = ''; let curPos = [0, 0]; let i = 0; while (lines[i] !== '') { if (lines[i].includes('@')) { curPos = [i, lines[i].indexOf('@')]; } warehouseMap.push(lines[i].split('')); i++; } i++; while (i < lines.length) { movements += lines[i]; i++; } return { warehouseMap, movements, curPos }; } function findOpenSpot(pos, move, warehouseMap) { while (true) { pos = [pos[0] + move[0], pos[1] + move[1]]; const posValue = warehouseMap[pos[0]]?.[pos[1]]; if (posValue === '#') return false; if (posValue === '.') return pos; } } function main() { const { warehouseMap, movements, curPos } = readInputFile(); let total = 0; let curPosLoc = curPos; for (const move of movements) { const destination = [ curPosLoc[0] + movementDict[move][0], curPosLoc[1] + movementDict[move][1] ]; const destinationValue = warehouseMap[destination[0]]?.[destination[1]]; if (destinationValue === 'O') { const openSpot = findOpenSpot(destination, movementDict[move], warehouseMap); if (openSpot) { warehouseMap[openSpot[0]][openSpot[1]] = 'O'; warehouseMap[destination[0]][destination[1]] = '@'; warehouseMap[curPosLoc[0]][curPosLoc[1]] = '.'; curPosLoc = destination; } } else if (destinationValue === '.') { warehouseMap[destination[0]][destination[1]] = '@'; warehouseMap[curPosLoc[0]][curPosLoc[1]] = '.'; curPosLoc = destination; } } for (let i = 0; i < warehouseMap.length; i++) { for (let j = 0; j < warehouseMap[i].length; j++) { if (warehouseMap[i][j] === 'O') { total += 100 * i + j; } } } console.log(`The sum of all boxes' GPS coordinates is ${total}`); } 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? 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf-8').split('\n'); let warehouseMap = []; let movements = """"; let curPos = [0, 0]; let total = 0; const movementDict = { ""v"": [1, 0], ""^"": [-1, 0], "">"": [0, 1], ""<"": [0, -1] }; function findOpenSpot(pos, move) { while (true) { pos = [pos[0] + move[0], pos[1] + move[1]]; const posValue = warehouseMap[pos[0]][pos[1]]; if (posValue === ""#"") return false; else if (posValue === ""."") return pos; } } let i = 0; while (input[i] !== """") { if (input[i].includes(""@"")) { curPos = [i, input[i].indexOf(""@"")]; } warehouseMap.push(input[i].split('')); i++; } i++; while (i < input.length) { movements += input[i]; i++; } for (const move of movements) { const destination = [curPos[0] + movementDict[move][0], curPos[1] + movementDict[move][1]]; const destinationValue = warehouseMap[destination[0]][destination[1]]; if (destinationValue === ""O"") { const openSpot = findOpenSpot(destination, movementDict[move]); if (openSpot) { warehouseMap[openSpot[0]][openSpot[1]] = ""O""; warehouseMap[destination[0]][destination[1]] = ""@""; warehouseMap[curPos[0]][curPos[1]] = "".""; curPos = destination; } } else if (destinationValue === ""."") { warehouseMap[destination[0]][destination[1]] = ""@""; warehouseMap[curPos[0]][curPos[1]] = "".""; curPos = destination; } } for (let i = 0; i < warehouseMap.length; i++) { for (let j = 0; j < warehouseMap[i].length; j++) { if (warehouseMap[i][j] === ""O"") { total += 100 * i + j; } } } 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? 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,"const fs = require('fs'); // Read and parse the input const adv_input = fs.readFileSync('input.txt', 'utf-8'); let [gridPart, steps_list] = adv_input.split(""\n\n""); const step_lines = steps_list.split(/\r?\n/).filter(line => line.trim().length > 0); let steps = step_lines.map(line => line.trim()).join(""""); let grid = gridPart.split(/\r?\n/).map(line => line.trim().split('')); let grid2 = grid.map(row => row.slice()); const shape = grid.length; const directions = { ""^"": [-1, 0], ""v"": [1, 0], "">"": [0, 1], ""<"": [0, -1] }; function next_step(grid, current_pos, step) { const [x, y] = current_pos; const [dx, dy] = directions[step]; const nx = x + dx; const ny = y + dy; if (grid[nx][ny] === ""#"") { return [x, y]; } else if (grid[nx][ny] === ""O"") { const next_block_pos = next_step(grid, [nx, ny], step); if (next_block_pos[0] !== nx || next_block_pos[1] !== ny) { grid[nx][ny] = grid[x][y]; grid[x][y] = "".""; return [nx, ny]; } else { return [x, y]; } } else if (grid[nx][ny] === ""."") { grid[nx][ny] = grid[x][y]; grid[x][y] = "".""; return [nx, ny]; } } function main(grid, steps) { let init_pos; for (let i = 0; i < shape; i++) { for (let j = 0; j < shape; j++) { if (grid[i][j] === ""@"") { init_pos = [i, j]; } } } let current_pos = init_pos; for (const step of steps) { current_pos = next_step(grid, current_pos, step); } let result = 0; for (let x = 0; x < shape; x++) { for (let y = 0; y < shape; y++) { if (grid[x][y] === ""O"") { result += 100 * x + y; } } } return result; } 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? 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,"const fs = require('fs'); const charMap = { '^': [0, -1], '>': [1, 0], '<': [-1, 0], 'v': [0, 1] }; function canMove(x, y, direction, width, height, warehouse) { while (x >= 0 && x < width && y >= 0 && y < height) { x += direction[0]; y += direction[1]; if (warehouse[y][x] === '#') { return false; } if (warehouse[y][x] === '.') { return true; } } return false; } function moveRobot(x, y, moves, warehouse, width, height) { for (const move of moves) { if (canMove(x, y, move, width, height, warehouse)) { let yy = y + move[1]; let xx = x + move[0]; if (warehouse[yy][xx] !== '.') { while (warehouse[yy + move[1]]?.[xx + move[0]] !== '.') { xx += move[0]; yy += move[1]; } [warehouse[yy + move[1]][xx + move[0]], warehouse[y + move[1]][x + move[0]]] = [warehouse[y + move[1]][x + move[0]], warehouse[yy + move[1]][xx + move[0]]]; } x += move[0]; y += move[1]; } } } function main() { const data = fs.readFileSync('input.txt', 'utf8').split('\n'); let warehouse = []; let moves = []; let robotX = 0, robotY = 0; let warehouseDone = false; for (let y = 0; y < data.length; y++) { const line = data[y].trim(); if (line !== '') { if (line.includes('@')) { robotX = line.indexOf('@'); robotY = y; } if (warehouseDone) { moves.push(...line.split('').map(c => charMap[c])); } else { warehouse.push(line.split('')); } } else { warehouseDone = true; } } const width = warehouse[0].length; const height = warehouse.length; warehouse[robotY][robotX] = '.'; moveRobot(robotX, robotY, moves, warehouse, width, height); let result = 0; for (let y = 0; y < warehouse.length; y++) { for (let x = 0; x < warehouse[y].length; x++) { if (warehouse[y][x] === 'O') { result += 100 * y + x; } } } console.log(`result=${result}`); } 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? 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..# #.....# ####### maplines[r][c] === '#'; const isRobot = (r, c) => maplines[r][c] === '@'; const isBox = (r, c) => maplines[r][c] === 'O'; const isOpen = (r, c) => maplines[r][c] === '.'; const replaceAt = (r, c, x) => { maplines[r] = maplines[r].substring(0, c) + x + maplines[r].substring(c + 1); } let robot; for (let r = 0; r < maplines.length; r++) { for (let c = 0; c < maplines[r].length; c++) { if (isRobot(r, c)) { robot = [r, c]; break; } } } console.log(maplines, robot); for (let instruction of instructions) { let cr = robot[0]; let cc = robot[1]; let boxesToMove = 0; if (instruction === '^') { for (let r = robot[0] - 1; r >= 0; r--) { if (isWall(r, cc)) { break; } else if (isBox(r, cc)) { boxesToMove++; } else if (isOpen(r, cc)) { if (boxesToMove > 0) { replaceAt(r, cc, 'O'); } replaceAt(cr, cc, '.'); replaceAt(cr - 1, cc, '@'); robot = [cr - 1, cc]; break; } } } else if (instruction === 'v') { for (let r = robot[0] + 1; r <= rows; r++) { if (isWall(r, cc)) { break; } else if (isBox(r, cc)) { boxesToMove++; } else if (isOpen(r, cc)) { if (boxesToMove > 0) { replaceAt(r, cc, 'O'); } replaceAt(cr, cc, '.'); replaceAt(cr + 1, cc, '@'); robot = [cr + 1, cc]; break; } } } else if (instruction === '<') { for (let c = robot[1] - 1; c >= 0; c--) { if (isWall(cr, c)) { break; } else if (isBox(cr, c)) { boxesToMove++; } else if (isOpen(cr, c)) { if (boxesToMove > 0) { replaceAt(cr, c, 'O'); } replaceAt(cr, cc, '.'); replaceAt(cr, cc - 1, '@'); robot = [cr, cc - 1]; break; } } } else if (instruction === '>') { for (let c = robot[1] + 1; c <= cols; c++) { if (isWall(cr, c)) { break; } else if (isBox(cr, c)) { boxesToMove++; } else if (isOpen(cr, c)) { if (boxesToMove > 0) { replaceAt(cr, c, 'O'); } replaceAt(cr, cc, '.'); replaceAt(cr, cc + 1, '@'); robot = [cr, cc + 1]; break; } } } } let sum = 0; for (let r = 0; r < maplines.length; r++) { for (let c = 0; c < maplines[r].length; c++) { if (isBox(r, c)) { sum+= 100 * r + c; } } } console.log(sum); } function part2() { const maplines = rawmap.split('\n'); let m = []; for (let r = 0; r < maplines.length; r++) { let ml = ''; for (let c = 0; c < maplines[r].length; c++) { if (maplines[r][c] === 'O') { ml += '[]' } else if (maplines[r][c] === '.') { ml += '..' } else if (maplines[r][c] === '#') { ml += '##' } else if (maplines[r][c] === '@') { ml += '@.' } } m.push(ml); } const rows = m.length const cols = m[0].length; const isWall = (r, c) => m[r][c] === '#'; const isRobot = (r, c) => m[r][c] === '@'; const isBox = (r, c) => isLBox(r, c) || isRBox(r, c); const isLBox = (r, c) => m[r][c] === '['; const isRBox = (r, c) => m[r][c] === ']'; const isOpen = (r, c) => m[r][c] === '.'; const replaceAt = (r, c, x) => { m[r] = m[r].substring(0, c) + x + m[r].substring(c + 1); } const canBoxMoveUp = (r, c) => { if (m[r - 1][c] === '#' || m[r - 1][c + 1] === '#') { return false; } if (m[r - 1][c] === '.' && m[r - 1][c + 1] === '.') { return true; } if (m[r - 1][c] === '[') { // box right above return canBoxMoveUp(r - 1, c); } if (m[r - 1][c] === ']' && m[r - 1][c + 1] === '[') { // 2 boxes return canBoxMoveUp(r - 1, c - 1) && canBoxMoveUp(r - 1, c + 1); } if (m[r - 1][c] === ']') { return canBoxMoveUp(r - 1, c - 1); } if (m[r - 1][c + 1] === '[') { return canBoxMoveUp(r - 1, c + 1); } } const moveBoxUp = (r, c) => { function move() { replaceAt(r - 1, c, '['); replaceAt(r - 1, c + 1, ']'); replaceAt(r, c, '.'); replaceAt(r, c + 1, '.'); } if (!isBox(r - 1, c) && !isBox(r - 1, c + 1)) { move(); } else { if (isLBox(r - 1, c)) { moveBoxUp(r - 1, c); move(); } else if (isRBox(r - 1, c) && isLBox(r - 1, c + 1)) { moveBoxUp(r - 1, c - 1); moveBoxUp(r - 1, c + 1); move(); } else if (isRBox(r - 1, c)) { moveBoxUp(r - 1, c - 1); move(); } else if (isLBox(r - 1, c + 1)) { moveBoxUp(r - 1, c + 1); move(); } } } const moveBoxDown = (r, c) => { function move() { replaceAt(r + 1, c, '['); replaceAt(r + 1, c + 1, ']'); replaceAt(r, c, '.'); replaceAt(r, c + 1, '.'); } if (!isBox(r + 1, c) && !isBox(r + 1, c + 1)) { move(); } else { if (isLBox(r + 1, c)) { moveBoxDown(r + 1, c); move(); } else if (isRBox(r + 1, c) && isLBox(r + 1, c + 1)) { moveBoxDown(r + 1, c - 1); moveBoxDown(r + 1, c + 1); move(); } else if (isRBox(r + 1, c)) { moveBoxDown(r + 1, c - 1); move(); } else if (isLBox(r + 1, c + 1)) { moveBoxDown(r + 1, c + 1); move(); } } } const canBoxMoveDown = (r, c) => { if (m[r + 1][c] === '#' || m[r + 1][c + 1] === '#') { return false; } if (m[r + 1][c] === '.' && m[r + 1][c + 1] === '.') { return true; } if (m[r + 1][c] === '[') { // box right above return canBoxMoveDown(r + 1, c); } if (m[r + 1][c] === ']' && m[r + 1][c + 1] === '[') { // 2 boxes return canBoxMoveDown(r + 1, c - 1) && canBoxMoveDown(r + 1, c + 1); } if (m[r + 1][c] === ']') { return canBoxMoveDown(r + 1, c - 1); } if (m[r + 1][c + 1] === '[') { return canBoxMoveDown(r + 1, c + 1); } } let robot; for (let r = 0; r < m.length; r++) { for (let c = 0; c < m[r].length; c++) { if (isRobot(r, c)) { robot = [r, c]; break; } } } let index = 0; for (let instruction of instructions) { // console.log(m); // console.log('====', index, '====', instruction); index++; let cr = robot[0]; let cc = robot[1]; let boxesToMove = []; if (instruction === '^') { const nextR = cr - 1; if (isWall(nextR, cc)) continue; if (isBox(nextR, cc)) { if (isLBox(nextR, cc)) { if (canBoxMoveUp(nextR, cc)) { moveBoxUp(nextR, cc); } else { continue; } } else { if (canBoxMoveUp(nextR, cc - 1)) { moveBoxUp(nextR, cc - 1); } else { continue; } } } if (isOpen(nextR, cc) || isBox(nextR, cc)) { replaceAt(cr, cc, '.'); replaceAt(nextR, cc, '@'); robot = [nextR, cc]; } } else if (instruction === 'v') { const nextR = cr + 1; if (isWall(nextR, cc)) continue; if (isBox(nextR, cc)) { if (isLBox(nextR, cc)) { if (canBoxMoveDown(nextR, cc)) { moveBoxDown(nextR, cc); } else { continue; } } else { if (canBoxMoveDown(nextR, cc - 1)) { moveBoxDown(nextR, cc - 1); } else { continue; } } } if (isOpen(nextR, cc) || isBox(nextR, cc)) { replaceAt(cr, cc, '.'); replaceAt(nextR, cc, '@'); robot = [nextR, cc]; } } else if (instruction === '<') { for (let c = robot[1] - 1; c >= 0; c--) { if (isWall(cr, c)) { break; } else if (isLBox(cr, c)) { boxesToMove.push([cr, c]); } else if (isOpen(cr, c)) { for (let b of boxesToMove) { replaceAt(b[0], b[1] - 1, '['); replaceAt(b[0], b[1], ']'); } replaceAt(cr, cc, '.'); replaceAt(cr, cc - 1, '@'); robot = [cr, cc - 1]; break; } } } else if (instruction === '>') { for (let c = robot[1] + 1; c <= cols; c++) { if (isWall(cr, c)) { break; } else if (isLBox(cr, c)) { boxesToMove.push([cr, c]); } else if (isOpen(cr, c)) { for (let b of boxesToMove) { replaceAt(b[0], b[1] + 1, '['); replaceAt(b[0], b[1] + 2, ']'); } replaceAt(cr, cc, '.'); replaceAt(cr, cc + 1, '@'); robot = [cr, cc + 1]; break; } } } } console.log(m); let sum = 0; for (let r = 0; r < m.length; r++) { for (let c = 0; c < m[r].length; c++) { if (isLBox(r, c)) { sum += 100 * r + c; } } } console.log(sum); } 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### ': [0, 1], 'v': [1, 0], '<': [0, -1]}; return [pos[0] + moveDict[move][0], pos[1] + moveDict[move][1]]; } function getChars(c) { if (c === '@') { return '@.'; } else if (c === 'O') { return '[]'; } else { return c + c; } } function canPush(grid, pos, move) { if (['<', '>'].includes(move)) { const nextPos = getNext(getNext(pos, move), move); if (grid[nextPos[0]][nextPos[1]] === '.') { return true; } if (grid[nextPos[0]][nextPos[1]] === '[' || grid[nextPos[0]][nextPos[1]] === ']') { return canPush(grid, nextPos, move); } return false; } if (['^', 'v'].includes(move)) { let left, right; if (grid[pos[0]][pos[1]] === '[') { left = pos; right = [pos[0], pos[1] + 1]; } else { left = [pos[0], pos[1] - 1]; right = pos; } const nextLeft = getNext(left, move); const nextRight = getNext(right, move); if (grid[nextLeft[0]][nextLeft[1]] === '#' || grid[nextRight[0]][nextRight[1]] === '#') { return false; } return (grid[nextLeft[0]][nextLeft[1]] === '.' || canPush(grid, nextLeft, move)) && (grid[nextRight[0]][nextRight[1]] === '.' || canPush(grid, nextRight, move)); } } function push(grid, pos, move) { if (['<', '>'].includes(move)) { let j = pos[1]; while (grid[pos[0]][j] !== '.') { [, j] = getNext([pos[0], j], move); } if (j < pos[1]) { grid[pos[0]].splice(j, pos[1] - j, ...grid[pos[0]].slice(j + 1, pos[1] + 1)); } else { grid[pos[0]].splice(pos[1] + 1, j - pos[1], ...grid[pos[0]].slice(pos[1], j)); } } if (['^', 'v'].includes(move)) { let left, right; if (grid[pos[0]][pos[1]] === '[') { left = pos; right = [pos[0], pos[1] + 1]; } else { left = [pos[0], pos[1] - 1]; right = pos; } const nextLeft = getNext(left, move); const nextRight = getNext(right, move); if (grid[nextLeft[0]][nextLeft[1]] === '[') { push(grid, nextLeft, move); } else { if (grid[nextLeft[0]][nextLeft[1]] === ']') { push(grid, nextLeft, move); } if (grid[nextRight[0]][nextRight[1]] === '[') { push(grid, nextRight, move); } } grid[nextLeft[0]][nextLeft[1]] = '['; grid[nextRight[0]][nextRight[1]] = ']'; grid[left[0]][left[1]] = '.'; grid[right[0]][right[1]] = '.'; } } function printGrid(grid) { for (const line of grid) { console.log(line.join('')); } } let grid = []; let moves = []; const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8').split('\n'); for (const line of input) { if (line.startsWith('#')) { let row = ''; for (const c of line) { row += getChars(c); } grid.push([...row]); } else if (line !== '') { moves.push(...line); } } let robotPos; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === '@') { robotPos = [i, j]; break; } } if (robotPos) break; } for (const move of moves) { const [nextI, nextJ] = getNext(robotPos, move); if (grid[nextI][nextJ] === '.') { grid[robotPos[0]][robotPos[1]] = '.'; grid[nextI][nextJ] = '@'; robotPos = [nextI, nextJ]; } else if (grid[nextI][nextJ] === '[' || grid[nextI][nextJ] === ']') { if (canPush(grid, [nextI, nextJ], move)) { push(grid, [nextI, nextJ], move); grid[robotPos[0]][robotPos[1]] = '.'; grid[nextI][nextJ] = '@'; robotPos = [nextI, nextJ]; } } } let total = 0; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === '[') { total += 100 * i + j; } } } 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### ': [0, 1], 'v': [1, 0], '<': [0, -1] }; getNext(pos, move) { const [dx, dy] = WarehouseSolver.MOVE_DICT[move]; return [pos[0] + dx, pos[1] + dy]; } // Grid character expansion getChars(c) { switch (c) { case '@': return '@.'; case 'O': return '[]'; default: return c + c; } } // Parsing and grid setup parseInput(input) { for (const line of input.split('\n')) { if (line.startsWith('#')) { const row = [...line].map(c => this.getChars(c)).join(''); this.grid.push([...row]); } else if (line.trim() !== '') { this.moves.push(...line.trim()); } } this.findRobot(); } findRobot() { for (let i = 0; i < this.grid.length; i++) { for (let j = 0; j < this.grid[i].length; j++) { if (this.grid[i][j] === '@') { this.robotPos = [i, j]; return; } } } } // Movement validation canPush(pos, move) { if (['<', '>'].includes(move)) { return this.canPushHorizontal(pos, move); } return this.canPushVertical(pos, move); } canPushHorizontal(pos, move) { const nextPos = this.getNext(this.getNext(pos, move), move); const nextChar = this.grid[nextPos[0]][nextPos[1]]; if (nextChar === '.') return true; if (['[', ']'].includes(nextChar)) { return this.canPush(nextPos, move); } return false; } canPushVertical(pos, move) { const [left, right] = this.getBoxEdges(pos); const nextLeft = this.getNext(left, move); const nextRight = this.getNext(right, move); if (this.grid[nextLeft[0]][nextLeft[1]] === '#' || this.grid[nextRight[0]][nextRight[1]] === '#') { return false; } return (this.grid[nextLeft[0]][nextLeft[1]] === '.' || this.canPush(nextLeft, move)) && (this.grid[nextRight[0]][nextRight[1]] === '.' || this.canPush(nextRight, move)); } getBoxEdges(pos) { return this.grid[pos[0]][pos[1]] === '[' ? [pos, [pos[0], pos[1] + 1]] : [[pos[0], pos[1] - 1], pos]; } // Pushing mechanics push(pos, move) { return ['<', '>'].includes(move) ? this.pushHorizontal(pos, move) : this.pushVertical(pos, move); } pushHorizontal(pos, move) { let j = pos[1]; while (this.grid[pos[0]][j] !== '.') { [, j] = this.getNext([pos[0], j], move); } const slice = j < pos[1] ? this.grid[pos[0]].slice(j + 1, pos[1] + 1) : this.grid[pos[0]].slice(pos[1], j); this.grid[pos[0]].splice( j < pos[1] ? j : pos[1] + 1, Math.abs(j - pos[1]), ...slice ); } pushVertical(pos, move) { const [left, right] = this.getBoxEdges(pos); const nextLeft = this.getNext(left, move); const nextRight = this.getNext(right, move); // Recursive push for existing boxes if (['[', ']'].includes(this.grid[nextLeft[0]][nextLeft[1]])) { this.push(nextLeft, move); } if (['[', ']'].includes(this.grid[nextRight[0]][nextRight[1]])) { this.push(nextRight, move); } // Update grid this.grid[nextLeft[0]][nextLeft[1]] = '['; this.grid[nextRight[0]][nextRight[1]] = ']'; this.grid[left[0]][left[1]] = '.'; this.grid[right[0]][right[1]] = '.'; } // Main solving method solve(input) { this.parseInput(input); for (const move of this.moves) { const [nextI, nextJ] = this.getNext(this.robotPos, move); if (this.grid[nextI][nextJ] === '.') { this.moveRobot(nextI, nextJ); } else if (['[', ']'].includes(this.grid[nextI][nextJ])) { if (this.canPush([nextI, nextJ], move)) { this.push([nextI, nextJ], move); this.moveRobot(nextI, nextJ); } } } return this.calculateTotal(); } moveRobot(nextI, nextJ) { this.grid[this.robotPos[0]][this.robotPos[1]] = '.'; this.grid[nextI][nextJ] = '@'; this.robotPos = [nextI, nextJ]; } calculateTotal() { let total = 0; for (let i = 0; i < this.grid.length; i++) { for (let j = 0; j < this.grid[i].length; j++) { if (this.grid[i][j] === '[') { total += 100 * i + j; } } } return total; } // Optional debug method printGrid() { console.log(this.grid.map(row => row.join('')).join('\n')); } } // Usage const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8'); const solver = new WarehouseSolver(); 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### ': [0, 1], 'v': [1, 0], '<': [0, -1] }, init: function() { this.grid = []; this.moves = []; this.robotPos = null; }, getNext: function(pos, move) { const [dx, dy] = WarehouseSolver.MOVE_DICT[move]; return [pos[0] + dx, pos[1] + dy]; }, getChars: function(c) { switch (c) { case '@': return '@.'; case 'O': return '[]'; default: return c + c; } }, parseInput: function(input) { input.split('\n').forEach(line => { if (line.startsWith('#')) { const row = [...line].map(c => this.getChars(c)).join(''); this.grid.push([...row]); } else if (line.trim() !== '') { this.moves.push(...line.trim()); } }); this.findRobot(); }, findRobot: function() { for (let i = 0; i < this.grid.length; i++) { for (let j = 0; j < this.grid[i].length; j++) { if (this.grid[i][j] === '@') { this.robotPos = [i, j]; return; } } } }, canPush: function(pos, move) { return ['<', '>'].includes(move) ? this.canPushHorizontal(pos, move) : this.canPushVertical(pos, move); }, canPushHorizontal: function(pos, move) { const nextPos = this.getNext(this.getNext(pos, move), move); const nextChar = this.grid[nextPos[0]][nextPos[1]]; if (nextChar === '.') return true; if (['[', ']'].includes(nextChar)) { return this.canPush(nextPos, move); } return false; }, canPushVertical: function(pos, move) { const [left, right] = this.getBoxEdges(pos); const nextLeft = this.getNext(left, move); const nextRight = this.getNext(right, move); if (this.grid[nextLeft[0]][nextLeft[1]] === '#' || this.grid[nextRight[0]][nextRight[1]] === '#') { return false; } return (this.grid[nextLeft[0]][nextLeft[1]] === '.' || this.canPush(nextLeft, move)) && (this.grid[nextRight[0]][nextRight[1]] === '.' || this.canPush(nextRight, move)); }, getBoxEdges: function(pos) { return this.grid[pos[0]][pos[1]] === '[' ? [pos, [pos[0], pos[1] + 1]] : [[pos[0], pos[1] - 1], pos]; }, push: function(pos, move) { return ['<', '>'].includes(move) ? this.pushHorizontal(pos, move) : this.pushVertical(pos, move); }, pushHorizontal: function(pos, move) { let j = pos[1]; while (this.grid[pos[0]][j] !== '.') { [, j] = this.getNext([pos[0], j], move); } const slice = j < pos[1] ? this.grid[pos[0]].slice(j + 1, pos[1] + 1) : this.grid[pos[0]].slice(pos[1], j); this.grid[pos[0]].splice( j < pos[1] ? j : pos[1] + 1, Math.abs(j - pos[1]), ...slice ); }, pushVertical: function(pos, move) { const [left, right] = this.getBoxEdges(pos); const nextLeft = this.getNext(left, move); const nextRight = this.getNext(right, move); if (['[', ']'].includes(this.grid[nextLeft[0]][nextLeft[1]])) { this.push(nextLeft, move); } if (['[', ']'].includes(this.grid[nextRight[0]][nextRight[1]])) { this.push(nextRight, move); } this.grid[nextLeft[0]][nextLeft[1]] = '['; this.grid[nextRight[0]][nextRight[1]] = ']'; this.grid[left[0]][left[1]] = '.'; this.grid[right[0]][right[1]] = '.'; }, moveRobot: function(nextI, nextJ) { this.grid[this.robotPos[0]][this.robotPos[1]] = '.'; this.grid[nextI][nextJ] = '@'; this.robotPos = [nextI, nextJ]; }, calculateTotal: function() { let total = 0; for (let i = 0; i < this.grid.length; i++) { for (let j = 0; j < this.grid[i].length; j++) { if (this.grid[i][j] === '[') { total += 100 * i + j; } } } return total; }, solve: function(input) { this.init(); this.parseInput(input); this.moves.forEach(move => { const [nextI, nextJ] = this.getNext(this.robotPos, move); if (this.grid[nextI][nextJ] === '.') { this.moveRobot(nextI, nextJ); } else if (['[', ']'].includes(this.grid[nextI][nextJ])) { if (this.canPush([nextI, nextJ], move)) { this.push([nextI, nextJ], move); this.moveRobot(nextI, nextJ); } } }); return this.calculateTotal(); }, printGrid: function() { console.log(this.grid.map(row => row.join('')).join('\n')); } }; // Usage const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf8'); 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? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### ': [0, 1], 'v': [1, 0], '<': [0, -1] }; static getNextPosition(pos, move) { const [dx, dy] = this.MOVES[move]; return [pos[0] + dx, pos[1] + dy]; } } class GridParser { static parseCharacter(c) { switch (c) { case '@': return '@.'; case 'O': return '[]'; default: return c + c; } } static parse(input) { const grid = []; const moves = []; input.split('\n').forEach(line => { if (line.startsWith('#')) { const row = [...line].map(c => GridParser.parseCharacter(c)).join(''); grid.push([...row]); } else if (line.trim()) { moves.push(...line.trim()); } }); return { grid, moves }; } } class WarehouseSolver { constructor() { this.grid = []; this.moves = []; this.robotPos = null; } solve(input) { const { grid, moves } = GridParser.parse(input); this.grid = grid; this.moves = moves; this.findRobot(); this.executeMoves(); return this.calculateTotal(); } findRobot() { for (let i = 0; i < this.grid.length; i++) { for (let j = 0; j < this.grid[i].length; j++) { if (this.grid[i][j] === '@') { this.robotPos = [i, j]; return; } } } } executeMoves() { this.moves.forEach(move => { const [nextI, nextJ] = GridMovement.getNextPosition(this.robotPos, move); if (this.grid[nextI][nextJ] === '.') { this.moveRobot(nextI, nextJ); } else if (['[', ']'].includes(this.grid[nextI][nextJ])) { if (this.canPush([nextI, nextJ], move)) { this.push([nextI, nextJ], move); this.moveRobot(nextI, nextJ); } } }); } canPush(pos, move) { return ['<', '>'].includes(move) ? this.canPushHorizontal(pos, move) : this.canPushVertical(pos, move); } canPushHorizontal(pos, move) { const nextPos = GridMovement.getNextPosition( GridMovement.getNextPosition(pos, move), move ); const nextChar = this.grid[nextPos[0]][nextPos[1]]; if (nextChar === '.') return true; if (['[', ']'].includes(nextChar)) { return this.canPush(nextPos, move); } return false; } canPushVertical(pos, move) { const [left, right] = this.getBoxEdges(pos); const nextLeft = GridMovement.getNextPosition(left, move); const nextRight = GridMovement.getNextPosition(right, move); if (this.grid[nextLeft[0]][nextLeft[1]] === '#' || this.grid[nextRight[0]][nextRight[1]] === '#') { return false; } return (this.grid[nextLeft[0]][nextLeft[1]] === '.' || this.canPush(nextLeft, move)) && (this.grid[nextRight[0]][nextRight[1]] === '.' || this.canPush(nextRight, move)); } getBoxEdges(pos) { return this.grid[pos[0]][pos[1]] === '[' ? [pos, [pos[0], pos[1] + 1]] : [[pos[0], pos[1] - 1], pos]; } push(pos, move) { return ['<', '>'].includes(move) ? this.pushHorizontal(pos, move) : this.pushVertical(pos, move); } pushHorizontal(pos, move) { let j = pos[1]; while (this.grid[pos[0]][j] !== '.') { [, j] = GridMovement.getNextPosition([pos[0], j], move); } const slice = j < pos[1] ? this.grid[pos[0]].slice(j + 1, pos[1] + 1) : this.grid[pos[0]].slice(pos[1], j); this.grid[pos[0]].splice( j < pos[1] ? j : pos[1] + 1, Math.abs(j - pos[1]), ...slice ); } pushVertical(pos, move) { const [left, right] = this.getBoxEdges(pos); const nextLeft = GridMovement.getNextPosition(left, move); const nextRight = GridMovement.getNextPosition(right, move); if (['[', ']'].includes(this.grid[nextLeft[0]][nextLeft[1]])) { this.push(nextLeft, move); } if (['[', ']'].includes(this.grid[nextRight[0]][nextRight[1]])) { this.push(nextRight, move); } this.grid[nextLeft[0]][nextLeft[1]] = '['; this.grid[nextRight[0]][nextRight[1]] = ']'; this.grid[left[0]][left[1]] = '.'; this.grid[right[0]][right[1]] = '.'; } moveRobot(nextI, nextJ) { this.grid[this.robotPos[0]][this.robotPos[1]] = '.'; this.grid[nextI][nextJ] = '@'; this.robotPos = [nextI, nextJ]; } calculateTotal() { let total = 0; for (let i = 0; i < this.grid.length; i++) { for (let j = 0; j < this.grid[i].length; j++) { if (this.grid[i][j] === '[') { total += 100 * i + j; } } } return total; } printGrid() { console.log(this.grid.map(row => row.join('')).join('\n')); } } // Usage const fs = require('fs'); const solver = new WarehouseSolver(); const input = fs.readFileSync('input.txt', 'utf8'); 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. ""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","const fs = require('fs'); // Functions for operations function comboOperand(op, registers) { const comboOperands = { 4: ""A"", 5: ""B"", 6: ""C"" }; return op < 4 ? op : registers[comboOperands[op]]; } function adv(op, registers) { return Math.floor(registers[""A""] / Math.pow(2, comboOperand(op, registers))); } function bxl(op, registers) { return registers[""B""] ^ op; } function bst(op, registers) { return comboOperand(op, registers) % 8; } function jnz(instPointer, op, registers) { return registers[""A""] !== 0 ? op : instPointer + 2; } function bxc(op, registers) { return registers[""B""] ^ registers[""C""]; } function out(op, registers) { return (comboOperand(op, registers) % 8).toString(); } function bdv(op, registers) { return adv(op, registers); } function cdv(op, registers) { return adv(op, registers); } // Read the input file fs.readFile('input.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const lines = data.split('\n'); const registers = {}; let program = []; // Parse the input data lines.forEach(line => { if (line.includes(""Register"")) { const parts = line.trim().split("" ""); registers[parts[1].slice(0, -1)] = parseInt(parts[2]); } else if (line.includes(""Program"")) { program = line.trim().slice(8).split("","").map(Number); } }); let instructionPointer = 0; const output = []; // Execute the program while (instructionPointer < program.length) { const opcode = program[instructionPointer]; const operand = program[instructionPointer + 1]; switch (opcode) { case 0: registers[""A""] = adv(operand, registers); break; case 1: registers[""B""] = bxl(operand, registers); break; case 2: registers[""B""] = bst(operand, registers); break; case 3: instructionPointer = jnz(instructionPointer, operand, registers); continue; case 4: registers[""B""] = bxc(operand, registers); break; case 5: output.push(out(operand, registers)); break; case 6: registers[""B""] = bdv(operand, registers); break; case 7: registers[""C""] = cdv(operand, registers); break; default: throw new Error(`Unknown opcode: ${opcode}`); } instructionPointer += 2; } console.log(""Program output:"", output.join("","")); });",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. ""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","const fs = require('fs'); // OpCodes const ADV = 0; const BXL = 1; const BST = 2; const JNZ = 3; const BXC = 4; const OUT = 5; const BDV = 6; const CDV = 7; // Function to handle operand conversion function getComboOperand(operand, reg) { if (operand >= 0 && operand <= 3) { return operand; } if (operand >= 4 && operand <= 6) { return reg[String.fromCharCode(65 + operand - 4)]; } throw new Error(`Unexpected operand ${operand}`); } fs.readFile('input.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const lines = data.split('\n'); // Register initialization const reg = { A: parseInt(lines[0].split("": "")[1]), B: parseInt(lines[1].split("": "")[1]), C: parseInt(lines[2].split("": "")[1]), }; // Parsing the instructions const instructions = lines[4].split("": "")[1].split("","").map(Number); let output = []; let instrPtr = 0; // Execute instructions while (instrPtr < instructions.length) { let jump = false; const [opcode, operand] = instructions.slice(instrPtr, instrPtr + 2); switch (opcode) { case ADV: reg['A'] = Math.floor(reg['A'] / Math.pow(2, getComboOperand(operand, reg))); break; case BXL: reg['B'] ^= operand; break; case BST: reg['B'] = getComboOperand(operand, reg) % 8; break; case JNZ: if (reg['A'] !== 0) { instrPtr = operand; jump = true; } break; case BXC: reg['B'] ^= reg['C']; break; case OUT: output.push(getComboOperand(operand, reg) % 8); break; case BDV: reg['B'] = Math.floor(reg['A'] / Math.pow(2, getComboOperand(operand, reg))); break; case CDV: reg['C'] = Math.floor(reg['A'] / Math.pow(2, getComboOperand(operand, reg))); break; default: throw new Error(`Unexpected opcode ${opcode}`); } if (!jump) { instrPtr += 2; } } // Output the result console.log(output.join("","")); });",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. ""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","const fs = require(""fs""); const inputText = ""./input.txt""; fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error('Error reading file:', err); return; } const parsedData = {}; data = data.split(""\n"").map(line => { if (line.includes(""Register"")) { line = line.replace(""Register "", """"); } line = line.split("": ""); if (line[0] === ""Program"") { line[1] = line[1].split("","").map(Number); } else line[1] = parseInt(line[1]); if (line[0]) parsedData[line[0]] = line[1]; }) console.log(part1(parsedData)); }); const part1 = (data) => { let output = []; let { A, B, C, Program: program } = data; let instructionPointer = 0; const getCombo = operand => { if (operand <= 3) return operand; if (operand === 4) return A; if (operand === 5) return B; if (operand === 6) return C; } const performInstruction = (opcode, operand) => { switch (opcode) { case 0: A = Math.trunc(A / (2 ** getCombo(operand))); break; case 1: B = B ^ operand; break; case 2: B = getCombo(operand) % 8; break; case 3: if (A !== 0) { instructionPointer = operand; return; } break; case 4: B = B ^ C; break; case 5: output.push(getCombo(operand) % 8); break; case 6: B = Math.trunc(A / (2 ** getCombo(operand))); break; case 7: C = Math.trunc(A / (2 ** getCombo(operand))); break; } instructionPointer += 2; } while (instructionPointer < program.length) { const opcode = program[instructionPointer]; const operand = program[instructionPointer + 1]; performInstruction(opcode, operand); } return output.join("",""); }",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. ""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","const fs = require('fs'); function runProgram(registers, program) { let { A, B, C } = registers; let ip = 0; let output = []; while (ip < program.length) { const opcode = program[ip]; const operand = program[ip + 1]; let operandValue; // Determine operand type if (operand >= 0 && operand <= 3) { operandValue = operand; } else if (operand === 4) { operandValue = A; } else if (operand === 5) { operandValue = B; } else if (operand === 6) { operandValue = C; } else { break; // Invalid operand } switch (opcode) { case 0: { // adv const denominator = Math.pow(2, operandValue); A = Math.trunc(A / denominator); ip += 2; break; } case 1: { // bxl B ^= operand; ip += 2; break; } case 2: { // bst B = operandValue % 8; ip += 2; break; } case 3: { // jnz if (A !== 0) { ip = operand; } else { ip += 2; } break; } case 4: { // bxc B ^= C; ip += 2; break; } case 5: { // out output.push(operandValue % 8); ip += 2; break; } case 6: { // bdv const denominator6 = Math.pow(2, operandValue); B = Math.trunc(A / denominator6); ip += 2; break; } case 7: { // cdv const denominator7 = Math.pow(2, operandValue); C = Math.trunc(A / denominator7); ip += 2; break; } default: ip = program.length; // Halt on invalid opcode } } return output.join(','); } // Read and parse input.txt const inputPath = 'input.txt'; const input = fs.readFileSync(inputPath, 'utf-8').trim().split('\n'); let registers = { A: 0, B: 0, C: 0 }; let program = []; input.forEach(line => { if (line.startsWith('Register A:')) { registers.A = parseInt(line.split(':')[1]); } else if (line.startsWith('Register B:')) { registers.B = parseInt(line.split(':')[1]); } else if (line.startsWith('Register C:')) { registers.C = parseInt(line.split(':')[1]); } else if (line.startsWith('Program:')) { program = line.split(':')[1].split(',').map(Number); } }); // Execute program and display output const result = runProgram(registers, program); 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. ""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","// solution for https://adventofcode.com/2024/day/17 part 1 ""use strict"" const input = Deno.readTextFileSync(""day17-input.txt"").trim() var registerA = 0 var registerB = 0 var registerC = 0 const program = [ ] var pointer = 0 var output = [ ] function main() { processInput() runProgram() console.log(""the answer is"", output.join("","")) } function processInput() { const lines = input.split(""\n"") registerA = parseInt(lines.shift().trim().replace(""Register A: "", """")) registerB = parseInt(lines.shift().trim().replace(""Register B: "", """")) registerC = parseInt(lines.shift().trim().replace(""Register C: "", """")) lines.shift() // blank line const strProgram = lines.shift().trim().replace(""Program: "", """").split("","") for (const str of strProgram) { program.push(parseInt(str)) } } /////////////////////////////////////////////////////////////////////////////// function runProgram() { while (true) { const opcode = program[pointer] if (opcode == undefined) { return } const operand = program[pointer + 1] if (opcode == 0) { adv(operand); pointer += 2; continue } if (opcode == 1) { bxl(operand); pointer += 2; continue } if (opcode == 2) { bst(operand); pointer += 2; continue } if (opcode == 3) { jnz(operand); continue } if (opcode == 4) { bxc(operand); pointer += 2; continue } if (opcode == 5) { out(operand); pointer += 2; continue } if (opcode == 6) { bdv(operand); pointer += 2; continue } if (opcode == 7) { cdv(operand); pointer += 2; continue } } } function adv(operand) { registerA = Math.floor(registerA / Math.pow(2, combo(operand))) } function bdv(operand) { registerB = Math.floor(registerA / Math.pow(2, combo(operand))) } function cdv(operand) { registerC = Math.floor(registerA / Math.pow(2, combo(operand))) } function bst(operand) { registerB = combo(operand) % 8 } function bxl(operand) { registerB = registerB ^ operand } function bxc(operand) { registerB = registerB ^ registerC } function jnz(operand) { pointer = (registerA == 0) ? pointer + 2 : operand } function out(operand) { output.push(combo(operand) % 8) } function combo(operand) { if (operand < 4) { return operand } if (operand == 4) { return registerA } if (operand == 5) { return registerB } if (operand == 6) { return registerC } console.log(""error in function 'combo'"") } console.time(""execution time"") main() 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. ""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,"const fs = require('fs'); let data = fs.readFileSync('input.txt', 'utf8'); let [regA, regB, regC] = [ parseInt(/Register A: (\d+)/.exec(data)[1]), parseInt(/Register B: (\d+)/.exec(data)[1]), parseInt(/Register C: (\d+)/.exec(data)[1]) ]; let regIP = 0, regSkipInc = false; let prog = /Program: (\d+(?:,\d+)*)/.exec(data)[1].split(','); let stack = []; const cOp = { '0': () => 0, '1': () => 1, '2': () => 2, '3': () => 3, '4': () => regA, '5': () => regB, '6': () => regC, '7': () => null }; const opcodes = { '0': (op) => { regA = Math.floor(regA / (2 ** cOp[op]())); return regA; }, '1': (op) => { regB ^= op; return regB; }, '2': (op) => { regB = ((cOp[op]() % 8) + 8) % 8; return regB; }, '3': (op) => { if (regA !== 0) { regIP = parseInt(op); regSkipInc = true; return true; } return false; }, '4': (op) => { regB ^= regC; return regB; }, '5': (op) => { let val = ((cOp[op]() % 8) + 8) % 8; stack.push(val); return val; }, '6': (op) => { regB = Math.floor(regA / (2 ** cOp[op]())); return regB; }, '7': (op) => { regC = Math.floor(regA / (2 ** cOp[op]())); return regC; } }; const main = () => { while (regIP < prog.length) { regSkipInc = false; opcodes[prog[regIP]](prog[regIP + 1]); if (!regSkipInc) regIP += 2; } }; main(); console.log(prog.toString()); console.log(""Part1"", stack.toString()); const main2 = () => { let found = false; let a = 0, s = 1; while (!found) { regA = a; regIP = 0; stack = []; main(); if (stack.toString() === prog.toString()) { found = true; regA = a; } else if (stack.toString() === prog.slice(-s).toString()) { a *= 8; s++; } else { a++; } } console.log(""Part2"", regA); }; 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. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"import { readFileSync } from 'node:fs' import { argv0 } from 'node:process'; let data = readFileSync('input.txt', { encoding: 'utf8', flag: 'r' }); let regA = parseInt(/Register A: (\d+)/.exec(data)[1]); let regB = parseInt(/Register B: (\d+)/.exec(data)[1]); let regC = parseInt(/Register C: (\d+)/.exec(data)[1]); let regIP = 0; // Instruction Pointer/Programme Counter let regSkipInc = false; let prog = /Program: (\d+(,\d+)*)/.exec(data)[1].split(','); let stack = []; const cOp = { '0': () => { return 0 }, '1': () => { return 1 }, '2': () => { return 2 }, '3': () => { return 3 }, '4': () => { return regA }, '5': () => { return regB }, '6': () => { return regC }, '7': () => { return null } } // Combo Operands const opcodes = { '0' : (op) => { // adv regA = Math.floor(regA / (Math.pow(2, cOp[op]()))); return regA; }, '1': (op) => { // bxl regB ^= op; return regB; }, '2': (op) => { // bst regB = ((cOp[op]() % 8) + 8) % 8; return regB; }, '3': (op) => { // jnz if (regA != 0) { regIP = parseInt(op); regSkipInc = true; return true; } else { return false; } }, '4': (op) => { // bxc regB ^= regC; return regB; }, '5': (op) => { // out let val = ((cOp[op]() % 8) + 8) % 8; stack.push(val); return val; }, '6': (op) => { // bdv regB = Math.floor(regA / (Math.pow(2, cOp[op]()))); return regB; }, '7': (op) => { // cdv regC = Math.floor(regA / (Math.pow(2, cOp[op]()))); return regC; } } const main = () => { while (regIP < prog.length) { regSkipInc = false; opcodes[prog[regIP]](prog[regIP+1]); if (!regSkipInc) regIP += 2; } } main(); console.log(prog.toString()); console.log(""Part1"",stack.toString()); const main2 = () => { let found = false; let a = 0; let s = 1; while (!found) { regA = a; regIP = 0; stack = []; main(); if (stack.toString() === prog.toString()) { found = true; regA = a; } else if (stack.toString() === prog.slice(-1 * s).toString()) { a *= 8; s++; } else { a++; } } console.log(""part2"",regA); } 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. ""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,"const fs = require('fs'); let data = fs.readFileSync('input.txt', { encoding: 'utf8', flag: 'r' }); let regA = parseInt(/Register A: (\d+)/.exec(data)[1]); let regB = parseInt(/Register B: (\d+)/.exec(data)[1]); let regC = parseInt(/Register C: (\d+)/.exec(data)[1]); let regIP = 0; // Instruction Pointer/Program Counter let regSkipInc = false; let prog = /Program: (\d+(,\d+)*)/.exec(data)[1].split(','); let stack = []; const cOp = { '0': () => { return 0 }, '1': () => { return 1 }, '2': () => { return 2 }, '3': () => { return 3 }, '4': () => { return regA }, '5': () => { return regB }, '6': () => { return regC }, '7': () => { return null } }; // Combo Operands const opcodes = { '0': (op) => { // adv regA = Math.floor(regA / (Math.pow(2, cOp[op]()))); return regA; }, '1': (op) => { // bxl regB ^= op; return regB; }, '2': (op) => { // bst regB = ((cOp[op]() % 8) + 8) % 8; return regB; }, '3': (op) => { // jnz if (regA !== 0) { regIP = parseInt(op); regSkipInc = true; return true; } else { return false; } }, '4': (op) => { // bxc regB ^= regC; return regB; }, '5': (op) => { // out let val = ((cOp[op]() % 8) + 8) % 8; stack.push(val); return val; }, '6': (op) => { // bdv regB = Math.floor(regA / (Math.pow(2, cOp[op]()))); return regB; }, '7': (op) => { // cdv regC = Math.floor(regA / (Math.pow(2, cOp[op]()))); return regC; } }; const main = () => { while (regIP < prog.length) { regSkipInc = false; opcodes[prog[regIP]](prog[regIP + 1]); if (!regSkipInc) regIP += 2; } }; main(); console.log(prog.toString()); console.log(""Part1"", stack.toString()); const main2 = () => { let found = false; let a = 0; let s = 1; while (!found) { regA = a; regIP = 0; stack = []; main(); if (stack.toString() === prog.toString()) { found = true; regA = a; } else if (stack.toString() === prog.slice(-1 * s).toString()) { a *= 8; s++; } else { a++; } } console.log(""Part2"", regA); }; 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. ""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,"const fs = require('fs'); const run = (fileContents) => { let data = parseInput(fileContents); let result1 = runProgram(structuredClone(data.registers), structuredClone(data.program)); let result2 = part2(structuredClone(data.program)); return { part1: result1.join(','), part2: result2 }; } /** * Part 2 solution * @param {number[]} program The program to run * @returns {number} The lowest correct initial value for A */ const part2 = (program) => { let targetOutput = structuredClone(program).reverse().join(''); let answers = []; findInitialValue(0, program.length - 1, program, targetOutput, answers); return Math.min(...answers); } /** * This recursively searches for a number to use for A. The program is always outputting * (A/8^outputIndex)%8. This works in reverse solving for the last digit first by adding * the previous partial sum to 8^outputIndexValue multiplied by x. X is a variable * between 0 and 7. One of these values is guaranteed to give us the next value necessary since * it covers all of the possible 3 bit values. If the output string matches we record * the value since there could be multiple possible solutions for this. if not we check if * it is partially matches for at least the values we have been working generate so far. * If it does match then continue with this partial sum to the next power to see if a value can be made * * @param {number} sum Sum of the answer to this point * @param {number} power The current power of 8 being checked for * @param {number[]} program The program to run * @param {string} target The reversed concatenated program * @param {number[]} answers The answers that have been found so far */ const findInitialValue = (sum, power, program, target, answers) => { for (let x = 0; x < 8; x++) { let partialSum = sum + Math.pow(8, power) * x; let registers = new Map(); registers.set('A', partialSum); registers.set('B', 0); registers.set('C', 0); let output = runProgram(registers, program); let revStrOutput = output.reverse().join(''); if (revStrOutput === target) { answers.push(partialSum); return; } else { let startOutput = revStrOutput.substring(0, target.length - power); if (target.startsWith(startOutput)) { findInitialValue(partialSum, power - 1, program, target, answers); } } } } /** * The program computer as described in Part 1 * @param {Map} registers The values to use for the program * @param {number[]} program The program to run * @returns {number[]} The output generated by the program */ const runProgram = (registers, program) => { let output = []; const comboOperandValue = (operand) => { if (operand >= 0 && operand <= 3) { return operand; } else if (operand === 4) { return registers.get('A'); } else if (operand === 5) { return registers.get('B'); } else if (operand === 6) { return registers.get('C'); } throw new Error(""Invalid Combo Operand:"", operand); } let current = 0; while (current < program.length) { let opCode = program[current]; let operand = program[current + 1]; let incrementCurrent = true; if (opCode === 0) { let numerator = registers.get(""A""); let operandVal = comboOperandValue(operand); let denominator = Math.pow(2, operandVal); registers.set('A', Math.floor(numerator / denominator)); } else if (opCode === 1) { let bVal = registers.get('B'); registers.set('B', bVal ^ operand); } else if (opCode === 2) { let operandVal = comboOperandValue(operand); registers.set('B', operandVal & 7); } else if (opCode === 3) { if (registers.get('A') !== 0) { current = operand; incrementCurrent = false; } } else if (opCode === 4) { let bVal = registers.get('B'); let cVal = registers.get('C'); registers.set('B', bVal ^ cVal); } else if (opCode === 5) { let operandVal = comboOperandValue(operand); output.push(operandVal & 7); } else if (opCode === 6) { let numerator = registers.get(""A""); let operandVal = comboOperandValue(operand); let denominator = Math.pow(2, operandVal); registers.set('B', Math.floor(numerator / denominator)); } else if (opCode === 7) { let numerator = registers.get(""A""); let operandVal = comboOperandValue(operand); let denominator = Math.pow(2, operandVal); registers.set('C', Math.floor(numerator / denominator)); } else { throw new Error(""Invalid OpCode:"", opCode); } if (incrementCurrent) current += 2; } return output; } /** * Parse the input into usable data * @param {string[]} fileContents The lines of the input file as a string array * @returns {registers: Map, number[]} The registers and program commands from the input file */ const parseInput = (fileContents) => { let registerMode = true; let registers = new Map(); let program; for (let line of fileContents) { if (line === '') { registerMode = false; continue; } if (registerMode) { let matches = line.match(/Register ([ABC]): (\d+)/); registers.set(matches[1], parseInt(matches[2])); } else { let matches = line.match(/Program: ([\d,]+)/); program = matches[1].split(',').map(num => parseInt(num)); } } return { registers, program }; } // Read the input.txt file and call the run function fs.readFile('input.txt', 'utf-8', (err, data) => { if (err) throw err; console.log(run(data.split('\n'))); });",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. ""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,"// solution for https://adventofcode.com/2024/day/17 part 2 // analysing *MY* puzzle entry I came to some conclusions: // // - register A is the main register that holds data and commands the execution // - register B and register C only exist for helping temporarily // - near the end of the program there is the *only* output instruction (outputs some_value % 8) // - there is *only* one jump instruction, it is in the last position, if register A is // zero it finishes the execution, otherwise it jumps back to the first line of the program // // - register A % 8 (its *THREE BITS* TO THE RIGHT) controls the value of each output // - register A / pow(8, n) (its *OTHER BITS*) controls how many loops (outputs) will exist ""use strict"" const input = Deno.readTextFileSync(""day17-input.txt"").trim() var originalA = 0 // unused var originalB = 0 var originalC = 0 const program = [ ] function main() { processInput() const register = search(BigInt(0), 1) console.log(""the answer is"", parseInt(register)) } function processInput() { const lines = input.split(""\n"") originalA = BigInt(lines.shift().trim().replace(""Register A: "", """")) originalB = BigInt(lines.shift().trim().replace(""Register B: "", """")) originalC = BigInt(lines.shift().trim().replace(""Register C: "", """")) lines.shift() // blank line const tokens = lines.shift().trim().replace(""Program: "", """").split("","") for (const token of tokens) { program.push(parseInt(token)) } } /////////////////////////////////////////////////////////////////////////////// function search(register, tail) { // wants to match the tail // 'tail' means the length of the tail for (let delta = 0; delta < 8; delta++) { const newRegister = register * BigInt(8) + BigInt(delta) const output = runProgram(newRegister) if (program.at(-tail) != output.at(-tail)) { continue } // tails don't match if (program.length == output.length) { return newRegister } // solved! const ultimateRegister = search(newRegister, tail + 1) if (ultimateRegister != 0) { return ultimateRegister } } return 0 } /////////////////////////////////////////////////////////////////////////////// function runProgram(register) { let registerA = register let registerB = originalB let registerC = originalC let pointer = 0 const output = [ ] while (true) { const opcode = program[pointer] if (opcode == undefined) { return output } const operand = BigInt(program[pointer + 1]) if (opcode == 0) { adv(operand); pointer += 2; continue } if (opcode == 1) { bxl(operand); pointer += 2; continue } if (opcode == 2) { bst(operand); pointer += 2; continue } if (opcode == 3) { jnz(operand); continue } if (opcode == 4) { bxc(operand); pointer += 2; continue } if (opcode == 5) { out(operand); pointer += 2; continue } if (opcode == 6) { bdv(operand); pointer += 2; continue } if (opcode == 7) { cdv(operand); pointer += 2; continue } } function adv(operand) { registerA = registerA / pow(BigInt(2), combo(operand)) } // BigInt dismisses Math.floor function bdv(operand) { registerB = registerA / pow(BigInt(2), combo(operand)) } // BigInt dismisses Math.floor function cdv(operand) { registerC = registerA / pow(BigInt(2), combo(operand)) } // BigInt dismisses Math.floor function bst(operand) { registerB = combo(operand) % BigInt(8) } function bxl(operand) { registerB = registerB ^ operand } function bxc(operand) { registerB = registerB ^ registerC } function jnz(operand) { pointer = (registerA == 0) ? pointer + 2 : parseInt(operand) } function out(operand) { output.push(combo(operand) % BigInt(8)) } function combo(operand) { if (operand < 4) { return operand } if (operand == 4) { return registerA } if (operand == 5) { return registerB } if (operand == 6) { return registerC } console.log(""error in function 'combo'"") } function pow(base, expoent) { // necessary because Math.pow doesn't accept BigInt let result = BigInt(1) for (let n = BigInt(0); n < expoent; n++) { result *= base } return result } } /////////////////////////////////////////////////////////////////////////////// console.time(""execution time"") main() 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! 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,"const fs = require('fs'); // Read the first 1024 coordinates from input.txt const data = fs.readFileSync('input.txt', 'utf8'); const lines = data.trim().split('\n').slice(0, 1024); // Initialize a 71x71 grid const gridSize = 71; const grid = Array.from({ length: gridSize }, () => Array(gridSize).fill(0)); // Mark the corrupted cells for (const line of lines) { const [xStr, yStr] = line.split(','); const x = parseInt(xStr, 10); const y = parseInt(yStr, 10); if (x >= 0 && x < gridSize && y >= 0 && y < gridSize) { grid[y][x] = 1; // Mark as corrupted } } // BFS to find the shortest path function bfs(startX, startY, endX, endY) { const visited = Array.from({ length: gridSize }, () => Array(gridSize).fill(false)); const queue = [{ x: startX, y: startY, steps: 0 }]; visited[startY][startX] = true; const directions = [ { dx: 0, dy: -1 }, // up { dx: 0, dy: 1 }, // down { dx: -1, dy: 0 }, // left { dx: 1, dy: 0 }, // right ]; while (queue.length > 0) { const { x, y, steps } = queue.shift(); if (x === endX && y === endY) { console.log(steps); return; } for (const { dx, dy } of directions) { const nx = x + dx; const ny = y + dy; if ( nx >= 0 && nx < gridSize && ny >= 0 && ny < gridSize && !visited[ny][nx] && grid[ny][nx] === 0 ) { visited[ny][nx] = true; queue.push({ x: nx, y: ny, steps: steps + 1 }); } } } console.log('No path found'); } 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! 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,"const fs = require('fs'); // Parses the input file and returns a list of tuples containing integer pairs. function parseInput(filePath) { const file = fs.readFileSync(filePath, 'utf-8').split('\n'); return file.map(line => line.trim().split(',').map(Number)); } // Initializes a square grid of the given size with all cells set to '.' function initializeGrid(size) { return Array.from({ length: size }, () => Array(size).fill('.')); } // Simulates the falling of bytes in a grid function simulateFallingBytes(grid, bytePositions, numBytes) { for (let i = 0; i < numBytes; i++) { const [x, y] = bytePositions[i]; grid[y][x] = '#'; } } // Finds the shortest path in a grid from the top-left corner to the bottom-right corner function findShortestPath(grid) { const size = grid.length; const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; const queue = [[0, 0, 0]]; // [x, y, steps] const visited = new Set(); visited.add('0,0'); while (queue.length > 0) { const [x, y, steps] = queue.shift(); if (x === size - 1 && y === size - 1) { return steps; } for (const [dx, dy] of directions) { const nx = x + dx; const ny = y + dy; if (nx >= 0 && nx < size && ny >= 0 && ny < size && grid[ny][nx] === '.' && !visited.has(`${nx},${ny}`)) { visited.add(`${nx},${ny}`); queue.push([nx, ny, steps + 1]); } } } return -1; // No path found } // Main function const filePath = 'input.txt'; const bytePositions = parseInput(filePath); 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}`);",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! 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,"// solution for https://adventofcode.com/2024/day/18 part 1 ""use strict"" const input = Deno.readTextFileSync(""day18-input.txt"").trim() const width = 71 const height = 71 const map = [ ] const BIG = 1000 * 1000 // means cell not walked function main() { makeMap() processInput() walk() // showMap() console.log(""the answer is"", map[width - 1][height - 1].distance) } function makeMap() { for (let row = 0; row < height; row++) { const line = [ ] map.push(line) for (let col = 0; col < width; col++) { line.push(createCell(row, col)) } } } function createCell(row, col) { return { ""row"": row, ""col"": col, ""blocked"": false, ""distance"": BIG } } function processInput() { const lines = input.split(""\n"") for (let n = 0; n < 1024; n++) { const coords = lines.shift().trim().split("","") const row = parseInt(coords.shift()) const col = parseInt(coords.shift()) map[row][col].blocked = true } } /////////////////////////////////////////////////////////////////////////////// function walk() { const homeCell = map[0][0] homeCell.distance = 0 let cellsToWalk = [ homeCell ] while (true) { const newCellsToWalk = [ ] for (const cell of cellsToWalk) { const row = cell.row const col = cell.col const distance = cell.distance + 1 grabCell(row - 1, col, distance, newCellsToWalk) grabCell(row + 1, col, distance, newCellsToWalk) grabCell(row, col - 1, distance, newCellsToWalk) grabCell(row, col + 1, distance, newCellsToWalk) } cellsToWalk = newCellsToWalk if (cellsToWalk.length == 0) { return } } } function grabCell(row, col, distance, newCellsToWalk) { if (row < 0) { return } if (col < 0) { return } if (row == height) { return } if (col == width) { return } const cell = map[row][col] if (cell.blocked) { return } if (cell.distance <= distance) { return } cell.distance = distance newCellsToWalk.push(cell) } /////////////////////////////////////////////////////////////////////////////// function showMap() { for (const line of map) { let s = """" for (const cell of line) { let c = ""."" if (cell.blocked) { c = ""#"" } if (cell.distance != BIG) { c = ""O"" } s += c } console.log(s) } } console.time(""execution time"") main() 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! 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,"const fs = require('fs'); const input_text = fs.readFileSync('input.txt', 'utf-8').split('\n'); const grid_size = 70; const num_fallen = 1024; const bytes = new Set(); for (let i = 0; i < num_fallen; i++) { const [byte_x, byte_y] = input_text[i].split("",""); bytes.add([parseInt(byte_x), parseInt(byte_y)].toString()); } const movements = [[-1, 0], [1, 0], [0, 1], [0, -1]]; const explored = new Set(); const discovered = [[0, 0, 0]]; while (discovered.length > 0) { discovered.sort((a, b) => a[0] - b[0]); const [distance, byte_x, byte_y] = discovered.shift(); if (!explored.has([byte_x, byte_y].toString())) { explored.add([byte_x, byte_y].toString()); if (byte_x === byte_y && byte_x === grid_size) { console.log(distance); break; } for (const movement of movements) { const new_position = [byte_x + movement[0], byte_y + movement[1]]; const new_position_str = new_position.toString(); if ( !bytes.has(new_position_str) && !explored.has(new_position_str) && new_position.every(coord => coord >= 0 && coord <= grid_size) ) { discovered.push([distance + 1, ...new_position]); } } } }",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! 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,"const fs = require('fs'); // Read the input file and parse the coordinates const lines = fs.readFileSync('input.txt', 'utf8').trim().split(""\n""); const coords = new Set(lines.slice(0, 1024).map(line => { const [x, y] = line.split("",""); return `${x},${y}`; })); const dd = [[1, 0], [0, 1], [-1, 0], [0, -1]]; const N = 70; // Heuristic for A* function h(i, j) { return Math.abs(N - i) + Math.abs(N - j); } function inGrid(i, j) { return i >= 0 && i <= N && j >= 0 && j <= N && !coords.has(`${i},${j}`); } const q = [[h(0, 0), 0, 0]]; // [cost, i, j] const cost = {}; while (q.length > 0) { // Sort by cost (A* logic) q.sort((a, b) => a[0] - b[0]); const [c, i, j] = q.shift(); if (cost[`${i},${j}`] !== undefined) { continue; } cost[`${i},${j}`] = c - h(i, j); if (i === N && j === N) { console.log(cost[`${i},${j}`]); break; } for (const [di, dj] of dd) { const ii = i + di; const jj = j + dj; if (inGrid(ii, jj)) { q.push([cost[`${i},${j}`] + 1 + h(ii, jj), ii, jj]); } } }",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! 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","const fs = require('fs'); const {log} = require('console'); const bytes = fs.readFileSync('input.txt', 'utf-8').split('\n').map(line => line.split(',').map(x => parseInt(x))); const cols = 70; const rows = 70; let walls = bytes.slice(0, 1024); const start = { row: 0, col: 0, g: 0, h: 140, f: 0 }; const end = { row: 70, col: 70, g: 0, h: 0, f: 0 }; // A* pathfinding algorithm function astar(start, end) { const openSet = []; const closedSet = []; openSet.push(start); while (openSet.length > 0) { // Find the node with the lowest total cost in the open set let currentNode = openSet[0]; for (let i = 1; i < openSet.length; i++) { if (openSet[i].f < currentNode.f || (openSet[i].f === currentNode.f && openSet[i].h < currentNode.h)) { currentNode = openSet[i]; } } // Remove the current node from the open set openSet.splice(openSet.indexOf(currentNode), 1); closedSet.push(currentNode); // If the current node is the goal, reconstruct the path if (currentNode.row === end.row && currentNode.col === end.col) { let path = []; let temp = currentNode; while (temp) { path.push(temp); temp = temp.parent; } return path.reverse(); } // Generate neighbors of the current node const neighbors = []; const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Right, Down, Left, Up for (let dir of directions) { const neighborRow = currentNode.row + dir[0]; const neighborCol = currentNode.col + dir[1]; if (isValidCell(neighborRow, neighborCol)) { const neighbor = { row: neighborRow, col: neighborCol, g: currentNode.g + 1, // Cost to move to a neighboring cell is 1 h: heuristic({row: neighborRow, col: neighborCol}, end), f: 0, parent: currentNode, }; neighbor.f = neighbor.g + neighbor.h; // Check if the neighbor is already in the closed set if (closedSet.some((node) => node.row === neighbor.row && node.col === neighbor.col)) { continue; } // Check if the neighbor is already in the open set const openSetNode = openSet.find((node) => node.row === neighbor.row && node.col === neighbor.col); if (!openSetNode || neighbor.g < openSetNode.g) { openSet.push(neighbor); } } } } } // Helper function to calculate the heuristic (Manhattan distance) function heuristic(a, b) { return Math.abs(a.row - b.row) + Math.abs(a.col - b.col); } // Helper function to check if a cell is valid and not an obstacle function isValidCell(row, col) { if (row < 0 || row > rows || col < 0 || col > cols) { return false; } return !walls.some(([r, c]) => r === row && c === col); } // console.log(bytes); // console.log(walls); let path = astar(start, end); console.log('part 1', path.length - 1); // for (let p of path) { // console.log(p.row,p.col) // } let wallsEnd = 1025; while (true) { console.log(wallsEnd); walls = bytes.slice(0, wallsEnd); if (!astar(start, end)) { break; } wallsEnd++; } 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! 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","const fs = require('fs'); const l = fs.readFileSync('input.txt', 'utf-8').split('\n').map(line => line.split(',').map(Number)); const max_x = Math.max(...l.map(coord => coord[0])); const max_y = Math.max(...l.map(coord => coord[1])); function P2() { for (let find = 1024; find < l.length; find++) { const grid = Array.from({ length: max_x + 1 }, () => Array(max_y + 1).fill(""."")); for (let i = 0; i < find; i++) { const [x, y] = l[i]; grid[x][y] = ""#""; } function bfs(grid, start, end) { const rows = grid.length; const cols = grid[0].length; const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; const queue = [[start, 0]]; const visited = new Set(); while (queue.length > 0) { const [[x, y], dist] = queue.shift(); if (x === end[0] && y === end[1]) { return dist; } if (visited.has(`${x},${y}`) || grid[x][y] === ""#"") { continue; } visited.add(`${x},${y}`); for (const [dx, dy] of directions) { const nx = x + dx; const ny = y + dy; if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && !visited.has(`${nx},${ny}`)) { queue.push([[nx, ny], dist + 1]); } } } return -1; } if (bfs(grid, [0, 0], [max_x, max_y]) === -1) { return l[find - 1]; } } } 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! 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","const fs = require('fs'); // Read all coordinates from input.txt const data = fs.readFileSync('input.txt', 'utf8'); const lines = data.trim().split('\n'); const gridSize = 71; const grid = Array.from({ length: gridSize }, () => Array(gridSize).fill(0)); function bfs(startX, startY, endX, endY) { const visited = Array.from({ length: gridSize }, () => Array(gridSize).fill(false)); const queue = [{ x: startX, y: startY }]; visited[startY][startX] = true; const directions = [ { dx: 0, dy: -1 }, // up { dx: 0, dy: 1 }, // down { dx: -1, dy: 0 }, // left { dx: 1, dy: 0 }, // right ]; while (queue.length > 0) { const { x, y } = queue.shift(); if (x === endX && y === endY) { return true; // Path exists } for (const { dx, dy } of directions) { const nx = x + dx; const ny = y + dy; if ( nx >= 0 && nx < gridSize && ny >= 0 && ny < gridSize && !visited[ny][nx] && grid[ny][nx] === 0 ) { visited[ny][nx] = true; queue.push({ x: nx, y: ny }); } } } return false; // No path found } for (let i = 0; i < lines.length; i++) { const [xStr, yStr] = lines[i].split(','); const x = parseInt(xStr, 10); const y = parseInt(yStr, 10); if (x >= 0 && x < gridSize && y >= 0 && y < gridSize) { grid[y][x] = 1; // Mark as corrupted } // Check if path is still available if (!bfs(0, 0, gridSize - 1, gridSize - 1)) { console.log(`${x},${y}`); break; } }",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! 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","// solution for https://adventofcode.com/2024/day/18 part 2 // expecting NO duplicated coordinates! ""use strict"" const input = Deno.readTextFileSync(""day18-input.txt"").trim() const width = 71 const height = 71 const map = [ ] const strCoordinates = [ ] function main() { makeMap() processInput() console.log(""the answer is"", findTheFirstBlockingByte()) } function makeMap() { for (let row = 0; row < height; row++) { const line = [ ] map.push(line) for (let col = 0; col < width; col++) { line.push(createCell(row, col)) } } } function createCell(row, col) { return { ""row"": row, ""col"": col, ""blockRound"": 1000 * 1000, ""walkRound"": -1 } } function processInput() { const lines = input.split(""\n"") while (lines.length != 0) { const str = lines.shift().trim() strCoordinates.push(str) const coords = str.split("","") const row = parseInt(coords.shift()) const col = parseInt(coords.shift()) map[row][col].blockRound = strCoordinates.length - 1 } } /////////////////////////////////////////////////////////////////////////////// function walk(walkRound) { const goalRow = width - 1 const goalCol = height - 1 const homeCell = map[0][0] homeCell.walkRound = walkRound let cellsToWalk = [ homeCell ] while (true) { const newCellsToWalk = [ ] for (const cell of cellsToWalk) { const row = cell.row const col = cell.col if (row == goalRow && col == goalCol) { return true } grabCell(row - 1, col, walkRound, newCellsToWalk) grabCell(row + 1, col, walkRound, newCellsToWalk) grabCell(row, col - 1, walkRound, newCellsToWalk) grabCell(row, col + 1, walkRound, newCellsToWalk) } cellsToWalk = newCellsToWalk if (cellsToWalk.length == 0) { return false } } } function grabCell(row, col, walkRound, newCellsToWalk) { if (row < 0) { return } if (col < 0) { return } if (row == height) { return } if (col == width) { return } const cell = map[row][col] if (cell.blockRound <= walkRound) { return } if (cell.walkRound == walkRound) { return } cell.walkRound = walkRound newCellsToWalk.push(cell) } /////////////////////////////////////////////////////////////////////////// function findTheFirstBlockingByte() { let highestFree = 0 let lowestBlocked = strCoordinates.length - 1 while (true) { if (highestFree + 1 == lowestBlocked) { return strCoordinates[lowestBlocked] } let round = Math.floor((highestFree + lowestBlocked) / 2) const free = walk(round) if (free) { highestFree = round } else { lowestBlocked = round } } } /////////////////////////////////////////////////////////////////////////////// function showMap(walkRound) { for (const line of map) { let s = """" for (const cell of line) { let c = ""."" if (cell.blockRound <= walkRound) { c = ""#"" } if (cell.walkRound == walkRound) { c = ""O"" } s += c } console.log(s) } } console.time(""execution time"") main() 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! 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","const fs = require('fs'); const input_text = fs.readFileSync('input.txt', 'utf-8').split('\n'); const grid_size = 70; const bytes_list = input_text.map(byte => { const [byte_x, byte_y] = byte.split("",""); return [parseInt(byte_x), parseInt(byte_y)]; }); const movements = [[-1, 0], [1, 0], [0, 1], [0, -1]]; let bytes_needed_lower = 0; let bytes_needed_upper = bytes_list.length - 1; while (bytes_needed_lower < bytes_needed_upper) { const mid = Math.floor((bytes_needed_lower + bytes_needed_upper) / 2); const bytes = new Set(bytes_list.slice(0, mid).map(byte => byte.toString())); const explored = new Set(); const discovered = [[0, 0, 0]]; while (discovered.length > 0) { discovered.sort((a, b) => a[0] - b[0]); const [distance, byte_x, byte_y] = discovered.shift(); if (!explored.has([byte_x, byte_y].toString())) { explored.add([byte_x, byte_y].toString()); if (byte_x === byte_y && byte_x === grid_size) { break; } for (const movement of movements) { const new_position = [byte_x + movement[0], byte_y + movement[1]]; const new_position_str = new_position.toString(); if ( !bytes.has(new_position_str) && !explored.has(new_position_str) && new_position.every(coord => coord >= 0 && coord <= grid_size) ) { discovered.push([distance + 1, ...new_position]); } } } } if (discovered.length === 0) { bytes_needed_upper = mid; } else { bytes_needed_lower = mid + 1; } } 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. 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,"// solution for https://adventofcode.com/2024/day/19 part 1 ""use strict"" const input = Deno.readTextFileSync(""day19-input.txt"").trim() const allTargets = [ ] const patternsBySize = { } // { size: list } const patternsByLetter = { } // { letter: list } const cache = { } // token: true/false function main() { processInput() simplifyPatterns() fillPatternsByLetter() let count = 0 for (const target of allTargets) { if (isComposable(target)) { count += 1 } } console.log(""the answer is"", count) } function processInput() { const sections = input.split(""\n\n"") const rawTargets = sections.pop().trim().split(""\n"") for (const rawTarget of rawTargets) { allTargets.push(rawTarget.trim()) } const patterns = sections.pop().trim().split("", "") for (const pattern of patterns) { const size = pattern.length if (patternsBySize[size] == undefined) { patternsBySize[size] = [ ] } patternsBySize[size].push(pattern) } } /////////////////////////////////////////////////////////////////////////////// function simplifyPatterns() { const maxSize = Object.keys(patternsBySize).length for (let size = 2; size <= maxSize; size++) { simplifyPatternsThisSize(size) } } function simplifyPatternsThisSize(size) { const newList = [ ] for (const pattern of patternsBySize[size]) { if (! isRedundant(pattern, 1)) { newList.push(pattern) } } patternsBySize[size] = newList } function isRedundant(sourcePattern, reductor) { const maxSize = sourcePattern.length - reductor for (let size = maxSize; size > 0; size--) { // decreasing for (const pattern of patternsBySize[size]) { if (! sourcePattern.startsWith(pattern)) { continue } const remain = sourcePattern.replace(pattern, """") if (remain == """") { return true } if (isRedundant(remain, 0)) { return true } } } return false } /////////////////////////////////////////////////////////////////////////////// function fillPatternsByLetter() { const maxSize = Object.keys(patternsBySize).length for (let size = maxSize; size > 0; size--) { // decreasing for (const pattern of patternsBySize[size]) { const letter = pattern[0] if (patternsByLetter[letter] == undefined) { patternsByLetter[letter] = [ ] } patternsByLetter[letter].push(pattern) } } } /////////////////////////////////////////////////////////////////////////////// function isComposable(target) { if (cache[target] !== undefined) { return cache[target] } for (const pattern of patternsByLetter[target[0]]) { if (! target.startsWith(pattern)) { continue } const remain = target.replace(pattern, """") if (remain == """") { cache[target] = true; return true } if (isComposable(remain)) { cache[target] = true; return true } } cache[target] = false return false } console.time(""execution time"") main() 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. 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,"const fs = require('fs'); function isPatternPossible(pattern, towels, visited) { if (pattern === """") { return true; } visited.add(pattern); return towels.some(towel => pattern.startsWith(towel) && !visited.has(pattern.slice(towel.length)) && isPatternPossible(pattern.slice(towel.length), towels, visited) ); } fs.readFile('input.txt', 'utf8', (err, data) => { if (err) throw err; const lines = data.split('\n'); const towels = lines[0].split("","").map(s => s.trim()); const patterns = lines.slice(2); const validPatternCount = patterns.reduce((count, pattern) => { return count + (isPatternPossible(pattern, towels, new Set()) ? 1 : 0); }, 0); console.log(validPatternCount); });",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. 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,"const fs = require('fs'); fs.readFile('./day_19.in', 'utf8', (err, data) => { if (err) throw err; const lines = data.split('\n'); const units = lines[0].split(', ').map(s => s.trim()); const designs = lines.slice(2); function possible(design) { const n = design.length; const dp = new Array(n).fill(false); for (let i = 0; i < n; i++) { if (units.includes(design.slice(0, i + 1))) { dp[i] = true; continue; } for (let u of units) { if (design.slice(i - u.length + 1, i + 1) === u && dp[i - u.length]) { dp[i] = true; break; } } } return dp[n - 1]; } let ans = 0; for (let design of designs) { if (possible(design)) { console.log(design); ans++; } } console.log(ans); });",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. 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,"const fs = require('fs'); const WHITE = ""w""; const BLUE = ""u""; const BLACK = ""b""; const RED = ""r""; const GREEN = ""g""; const INPUT_FILE = ""input.txt""; // Read input file const lines = fs.readFileSync(INPUT_FILE, 'utf8').split('\n'); // Read available towels from the first line const availableTowels = lines[0].trim().split("", ""); // Read designs from the lines after the second line const designs = lines.slice(2).map(line => line.trim()); function findFirstPattern(design, startIndex = 0) { for (let i = design.length; i > 0; i--) { if (availableTowels.includes(design.slice(startIndex, i))) { return [i, design.slice(startIndex, i)]; } } return [null, null]; } function findLastPattern(design, endIndex) { for (let i = 0; i < design.length; i++) { if (availableTowels.includes(design.slice(i, endIndex))) { return [i, design.slice(i, endIndex)]; } } return [null, null]; } function findLargestFromStart(design, start = 0) { let largestPatternMatch = null; let end = 0; for (let i = start + 1; i <= design.length; i++) { const subString = design.slice(start, i); if (availableTowels.includes(subString)) { largestPatternMatch = subString; end = i; } } return [largestPatternMatch, end]; } let canBuildCount = 0; function canBuildWord(target, patterns) { const memo = {}; function canBuild(remaining) { // Base cases if (!remaining) return true; // Successfully used all letters if (memo[remaining]) return memo[remaining]; // Already tried this combo // Try each pattern at the start of our remaining string for (const pattern of patterns) { if (remaining.startsWith(pattern)) { const newRemaining = remaining.slice(pattern.length); if (canBuild(newRemaining)) { memo[remaining] = true; return true; } } } memo[remaining] = false; return false; } return canBuild(target); } // Loop through designs to check how many can be built with available towels designs.forEach(design => { if (canBuildWord(design, availableTowels)) { canBuildCount += 1; } }); console.log(canBuildCount); // Further processing for patterns const results = []; const impossibleDesigns = []; designs.forEach(design => { let patterns = {}; let result = 0; let patternFound = false; while (true) { [result, pattern] = findFirstPattern(design, result); if (!result) { patternFound = false; break; } patterns[pattern] = (patterns[pattern] || 0) + 1; if (design.slice(0, result) === design) { patternFound = true; break; } } if (patternFound) { results.push([design, patterns]); } else { patterns = {}; result = design.length; patternFound = false; while (true) { [result, pattern] = findLastPattern(design, result); if (result === null) { patternFound = false; break; } patterns[pattern] = (patterns[pattern] || 0) + 1; if (result === 0) { patternFound = true; break; } } if (patternFound) { results.push([design, patterns]); } else { impossibleDesigns.push(design); } } }); 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. 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n'); // Get towel patterns const towelsLine = input.shift(); const towels = towelsLine.split(',').map(s => s.trim()); // Skip empty lines while (input.length && input[0].trim() === '') { input.shift(); } // Get designs const designs = input.map(s => s.trim()).filter(s => s.length > 0); function canForm(design, towels, memo = {}) { if (design in memo) return memo[design]; if (design.length === 0) return true; for (let towel of towels) { if (design.startsWith(towel)) { if (canForm(design.slice(towel.length), towels, memo)) { memo[design] = true; return true; } } } memo[design] = false; return false; } let count = 0; for (let design of designs) { if (canForm(design, towels)) { count++; } } 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. 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,"const fs = require('fs'); function numPossiblePatterns(pattern, towels, memo) { if (pattern === """") { return 1; } if (memo.has(pattern)) { return memo.get(pattern); } let res = towels.reduce((sum, towel) => { return sum + (pattern.startsWith(towel) ? numPossiblePatterns(pattern.slice(towel.length), towels, memo) : 0); }, 0); memo.set(pattern, res); return res; } fs.readFile('input.txt', 'utf8', (err, data) => { if (err) throw err; const lines = data.split('\n'); const towels = lines[0].split(',').map(s => s.trim()); const patterns = lines.slice(2); console.log( patterns.reduce((sum, pattern) => sum + numPossiblePatterns(pattern, towels, new Map()), 0) ); });",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. 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,"const fs = require('fs'); function buildTowelsTrie(towels) { const towelsTrie = {}; towels.forEach(towel => { let innerDict = towelsTrie; for (let letter of towel) { if (!(letter in innerDict)) { innerDict[letter] = {}; } innerDict = innerDict[letter]; } innerDict[null] = null; }); return towelsTrie; } function patternPossible(pattern, towelsTrie, memo = new Map()) { if (pattern === """") { return 1; } if (memo.has(pattern)) { return memo.get(pattern); } let patternsNeeded = []; let trie = towelsTrie; for (let i = 0; i < pattern.length; i++) { let letter = pattern[i]; if (letter in trie) { trie = trie[letter]; if (null in trie) { patternsNeeded.push(pattern.slice(i + 1)); } } else { break; } } let result = patternsNeeded.reduce((sum, subPattern) => sum + patternPossible(subPattern, towelsTrie, memo), 0); memo.set(pattern, result); return result; } fs.readFile('input.txt', 'utf8', (err, data) => { if (err) throw err; const inputText = data.split('\n'); const towels = inputText[0].split(', ').map(s => s.trim()); const patterns = inputText.slice(2); const towelsTrie = buildTowelsTrie(towels); const totalPatterns = patterns.reduce((sum, pattern) => sum + patternPossible(pattern, towelsTrie), 0); console.log(totalPatterns); });",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. 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,"const fs = require('fs'); function checkCount(towels, pattern, cache) { if (pattern === """") { return 1; } const block = cache.get(pattern); if (block !== undefined) { return block; } let result = 0; for (let towel of towels) { if (pattern.startsWith(towel)) { result += checkCount(towels, pattern.slice(towel.length), cache); } } cache.set(pattern, result); return result; } function getNumAchievablePatterns(towels, patterns) { return patterns.reduce((sum, pattern) => sum + checkCount(towels, pattern, new Map()), 0); } fs.readFile('day19-2.txt', 'utf8', (err, data) => { if (err) throw err; const lines = data.split('\n'); let towels = []; let patterns = []; for (let line of lines) { line = line.trim(); if (line.length === 0) { continue; } if (towels.length === 0) { towels = line.split(', ').map(s => s.trim()); } else { patterns.push(line); } } console.log(""Number of ways to achieve patterns:"", getNumAchievablePatterns(towels, patterns)); });",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. 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,"// solution for https://adventofcode.com/2024/day/19 part 2 ""use strict"" const input = Deno.readTextFileSync(""day19-input.txt"").trim() const singles = { } // one letter patterns const multiples = { // two or more letter patterns, organized by start ""bb"": [ ], ""bg"": [ ], ""br"": [ ], ""bu"": [ ], ""bw"": [ ], ""gb"": [ ], ""gg"": [ ], ""gr"": [ ], ""gu"": [ ], ""gw"": [ ], ""rb"": [ ], ""rg"": [ ], ""rr"": [ ], ""ru"": [ ], ""rw"": [ ], ""ub"": [ ], ""ug"": [ ], ""ur"": [ ], ""uu"": [ ], ""uw"": [ ], ""wb"": [ ], ""wg"": [ ], ""wr"": [ ], ""wu"": [ ], ""ww"": [ ] } const allTargets = [ ] const cache = { } // token: true/false function main() { processInput() var count = 0 for (const target of allTargets) { count += countWays(target) } console.log(""the answer is"", count) } function processInput() { const sections = input.split(""\n\n"") const rawTargets = sections.pop().trim().split(""\n"") for (const rawTarget of rawTargets) { allTargets.push(rawTarget.trim()) } const patterns = sections.pop().trim().split("", "") for (const pattern of patterns) { if (pattern.length == 1) { singles[pattern] = true; continue } const key = pattern.substr(0, 2) multiples[key].push(pattern) } } /////////////////////////////////////////////////////////////////////////////// function countWays(target) { if (cache[target] != undefined) { return cache[target] } if (target.length == 1) { return (singles[target] == true) ? 1 : 0 } let ways = 0 if (singles[target[0]] == true) { ways += countWays(target.substr(1)) } const key = target.substr(0, 2) for (const pattern of multiples[key]) { if (! target.startsWith(pattern)) { continue } const remain = target.replace(pattern, """") if (remain == """") { ways += 1; continue } ways += countWays(remain) } cache[target] = ways return ways } console.time(""execution time"") main() 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. 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,"const fs = require('fs'); const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n'); // Get towel patterns const towelsLine = input.shift(); const towels = towelsLine.split(',').map(s => s.trim()); // Skip empty lines while (input.length && input[0].trim() === '') { input.shift(); } // Get designs const designs = input.map(s => s.trim()).filter(s => s.length > 0); function countWays(design, towels, memo = {}) { if (design in memo) return memo[design]; if (design.length === 0) return 1; let totalWays = 0; for (let towel of towels) { if (design.startsWith(towel)) { totalWays += countWays(design.slice(towel.length), towels, memo); } } memo[design] = totalWays; return totalWays; } let totalCount = 0; for (let design of designs) { totalCount += countWays(design, towels); } 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! 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,"const fs = require('fs'); const Direction = Object.freeze({ UP: 0, RIGHT: 1, DOWN: 2, LEFT: 3 }); class Position { constructor(x, y) { this.x = x; this.y = y; } toString() { return `${this.x}_${this.y}`; } equals(other) { return this.x === other.x && this.y === other.y; } static hash(position) { return `${position.x}_${position.y}`; } } class Cheat { constructor(s, e) { this.s = s; this.e = e; } toString() { return `${this.s.toString()}_${this.e.toString()}`; } } const space = 0; const wall = 1; function importMatrix(matrixString) { const matrix = []; let startPosition = null; let goalPosition = null; matrixString.split(""\n"").forEach((line, lineIndex) => { matrix[lineIndex] = []; for (let columnIndex = 0; columnIndex < line.length; columnIndex++) { const tile = line[columnIndex]; if (tile === ""."") { matrix[lineIndex].push(space); } else if (tile === ""#"") { matrix[lineIndex].push(wall); } else if (tile === ""S"") { matrix[lineIndex].push(space); startPosition = new Position(columnIndex, lineIndex); } else if (tile === ""E"") { matrix[lineIndex].push(space); goalPosition = new Position(columnIndex, lineIndex); } } }); return [matrix, startPosition, goalPosition]; } function getValidInDirection(currentPosition, direction) { let p; switch (direction) { case Direction.UP: p = new Position(currentPosition.x, currentPosition.y - 1); break; case Direction.LEFT: p = new Position(currentPosition.x - 1, currentPosition.y); break; case Direction.RIGHT: p = new Position(currentPosition.x + 1, currentPosition.y); break; case Direction.DOWN: p = new Position(currentPosition.x, currentPosition.y + 1); break; } if (p.x < 0 || p.x >= map[0].length || p.y < 0 || p.y >= map.length) { return null; } return [p, direction]; } function getNeighborsAndCheats(currentPosition) { const directions = [Direction.LEFT, Direction.RIGHT, Direction.UP, Direction.DOWN]; const neighborsInMap = directions.map(d => getValidInDirection(currentPosition, d)).filter(Boolean); const neighbors = []; const wallsWithDirection = []; neighborsInMap.forEach(([p, direction]) => { if (map[p.y][p.x] === space) { neighbors.push(p); } else { wallsWithDirection.push([p, direction]); } }); const cheats = []; wallsWithDirection.forEach(([wd, direction]) => { const possibleCheat = getValidInDirection(wd, direction); if (possibleCheat && map[possibleCheat[0].y][possibleCheat[0].x] === space) { cheats.push(new Cheat(wd, possibleCheat[0])); } }); return [neighbors, cheats]; } const [map, start, goal] = importMatrix(fs.readFileSync(""20.txt"", ""utf8"")); function createTrack() { const graph = {}; const cheatsDict = {}; for (let y = 0; y < map.length; y++) { for (let x = 0; x < map[y].length; x++) { if (map[y][x] === wall) continue; const position = new Position(x, y); const [neighbors, cheats] = getNeighborsAndCheats(position); graph[position] = neighbors; cheatsDict[position] = cheats; } } const track = {}; const cheats = {}; const ignore = new Set(); let currentPosition = start; let currentStep = 0; while (true) { ignore.add(Position.hash(currentPosition)); track[currentPosition] = currentStep; if (currentPosition.equals(goal)) { break; } const validCheats = cheatsDict[currentPosition].filter(c => !ignore.has(Position.hash(c.e))); cheats[currentStep] = validCheats; const neighbors = graph[currentPosition]; for (const neighbor of neighbors) { if (!ignore.has(Position.hash(neighbor))) { currentPosition = neighbor; break; } } currentStep++; } return [track, cheats, currentStep]; } const [track, cheats, totalSteps] = createTrack(); let solution = 0; for (const step of Object.keys(cheats)) { cheats[step].forEach(cheat => { const lengthUpToCheat = Number(step); const stepAtCheatEnd = track[Position.hash(cheat.e)]; const resultingLength = lengthUpToCheat + 2 + (totalSteps - stepAtCheatEnd); const stepsSaved = totalSteps - resultingLength; if (stepsSaved >= 100) { solution++; } }); } 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! 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,"const fs = require('fs'); const grid = fs.readFileSync('input.txt', 'utf8').split('\n').map(line => line.split('')); function getStart(grid) { for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === 'S') { return [i, j]; } } } } function getEnd(grid) { for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === 'E') { return [i, j]; } } } } const start = getStart(grid); const end = getEnd(grid); function getNeighbors(grid, pos) { const [i, j] = pos; const neighbors = []; if (i > 0 && grid[i - 1][j] !== '#') { neighbors.push([i - 1, j]); } if (i < grid.length - 1 && grid[i + 1][j] !== '#') { neighbors.push([i + 1, j]); } if (j > 0 && grid[i][j - 1] !== '#') { neighbors.push([i, j - 1]); } if (j < grid[i].length - 1 && grid[i][j + 1] !== '#') { neighbors.push([i, j + 1]); } return neighbors; } function getRaceTrack(grid, start, end) { const visited = []; const queue = [start]; while (queue.length > 0) { const pos = queue.shift(); visited.push(pos); if (pos[0] === end[0] && pos[1] === end[1]) { return visited; } const neighbors = getNeighbors(grid, pos); for (const neighbor of neighbors) { if (!visited.some(v => v[0] === neighbor[0] && v[1] === neighbor[1])) { queue.push(neighbor); } } } return []; } function printPath(grid, path) { const gridCopy = grid.map(line => [...line]); for (let i = 0; i < Math.min(10, path.length); i++) { const [iIdx, jIdx] = path[i]; gridCopy[iIdx][jIdx] = 'X'; } gridCopy.forEach(line => { console.log(line.join('')); }); } function printCheat(grid, first, second) { const gridCopy = grid.map(line => [...line]); gridCopy[first[0]][first[1]] = '1'; gridCopy[second[0]][second[1]] = '2'; gridCopy.forEach(line => { console.log(line.join('')); }); } function getCheats(path, grid) { const cheats = {}; for (let i = 0; i < path.length; i++) { for (let j = i; j < path.length; j++) { const [i1, j1] = path[i]; const [i2, j2] = path[j]; if ((i1 === i2 && Math.abs(j1 - j2) === 2 && grid[i1][(j1 + j2) / 2] === '#') || (j1 === j2 && Math.abs(i1 - i2) === 2 && grid[(i1 + i2) / 2][j1] === '#')) { const savedTime = j - i - 2; if (!cheats[savedTime]) { cheats[savedTime] = 1; } else { cheats[savedTime]++; } } } } return cheats; } const path = getRaceTrack(grid, start, end); const cheats = getCheats(path, grid); let count = 0; for (const key in cheats) { if (parseInt(key) >= 100) { count += cheats[key]; } } 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! 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,"// solution for https://adventofcode.com/2024/day/20 part 1 ""use strict"" const input = Deno.readTextFileSync(""day20-input.txt"").trim() const map = [ ] var width = 0 var height = 0 var homeCell = null var goalCell = null var bestShortcuts = 0 function main() { processInput() walk() findAllShortcuts() console.log(""the answer is"", bestShortcuts) } function processInput() { const rawLines = input.split(""\n"") let row = -1 for (const rawLine of rawLines) { row += 1 const mapLine = [ ] map.push(mapLine) let col = -1 for (const symbol of rawLine.trim()) { col += 1 const cell = createCell(row, col, symbol) if (symbol == ""S"") { homeCell = cell } if (symbol == ""E"") { goalCell = cell } mapLine.push(cell) } } height = map.length width = map[0].length } function createCell(row, col, symbol) { return { ""row"": row, ""col"": col, ""symbol"": symbol, ""distance"": -1 } } /////////////////////////////////////////////////////////////////////////////// function walk() { homeCell.distance = 0 let cellsToWalk = [ homeCell ] while (true) { const newCellsToWalk = [ ] for (const cell of cellsToWalk) { const row = cell.row const col = cell.col const distance = cell.distance + 1 if (cell == goalCell) { return } // not necessary for my input grabCell(row - 1, col, distance, newCellsToWalk) grabCell(row + 1, col, distance, newCellsToWalk) grabCell(row, col - 1, distance, newCellsToWalk) grabCell(row, col + 1, distance, newCellsToWalk) } cellsToWalk = newCellsToWalk if (cellsToWalk.length == 0) { return } } } function grabCell(row, col, distance, newCellsToWalk) { if (row < 0) { return } if (col < 0) { return } if (row == height) { return } if (col == width) { return } const cell = map[row][col] if (cell.symbol == ""#"") { return } if (cell.distance != -1) { return } cell.distance = distance newCellsToWalk.push(cell) } /////////////////////////////////////////////////////////////////////////////// function findAllShortcuts() { for (const line of map) { for (const cell of line) { if (cell.symbol != ""#"") { continue } if (cell.row == 0) { continue } if (cell.col == 0) { continue } if (cell.row == height - 1) { continue } if (cell.col == width - 1) { continue } findShortcut(cell) } } } function findShortcut(cell) { const north = map[cell.row - 1][cell.col] const south = map[cell.row + 1][cell.col] const east = map[cell.row][cell.col + 1] const west = map[cell.row][cell.col - 1] const neighbors = [ ] // only cells that are in the path if (north.distance != -1) { neighbors.push(north) } if (south.distance != -1) { neighbors.push(south) } if (east.distance != -1) { neighbors.push(east) } if (west.distance != -1) { neighbors.push(west) } if (neighbors.length < 2) { return } orderByDistance(neighbors) const cellBeforeCut = neighbors.shift() const distanceBeforeCut = cellBeforeCut.distance for (const neighbor of neighbors) { const distanceAfterCut = neighbor.distance const economy = distanceAfterCut - distanceBeforeCut - 2 if (economy >= 100) { bestShortcuts += 1 } } } /////////////////////////////////////////////////////////////////////////////// function orderByDistance(list) { let n = -1 while (true) { n += 1 const a = list[n] const b = list[n + 1] if (b == undefined) { return } if (a.distance < b.distance) { continue } list[n] = b list[n + 1] = a n = -1 } } console.time(""execution time"") main() 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! 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,"const fs = require('fs'); // Helper function to parse input and get grid with start and end positions const parseInput = (filePath) => { const input = fs.readFileSync(filePath, 'utf-8').split('\n').map(line => [...line.trim()]); let start = null, end = null; input.forEach((line, row) => { if (line.includes('S')) start = [row, line.indexOf('S')]; if (line.includes('E')) end = [row, line.indexOf('E')]; }); return { grid: input, start, end }; }; // Function to determine if a given position is within bounds const isInBounds = (grid, position) => { const [y, x] = position; return y >= 0 && y < grid.length && x >= 0 && x < grid[0].length; }; // Function to check neighbors in all four directions const getNeighbors = (grid, position) => { const [y, x] = position; const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; let neighbors = []; directions.forEach(([dy, dx]) => { const newPosition = [y + dy, x + dx]; if (isInBounds(grid, newPosition) && grid[newPosition[0]][newPosition[1]] !== '#') { neighbors.push(newPosition); } }); return neighbors; }; // Function to find shortcuts from the current position const findShortcuts = (grid, position) => { const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; const [y, x] = position; let shortcuts = []; directions.forEach(([dy, dx]) => { if (grid[y + dy] && grid[y + dy][x + dx] === '#') { const shortcutTo = grid[y + 2 * dy] && grid[y + 2 * dy][x + 2 * dx]; if (shortcutTo !== '#' && shortcutTo !== '.') { shortcuts.push(grid[y][x] - shortcutTo - 2); } } }); return shortcuts; }; // Function to perform one step in the map const step = (grid, position, steps) => { const [y, x] = position; const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; for (const [dy, dx] of directions) { if (grid[y + dy] && grid[y + dy][x + dx] === '.') { grid[y + dy][x + dx] = steps; return [y + dy, x + dx]; } } return position; // No valid move found }; // Main function to simulate the race and collect results const runRaceSimulation = (filePath) => { const { grid, start, end } = parseInput(filePath); let position = start; let shortcuts = []; let steps = 0; grid[start[0]][start[1]] = 0; grid[end[0]][end[1]] = '.'; // Traverse the grid to find the path while (JSON.stringify(position) !== JSON.stringify(end)) { steps += 1; shortcuts = [...shortcuts, ...findShortcuts(grid, position)]; position = step(grid, position, steps); } // Collect shortcuts to the end shortcuts = [...shortcuts, ...findShortcuts(grid, position)]; // Count the occurrences of each shortcut const counts = shortcuts.reduce((acc, l) => { acc[l] = (acc[l] || 0) + 1; return acc; }, {}); // Calculate and print the number of shortcuts with time saved >= 100 const result = shortcuts.filter(s => s >= 100).length; console.log(result); }; // Run the simulation with the specified input file 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! 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,"const fs = require('fs'); function findShortcuts(map, p) { const [y, x] = p; const directions = [ [1, 0], [-1, 0], [0, 1], [0, -1] ]; let shortcuts = []; for (const direction of directions) { if (inDirection(map, p, direction, 1) === '#') { const shortcutTo = inDirection(map, p, direction, 2); if (shortcutTo === '#' || shortcutTo === '.') { continue; } shortcuts.push(map[y][x] - shortcutTo - 2); } } return shortcuts; } function inDirection(map, f, d, count) { let [y, x] = f; for (let i = 0; i < count; i++) { y += d[0]; x += d[1]; } if (y < 0 || y >= map.length || x < 0 || x >= map[0].length) { return '#'; } return map[y][x]; } function step(map, p, steps) { const [y, x] = p; const directions = [ [y + 1, x], [y - 1, x], [y, x + 1], [y, x - 1] ]; for (const [r, c] of directions) { if (map[r][c] === '.') { map[r][c] = steps; return [r, c]; } } return p; // Shouldn't happen unless there's an error } const map = []; let start = null; let end = null; const input = fs.readFileSync('input.txt', 'utf-8').split('\n'); input.forEach((line, row) => { line = line.trim(); map.push([...line]); if (line.includes('S')) { start = [row, line.indexOf('S')]; } if (line.includes('E')) { end = [row, line.indexOf('E')]; } }); console.log(`Race from ${start} to ${end}`); let p = start; let shortcuts = []; let steps = 0; map[start[0]][start[1]] = 0; map[end[0]][end[1]] = '.'; while (JSON.stringify(p) !== JSON.stringify(end)) { steps += 1; shortcuts = shortcuts.concat(findShortcuts(map, p)); p = step(map, p, steps); } // And also shortcuts straight to the end shortcuts = shortcuts.concat(findShortcuts(map, p)); const counts = {}; shortcuts.forEach(l => { counts[l] = (counts[l] || 0) + 1; }); const sortedCounts = Object.entries(counts).sort(([a], [b]) => a - b); sortedCounts.forEach(([l, count]) => { console.log(`${l}: ${count}`); }); const result = shortcuts.filter(s => s >= 100).length; 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! 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,"const fs = require('fs'); const parseInput = (filename) => { const grid = []; const data = fs.readFileSync(filename, 'utf8').split('\n'); data.forEach(line => { grid.push(line.trim().split('')); }); return grid; }; const solve1 = (grid, minsave) => { let si = 0, sj = 0, ei = 0, ej = 0; const N = grid.length; const M = grid[0].length; const inside = (i, j) => 0 <= i && i < N && 0 <= j && j < M; for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { if (grid[i][j] === 'S') { si = i; sj = j; } else if (grid[i][j] === 'E') { ei = i; ej = j; } } } const h = [[0, si, sj, 0, 0]]; const path = []; const cost = {}; while (h.length > 0) { const [c, i, j, pi, pj] = h.pop(); if (grid[i][j] === ""#"") continue; path.push([i, j]); cost[`${i},${j}`] = c; if (grid[i][j] === ""E"") break; const nxt = [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]; nxt.forEach(([ni, nj]) => { if (ni !== pi || nj !== pj) { h.push([c + 1, ni, nj, i, j]); } }); } const savings = {}; let count = 0; path.forEach(([i, j]) => { const nxt = [[i + 2, j], [i - 2, j], [i, j + 2], [i, j - 2]]; const thru = [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]; nxt.forEach(([ni, nj], idx) => { const [ti, tj] = thru[idx]; if (!inside(ni, nj) || grid[ni][nj] === '#') return; if (cost[`${ni},${nj}`] - cost[`${i},${j}`] - 2 >= minsave && grid[ti][tj] === '#') { savings[`${i},${j},${ni},${nj}`] = cost[`${ni},${nj}`] - cost[`${i},${j}`] - 2; count += 1; } }); }); console.log(`Part One - ${count}`); }; const solve2 = (grid, minsave) => { let si = 0, sj = 0, ei = 0, ej = 0; const N = grid.length; const M = grid[0].length; const inside = (i, j) => 0 <= i && i < N && 0 <= j && j < M; for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { if (grid[i][j] === 'S') { si = i; sj = j; } else if (grid[i][j] === 'E') { ei = i; ej = j; } } } const h = [[0, si, sj, 0, 0]]; const path = []; const cost = {}; while (h.length > 0) { const [c, i, j, pi, pj] = h.pop(); if (grid[i][j] === ""#"") continue; path.push([i, j]); cost[`${i},${j}`] = c; if (grid[i][j] === ""E"") break; const nxt = [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]; nxt.forEach(([ni, nj]) => { if (ni !== pi || nj !== pj) { h.push([c + 1, ni, nj, i, j]); } }); } const savings = {}; let count = 0; path.forEach(([i, j]) => { for (let step = 2; step <= 20; step++) { for (let di = 0; di <= step; di++) { const dj = step - di; const nxt = [[i + di, j + dj], [i + di, j - dj], [i - di, j + dj], [i - di, j - dj]]; nxt.forEach(([ni, nj]) => { if (!inside(ni, nj) || grid[ni][nj] === '#' || savings[`${i},${j},${ni},${nj}`]) return; if (cost[`${ni},${nj}`] - cost[`${i},${j}`] - step >= minsave) { savings[`${i},${j},${ni},${nj}`] = cost[`${ni},${nj}`] - cost[`${i},${j}`] - step; count += 1; } }); } } }); console.log(`Part Two - ${count}`); }; // Parse the input grid and solve for both parts const grid = parseInput('./inputs/day20.txt'); solve1(grid, 100); 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! 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,"// solution for https://adventofcode.com/2024/day/20 part 2 ""use strict"" const input = Deno.readTextFileSync(""day20-input.txt"").trim() const map = [ ] var width = 0 var height = 0 var homeCell = null var goalCell = null const minimumEconomy = 100 var bestShortcuts = 0 function main() { processInput() walk() findAllShortcuts() console.log(""the answer is"", bestShortcuts) } function processInput() { const rawLines = input.split(""\n"") let row = -1 for (const rawLine of rawLines) { row += 1 const mapLine = [ ] map.push(mapLine) let col = -1 for (const symbol of rawLine.trim()) { col += 1 const cell = createCell(row, col, symbol) if (symbol == ""S"") { homeCell = cell } if (symbol == ""E"") { goalCell = cell } mapLine.push(cell) } } height = map.length width = map[0].length } function createCell(row, col, symbol) { return { ""row"": row, ""col"": col, ""symbol"": symbol, ""distance"": -1 } } /////////////////////////////////////////////////////////////////////////////// function walk() { homeCell.distance = 0 let cellsToWalk = [ homeCell ] while (true) { const newCellsToWalk = [ ] for (const cell of cellsToWalk) { const row = cell.row const col = cell.col const distance = cell.distance + 1 if (cell == goalCell) { return } // not necessary for my input grabCell(row - 1, col, distance, newCellsToWalk) grabCell(row + 1, col, distance, newCellsToWalk) grabCell(row, col - 1, distance, newCellsToWalk) grabCell(row, col + 1, distance, newCellsToWalk) } cellsToWalk = newCellsToWalk if (cellsToWalk.length == 0) { return } } } function grabCell(row, col, distance, newCellsToWalk) { if (row < 0) { return } if (col < 0) { return } if (row == height) { return } if (col == width) { return } const cell = map[row][col] if (cell.symbol == ""#"") { return } if (cell.distance != -1) { return } cell.distance = distance newCellsToWalk.push(cell) } /////////////////////////////////////////////////////////////////////////////// function findAllShortcuts() { for (const line of map) { for (const cell of line) { if (cell.distance != -1) { findShortcut(cell) } } } } function findShortcut(baseCell) { for (let deltaRow = -20; deltaRow <= 20; deltaRow++) { const row = baseCell.row + deltaRow if (row < 0) { continue } if (row > height - 1) { return } for (let deltaCol = -20; deltaCol <= 20; deltaCol++) { const col = baseCell.col + deltaCol if (col < 0) { continue } if (col > width - 1) { break } const manhattan = Math.abs(deltaRow) + Math.abs(deltaCol) // manhattan distance if (manhattan == 0) { continue } if (manhattan > 20) { continue } const cell = map[row][col] if (cell.distance == -1) { continue } const economy = cell.distance - baseCell.distance - manhattan if (economy < minimumEconomy) { continue } bestShortcuts += 1 } } } console.time(""execution time"") main() 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! 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,"const fs = require('fs'); const lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); // track // [ // [r,c,hacks:[[r,c]]], // ] let start, end; let path = [] // add start and end for (let r = 0; r < lines.length; r++) { for (let c = 0; c < lines[r].length; c++) { if (lines[r][c] === 'S') { start = [r, c]; } else if (lines[r][c] === 'E') { end = [r, c]; } else if (lines[r][c] === '.') { path.push([r, c]); } } } let current = start; let track = [] console.log(start, end); while (!(current[0] === end[0] && current[1] === end[1])) { let adjacent = [ [[current[0], current[1] + 1], [current[0], current[1] + 2]], [[current[0], current[1] - 1], [current[0], current[1] - 2]], [[current[0] - 1, current[1]], [current[0] - 2, current[1]]], [[current[0] + 1, current[1]], [current[0] + 2, current[1]]], ]; let next; let hacks = []; for (let [[afr, afc], [nfr, nfc]] of adjacent) { if (lines[afr][afc] === '.' || lines[afr][afc] === 'E') { let seen = track.some(i => i[0] === afr && i[1] === afc); if (!seen) { next = [afr, afc]; } } else if (lines[afr][afc] === '#') { if (nfr > 0 && nfr < lines.length && nfc > 0 && nfc < lines[0].length) { if (lines[nfr][nfc] === '.' || lines[nfr][nfc] === 'E') { let seen = track.some(i => i[0] === nfr && i[1] === nfc); if (!seen) { hacks.push([nfr, nfc]); } } } } } track.push([current[0], current[1], hacks]); if (!next) { throw 'weird'; } current = next; } track.push([...end, []]); let pico = []; for (let i = 0; i < track.length; i++) { const hacks = track[i][2]; for (let hack of hacks) { let index = track.findIndex(t => t[0] === hack[0] && t[1] === hack[1]); pico.push(index - i - 2); } } console.log('part 1', pico.filter(p => p >= 100).length); const distance = (r, c, dr, dc) => { return Math.abs(r - dr) + Math.abs(c - dc); } let part2 = []; for (let i = 0; i < track.length - 2; i++) { for (let j = i + 2; j < track.length; j++) { const [r, c, {}] = track[i]; const [dr, dc, {}] = track[j]; const d = distance(r, c, dr, dc); const cutoff = j - i - d; if (d <= 20 && cutoff >= 100) { part2.push(cutoff); } } } 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! 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,"const fs = require('fs'); fs.readFile('input.txt', 'utf8', (err, data) => { if (err) throw err; const inputText = data.split('\n'); let start = [-1, -1]; let end = [-1, -1]; let walls = new Set(); for (let row = 0; row < inputText.length; row++) { for (let col = 0; col < inputText[0].length; col++) { const cell = inputText[row][col]; if (cell === 'S') { start = [row, col]; } else if (cell === 'E') { end = [row, col]; } else if (cell === '#') { walls.add(`${row},${col}`); } } } const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]; let noCheatMoveCount = { [`${start[0]},${start[1]}`]: 0 }; let currentPos = start; let moveCount = 0; while (currentPos[0] !== end[0] || currentPos[1] !== end[1]) { for (const [rowMove, colMove] of moves) { const newPos = [currentPos[0] + rowMove, currentPos[1] + colMove]; const newPosStr = `${newPos[0]},${newPos[1]}`; if (!walls.has(newPosStr) && !noCheatMoveCount[newPosStr]) { moveCount += 1; currentPos = newPos; noCheatMoveCount[newPosStr] = moveCount; break; } } } let cheatMoves = []; for (let deltaRow = -20; deltaRow <= 20; deltaRow++) { for (let deltaCol = -(20 - Math.abs(deltaRow)); deltaCol <= 20 - Math.abs(deltaRow); deltaCol++) { cheatMoves.push([deltaRow, deltaCol]); } } let cheats = {}; for (let [key, step] of Object.entries(noCheatMoveCount)) { let [initialRow, initialCol] = key.split(',').map(Number); for (let [rowMove, colMove] of cheatMoves) { const cheatPos = `${initialRow + rowMove},${initialCol + colMove}`; if (noCheatMoveCount[cheatPos] && noCheatMoveCount[cheatPos] > step + Math.abs(rowMove) + Math.abs(colMove)) { const saving = noCheatMoveCount[cheatPos] - step - Math.abs(rowMove) - Math.abs(colMove); cheats[saving] = (cheats[saving] || 0) + 1; } } } const result = Object.entries(cheats).reduce((sum, [saving, count]) => { if (saving >= 100) { sum += count; } return sum; }, 0); console.log(result); });",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! 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,"const fs = require('fs'); fs.readFile('input20.txt', 'utf8', (err, data) => { if (err) throw err; const input = data.split('\n').map(x => x.trim()); const test_data = `############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ###############`.split(""\n""); // Uncomment the next line to test with test_data // const input = test_data; const map = input.join(""""); const w = input[0].length; const h = input.length; const start = map.indexOf(""S""); const end = map.indexOf(""E""); const printMap = () => { for (let r = 0; r < h; r++) { console.log(map.slice(r * w, (r + 1) * w)); } }; const distances = new Array(w * h).fill(null); let workingSet = [end]; let current = 0; while (workingSet.length > 0) { const next = []; for (let i of workingSet) { if (distances[i] === null) { distances[i] = current; } const neighbors = [i - 1, i - w, i + 1, i + w]; for (let neighbor of neighbors) { if (map[neighbor] !== ""#"" && distances[neighbor] === null) { next.push(neighbor); } } } workingSet = next; current += 1; } const original = distances[start]; const getCheats = (cheatLength, limit) => { let count = 0; for (let i = 0; i < w * h; i++) { if (distances[i] === null) continue; for (let j = i + 1; j < w * h; j++) { if (distances[j] === null) continue; const x1 = i % w; const y1 = Math.floor(i / w); const x2 = j % w; const y2 = Math.floor(j / w); if (Math.abs(x1 - x2) + Math.abs(y1 - y2) <= cheatLength) { let k = 0; if (distances[i] > distances[j]) { k = original - distances[i] + distances[j] + Math.abs(x1 - x2) + Math.abs(y1 - y2); } else if (distances[i] < distances[j]) { k = original - distances[j] + distances[i] + Math.abs(x1 - x2) + Math.abs(y1 - y2); } if (original - k >= limit) { count += 1; } } } } return count; }; console.log(getCheats(20, 100)); });",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. 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,"const fs = require('fs'); // Read the input file const input = fs.readFileSync('input.txt', { encoding: ""utf8"", flag: ""r"" }); const keypadCodes = input.split('\n'); // Keypad and Directional Pad definitions const keypad = [ ['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], [null, '0', 'A'], ]; const dirpad = [ [null, '^', 'A'], ['<', 'v', '>'] ]; // Function to count occurrences of characters in a string const count = (str) => { let countObj = {}; for (let char of str) { countObj[char] = (countObj[char] || 0) + 1; } return countObj; }; // Function to calculate all shortest best paths on the grid const allShortestBest = (start, grid) => { let pathsObj = {}; let seen = new Set(); seen.add(start.join('|')); let startVal = grid[start[0]][start[1]]; let queue = [[[start, '', startVal]]]; const nextStep = ([r, c], grid) => { return [[r - 1, c, '^'], [r, c + 1, '>'], [r + 1, c, 'v'], [r, c - 1, '<']].filter(([nr, nc, nd]) => grid?.[nr]?.[nc] !== undefined && !seen.has(`${nr}|${nc}`) && !!grid?.[nr]?.[nc] ).map(([nr, nc, nd]) => [[nr, nc], nd].concat(grid[nr][nc])); }; while (queue.length > 0) { let nextQueue = []; let queueSeen = []; queue.forEach((path) => { let last = [point, dir, val] = path.at(-1); let next = nextStep(point, grid); next.forEach(([np, nd, nv]) => { queueSeen.push(np.join('|')); let newPath = path.concat([[np, nd, nv]]); pathsObj[nv] ? pathsObj[nv].push(newPath.map((x) => x[1]).join('')) : pathsObj[nv] = [newPath.map((x) => x[1]).join('')]; nextQueue.push(newPath); }); }); queueSeen.forEach((x) => seen.add(x)); queue = nextQueue; } let bestPaths = {}; Object.entries(pathsObj).forEach(([k, paths]) => { if (paths.length === 1) { bestPaths[`${startVal}${k}`] = `${paths[0]}A`; if (startVal === 'A') bestPaths[k] = `${paths[0]}A`; } else { let order = ''; const pathscore = (path) => { let split = path.split(''); return split.slice(0, -1).map((y, yx) => { let score = 0; if (y !== split[yx + 1]) score += 10; if (order.indexOf(split[yx + 1]) < order.indexOf(y)) score += 5; return score; }).reduce((a, b) => a + b, 0); }; let scores = paths.map((x) => [pathscore(x), x]).sort((a, c) => a[0] - c[0]); bestPaths[`${startVal}${k}`] = `${scores[0][1]}A`; if (startVal === 'A') bestPaths[k] = `${scores[0][1]}A`; } }); return bestPaths; }; let numpadDirs = Object.assign(...keypad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], keypad))); let dirs = Object.assign(...dirpad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], dirpad))); dirs['A'] = 'A'; dirs['AA'] = 'A'; dirs['<<'] = 'A'; dirs['>>'] = 'A'; dirs['^^'] = 'A'; dirs['vv'] = 'A'; const codes = keypadCodes.map((x) => [''].concat(x.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1)).map((x) => x.map((y) => numpadDirs[y])); // First keyboard, array of button presses e.g. ['^^A','vvvA'] for example // Function to calculate the minimum presses required const minPresses = (keypadCodes, dircodes, keyboards) => { let keypadNums = keypadCodes.map((x) => parseInt(x.slice(0, -1))); let targetDepth = keyboards - 1; let result = 0; for (const [index, code] of dircodes.entries()) { let countObj = count(code); for (let i = 0; i < targetDepth; i++) { let newCountObj = {}; for (const [key, val] of Object.entries(countObj)) { if (key.length === 1) { let newKey = dirs[key]; newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; } else { let keySplit = [''].concat(key.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1); keySplit.forEach((sKey) => { let newKey = dirs[sKey]; newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; }); } } countObj = newCountObj; } result += (Object.entries(countObj).map(([k, v]) => k.length * v).reduce((a, b) => a + b, 0) * keypadNums[index]); } return result; }; // Performance tracking and calculation const t0 = performance.now(); let p1 = minPresses(keypadCodes, codes, 3); const t1 = performance.now(); console.log('Part 1 answer is ', p1, t1 - t0, 'ms'); // Old list of hardcoded directions (commented out for clarity) const olddirs = { '<': 'v<': 'vA', 'A': 'A', '<^': '>^A', 'A', '<>': '>>A', '>^A', '^<': 'v': 'v>A', '^A': '>A', 'v<': '': '>A', 'vA': '^>A', '><': '<v': '^': '<^A', '>A': '^A', 'A<': 'v<': 'vA', '<<': 'A', 'vv': 'A', '^^': 'A', '>>': 'A', 'AA': 'A' };",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. 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,"const fs = require(""fs""); const 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], }; const ARROWS = { ""^"": [0, 1], ""A"": [0, 2], ""<"": [1, 0], ""v"": [1, 1], "">"": [1, 2], """": [0, 0], }; const DIR_TO_ARROW_MAP = { ""-1,0"": ""^"", ""1,0"": ""v"", ""0,-1"": ""<"", ""0,1"": "">"", }; function getShortest(keys, sequence) { let path = []; for (let i = 0; i < sequence.length - 1; i++) { let cur = keys[sequence[i]]; let target = keys[sequence[i + 1]]; let nextPath = []; let dirs = []; if (!cur || !target) continue; for (let y = cur[1] - 1; y >= target[1]; y--) { nextPath.push([cur[0], y]); dirs.push([0, -1]); } for (let x = cur[0] + 1; x <= target[0]; x++) { nextPath.push([x, cur[1]]); dirs.push([1, 0]); } for (let x = cur[0] - 1; x >= target[0]; x--) { nextPath.push([x, cur[1]]); dirs.push([-1, 0]); } for (let y = cur[1] + 1; y <= target[1]; y++) { nextPath.push([cur[0], y]); dirs.push([0, 1]); } if (nextPath.some((pos) => JSON.stringify(pos) === JSON.stringify(keys[""""]))) { dirs.reverse(); } path.push(...dirs.map((d) => DIR_TO_ARROW_MAP[d.join("","")]), ""A""); } return path.join(""""); } // Read input file const lines = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n""); let totalComplexity = 0; for (let line of lines) { if (!line) continue; let l1 = getShortest(NUMS, ""A"" + line); let l2 = getShortest(ARROWS, ""A"" + l1); let l3 = getShortest(ARROWS, ""A"" + l2); totalComplexity += parseInt(line.slice(0, -1)) * l3.length; } 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. 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,"// solution for https://adventofcode.com/2024/day/21 part 1 // this solution tests ALL combinations of the simplest commands! ""use strict"" const input = Deno.readTextFileSync(""day21-input.txt"").trim() const allCodes = [ ] const numericCommandsByMove = { // simplest commands only ""0 to 0"": [ ""A"" ], ""0 to 1"": [ ""^A"", "">^A"" ], ""0 to 4"": [ ""^^A"", "">^^A"" ], ""0 to 7"": [ ""^^^A"", "">^^^A"" ], ""0 to A"": [ "">A"" ], ""1 to 0"": [ "">vA"" ], ""1 to 1"": [ ""A"" ], ""1 to 2"": [ "">A"" ], ""1 to 3"": [ "">>A"" ], ""1 to 4"": [ ""^A"" ], ""1 to 5"": [ ""^>A"", "">^A"" ], ""1 to 6"": [ ""^>>A"", "">>^A"" ], ""1 to 7"": [ ""^^A"" ], ""1 to 8"": [ ""^^>A"", "">^^A"" ], ""1 to 9"": [ ""^^>>A"", "">>^^A"" ], ""1 to A"": [ "">>vA"" ], ""2 to 0"": [ ""vA"" ], ""2 to 1"": [ ""A"" ], ""2 to 4"": [ ""^A"", "">^A"" ], ""2 to 7"": [ ""^^A"", "">^^A"" ], ""2 to A"": [ ""v>A"", "">vA"" ], ""3 to 0"": [ ""vvvA"" ], ""4 to 1"": [ ""vA"" ], ""4 to 2"": [ ""v>A"", "">vA"" ], ""4 to 3"": [ ""v>>A"", "">>vA"" ], ""4 to 4"": [ ""A"" ], ""4 to 5"": [ "">A"" ], ""4 to 6"": [ "">>A"" ], ""4 to 7"": [ ""^A"" ], ""4 to 8"": [ ""^>A"", "">^A"" ], ""4 to 9"": [ ""^>>A"", "">>^A"" ], ""4 to A"": [ "">>vvA"" ], ""5 to 0"": [ ""vvA"" ], ""5 to 1"": [ ""vA"", "">vA"" ], ""5 to 4"": [ ""A"" ], ""5 to 7"": [ ""^A"", "">^A"" ], ""5 to A"": [ ""vv>A"", "">vvA"" ], ""6 to 0"": [ ""vvvvvA"" ], ""7 to 1"": [ ""vvA"" ], ""7 to 2"": [ ""vv>A"", "">vvA"" ], ""7 to 3"": [ ""vv>>A"", "">>vvA"" ], ""7 to 4"": [ ""vA"" ], ""7 to 5"": [ ""v>A"", "">vA"" ], ""7 to 6"": [ ""v>>A"", "">>vA"" ], ""7 to 7"": [ ""A"" ], ""7 to 8"": [ "">A"" ], ""7 to 9"": [ "">>A"" ], ""7 to A"": [ "">>vvvA"" ], ""8 to 0"": [ ""vvvA"" ], ""8 to 1"": [ ""vvA"", "">vvA"" ], ""8 to 4"": [ ""vA"", "">vA"" ], ""8 to 7"": [ ""A"" ], ""8 to A"": [ ""vvv>A"", "">vvvA"" ], ""9 to 0"": [ ""vvv"": [ ""v>A"", "">vA"" ], ""^ to A"": [ "">A"" ], ""v to ^"": [ ""^A"" ], ""v to v"": [ ""A"" ], ""v to <"": [ """": [ "">A"" ], ""v to A"": [ ""^>A"", "">^A"" ], ""< to ^"": [ "">^A"" ], ""< to v"": [ "">A"" ], ""< to <"": [ ""A"" ], ""< to >"": [ "">>A"" ], ""< to A"": [ "">>^A"" ], ""> to ^"": [ ""^ to v"": [ "" to <"": [ ""< to >"": [ ""A"" ], ""> to A"": [ ""^A"" ], ""A to ^"": [ """": [ ""vA"" ], ""A to A"": [ ""A"" ] } const memory = { } function main() { processInput() let complexity = 0 for (const code of allCodes) { complexity += calcComplexityOf(code) } console.log(""the answer is"", complexity) } function processInput() { const rawLines = input.split(""\n"") for (const rawLine of rawLines) { allCodes.push(rawLine.trim()) } } function calcComplexityOf(code) { const initialSequences = generateInitialSequences(code) const leastSteps = calcLeastSteps(initialSequences) return parseInt(code) * leastSteps } /////////////////////////////////////////////////////////////////////////////// function generateInitialSequences(code) { let lastButton = ""A"" let sequences = [ """" ] for (const button of code) { const temp = [ ] const commands = numericCommandsByMove[lastButton + "" to "" + button] lastButton = button for (const command of commands) { for (const sequence of sequences) { temp.push(sequence + command) } } sequences = temp } return sequences } /////////////////////////////////////////////////////////////////////////////// function calcLeastSteps(initialSequences) { let minLength = Infinity for (const sequence of initialSequences) { const length = findFutureLength(sequence) if (length < minLength) { minLength = length } } return minLength } function findFutureLength(sequence) { const tokens = tokenize(sequence) let length = 0 for (const token of tokens) { length += smallestFutureLengthForToken(token) } return length } function tokenize(sequence) { const tokens = [ ] let token = """" for (const button of sequence) { token += button if (button == ""A"") { tokens. push(token); token = """" } } return tokens } function smallestFutureLengthForToken(token) { let minLength = Infinity const sequences = generateSequencesFromToken(token, 2) for (const sequence of sequences) { if (sequence.length < minLength) { minLength = sequence.length } } return minLength } /////////////////////////////////////////////////////////////////////////////// function generateSequencesFromToken(sourceToken, roundsToGo) { if (roundsToGo == 0) { return [ sourceToken ] } const id = sourceToken + ""~"" + roundsToGo if (memory[id] != undefined) { return memory[id] } // let sequences = [ """" ] let lastButton = ""A"" for (const button of sourceToken) { const temp = [ ] const newTokens = directionalCommandsByMove[lastButton + "" to "" + button] lastButton = button const listA = generateSequencesFromToken(newTokens[0], roundsToGo - 1) let listB = [ ] if (newTokens[1] != undefined) { listB = generateSequencesFromToken(newTokens[1], roundsToGo - 1) } for (const sequence of sequences) { for (const newSequence of listA) { temp.push(sequence + newSequence) } for (const newSequence of listB) { temp.push(sequence + newSequence) } } sequences = temp } memory[id] = sequences return sequences } /////////////////////////////////////////////////////////////////////////////// console.time(""execution time"") main() 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. 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,"const fs = require(""fs""); const positionMap = { ""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], }; const movementMap = { ""^"": [0, 1], ""A"": [0, 2], ""<"": [1, 0], ""v"": [1, 1], "">"": [1, 2], """": [0, 0], }; const directionMapping = { ""-1,0"": ""^"", ""1,0"": ""v"", ""0,-1"": ""<"", ""0,1"": "">"", }; function calculatePath(keyLocations, inputSequence) { let pathSequence = []; for (let i = 0; i < inputSequence.length - 1; i++) { const start = keyLocations[inputSequence[i]]; const end = keyLocations[inputSequence[i + 1]]; const steps = []; const directions = []; if (!start || !end) continue; for (let y = start[1] - 1; y >= end[1]; y--) { steps.push([start[0], y]); directions.push([0, -1]); } for (let x = start[0] + 1; x <= end[0]; x++) { steps.push([x, start[1]]); directions.push([1, 0]); } for (let x = start[0] - 1; x >= end[0]; x--) { steps.push([x, start[1]]); directions.push([-1, 0]); } for (let y = start[1] + 1; y <= end[1]; y++) { steps.push([start[0], y]); directions.push([0, 1]); } if (steps.some((coord) => JSON.stringify(coord) === JSON.stringify(keyLocations[""""]))) { directions.reverse(); } pathSequence.push(...directions.map((direction) => directionMapping[direction.join("","")]), ""A""); } return pathSequence.join(""""); } const inputData = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n""); let totalScore = 0; inputData.forEach((line) => { if (!line) return; let pathToFirstStep = calculatePath(positionMap, ""A"" + line); let pathToSecondStep = calculatePath(movementMap, ""A"" + pathToFirstStep); let finalPath = calculatePath(movementMap, ""A"" + pathToSecondStep); totalScore += parseInt(line.slice(0, -1)) * finalPath.length; }); 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. 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,"const fs = require('fs'); const keypadSequences = fs.readFileSync('input.txt', 'utf8').split('\n'); const 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] }; const keypadBadPosition = [3, 0]; const startKeypad = [3, 2]; const directionalpad = { '#': [0, 0], '^': [0, 1], 'A': [0, 2], '<': [1, 0], 'v': [1, 1], '>': [1, 2] }; const directionalpadBadPosition = [0, 0]; const startdirectionalpad = [0, 2]; const getNumericPart = (code) => { return code.split('').filter(elem => /\d/.test(elem)).join(''); }; const getdirections = (drow, dcol) => { let res = []; if (drow > 0) { res.push('v'.repeat(drow)); } else if (drow < 0) { res.push('^'.repeat(Math.abs(drow))); } if (dcol > 0) { res.push('>'.repeat(dcol)); } else if (dcol < 0) { res.push('<'.repeat(Math.abs(dcol))); } return res.join(''); }; const getPossiblePermutations = (pos, directions, position) => { const perms = new Set(permutations(directions)); let validPerms = []; perms.forEach(perm => { if (validatepath(pos, perm, position)) { validPerms.push(perm.join('')); } }); return validPerms; }; const validatepath = (pos, directions, position) => { let _pos = pos; for (let direction of directions) { if (direction === 'v') { _pos = [_pos[0] + 1, _pos[1]]; } else if (direction === '^') { _pos = [_pos[0] - 1, _pos[1]]; } else if (direction === '>') { _pos = [_pos[0], _pos[1] + 1]; } else if (direction === '<') { _pos = [_pos[0], _pos[1] - 1]; } if (_pos.toString() === position.toString()) { return false; } } return true; }; const getDirectionToWriteCode = (input) => { let pos = startKeypad; let result = []; for (let elem of input) { let nextPos = keypad[elem]; let drow = nextPos[0] - pos[0]; let dcol = nextPos[1] - pos[1]; let directions = getdirections(drow, dcol); let validPaths = getPossiblePermutations(pos, directions, keypadBadPosition); if (result.length === 0) { for (let path of validPaths) { result.push(path + 'A'); } } else { let temp = []; for (let res of result) { for (let path of validPaths) { temp.push(res + path + 'A'); } } result = temp; } pos = nextPos; } return result; }; const getDirectionToWriteDirection = (input) => { let pos = startdirectionalpad; let result = []; for (let elem of input) { let nextPos = directionalpad[elem]; let drow = nextPos[0] - pos[0]; let dcol = nextPos[1] - pos[1]; let directions = getdirections(drow, dcol); let validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition); if (result.length === 0) { for (let path of validPaths) { result.push(path + 'A'); } } else { let temp = []; for (let res of result) { for (let path of validPaths) { temp.push(res + path + 'A'); } } result = temp; } pos = nextPos; } let minLength = Math.min(...result.map(r => r.length)); return result.filter(r => r.length === minLength); }; const getDirectionToWriteDirectionSample = (input) => { let pos = startdirectionalpad; let result = []; for (let elem of input) { let nextPos = directionalpad[elem]; let drow = nextPos[0] - pos[0]; let dcol = nextPos[1] - pos[1]; let directions = getdirections(drow, dcol); let validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition)[0]; result.push(validPaths); result.push('A'); pos = nextPos; } return result.join(''); }; const calculateComplexity = (code) => { let sol1 = getDirectionToWriteCode(code); let sol2 = sol1.flatMap(sol => getDirectionToWriteDirection(sol)); let sol3 = sol2.map(elem => getDirectionToWriteDirectionSample(elem)); console.log(sol3[0]); console.log(sol2[0]); console.log(sol1[0]); console.log(code); let minLength = Math.min(...sol3.map(r => r.length)); let num = getNumericPart(code); console.log(`Code: Numeric: ${num}, minimum length: ${minLength}`); return minLength * parseInt(num); }; let total = 0; keypadSequences.forEach(code => { let score = calculateComplexity(code); total += score; console.log(); }); console.log(total); // Helper function to generate permutations (equivalent to Python's itertools.permutations) function permutations(arr) { let result = []; const permute = (arr, current = []) => { if (arr.length === 0) { result.push(current); return; } for (let i = 0; i < arr.length; i++) { let newArr = [...arr]; // Correctly copy the array newArr.splice(i, 1); // Remove the element at index i permute(newArr, current.concat(arr[i])); // Continue recursion } }; permute(arr); return result; }",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. 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,"const fs = require('fs'); // Read the input file const input = fs.readFileSync('input.txt', { encoding: ""utf8"", flag: ""r"" }); const keypadCodes = input.split('\n'); // Keypad and Directional Pad definitions const keypad = [ ['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], [null, '0', 'A'], ]; const dirpad = [ [null, '^', 'A'], ['<', 'v', '>'] ]; // Function to count occurrences of characters in a string const count = (str) => { let countObj = {}; for (let char of str) { countObj[char] = (countObj[char] || 0) + 1; } return countObj; }; // Function to calculate all shortest best paths on the grid const allShortestBest = (start, grid) => { let pathsObj = {}; let seen = new Set(); seen.add(start.join('|')); let startVal = grid[start[0]][start[1]]; let queue = [[[start, '', startVal]]]; const nextStep = ([r, c], grid) => { return [[r - 1, c, '^'], [r, c + 1, '>'], [r + 1, c, 'v'], [r, c - 1, '<']].filter(([nr, nc, nd]) => grid?.[nr]?.[nc] !== undefined && !seen.has(`${nr}|${nc}`) && !!grid?.[nr]?.[nc] ).map(([nr, nc, nd]) => [[nr, nc], nd].concat(grid[nr][nc])); }; while (queue.length > 0) { let nextQueue = []; let queueSeen = []; queue.forEach((path) => { let last = [point, dir, val] = path.at(-1); let next = nextStep(point, grid); next.forEach(([np, nd, nv]) => { queueSeen.push(np.join('|')); let newPath = path.concat([[np, nd, nv]]); pathsObj[nv] ? pathsObj[nv].push(newPath.map((x) => x[1]).join('')) : pathsObj[nv] = [newPath.map((x) => x[1]).join('')]; nextQueue.push(newPath); }); }); queueSeen.forEach((x) => seen.add(x)); queue = nextQueue; } let bestPaths = {}; Object.entries(pathsObj).forEach(([k, paths]) => { if (paths.length === 1) { bestPaths[`${startVal}${k}`] = `${paths[0]}A`; if (startVal === 'A') bestPaths[k] = `${paths[0]}A`; } else { let order = ''; const pathscore = (path) => { let split = path.split(''); return split.slice(0, -1).map((y, yx) => { let score = 0; if (y !== split[yx + 1]) score += 10; if (order.indexOf(split[yx + 1]) < order.indexOf(y)) score += 5; return score; }).reduce((a, b) => a + b, 0); }; let scores = paths.map((x) => [pathscore(x), x]).sort((a, c) => a[0] - c[0]); bestPaths[`${startVal}${k}`] = `${scores[0][1]}A`; if (startVal === 'A') bestPaths[k] = `${scores[0][1]}A`; } }); return bestPaths; }; let numpadDirs = Object.assign(...keypad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], keypad))); let dirs = Object.assign(...dirpad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], dirpad))); dirs['A'] = 'A'; dirs['AA'] = 'A'; dirs['<<'] = 'A'; dirs['>>'] = 'A'; dirs['^^'] = 'A'; dirs['vv'] = 'A'; const codes = keypadCodes.map((x) => [''].concat(x.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1)).map((x) => x.map((y) => numpadDirs[y])); // First keyboard, array of button presses e.g. ['^^A','vvvA'] for example // Function to calculate the minimum presses required const minPresses = (keypadCodes, dircodes, keyboards) => { let keypadNums = keypadCodes.map((x) => parseInt(x.slice(0, -1))); let targetDepth = keyboards - 1; let result = 0; for (const [index, code] of dircodes.entries()) { let countObj = count(code); for (let i = 0; i < targetDepth; i++) { let newCountObj = {}; for (const [key, val] of Object.entries(countObj)) { if (key.length === 1) { let newKey = dirs[key]; newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; } else { let keySplit = [''].concat(key.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1); keySplit.forEach((sKey) => { let newKey = dirs[sKey]; newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; }); } } countObj = newCountObj; } result += (Object.entries(countObj).map(([k, v]) => k.length * v).reduce((a, b) => a + b, 0) * keypadNums[index]); } return result; }; // Performance tracking and calculation const t0 = performance.now(); let p1 = minPresses(keypadCodes, codes, 3); const t1 = performance.now(); let p2 = minPresses(keypadCodes, codes, 26); const t2 = performance.now(); console.log('Part 1 answer is ', p1, t1 - t0, 'ms'); console.log('Part 2 answer is ', p2, t2 - t1, 'ms'); // Old list of hardcoded directions (commented out for clarity) const olddirs = { '<': 'v<': 'vA', 'A': 'A', '<^': '>^A', 'A', '<>': '>>A', '>^A', '^<': 'v': 'v>A', '^A': '>A', 'v<': '': '>A', 'vA': '^>A', '><': '<v': '^': '<^A', '>A': '^A', 'A<': 'v<': 'vA', '<<': 'A', 'vv': 'A', '^^': 'A', '>>': 'A', 'AA': 'A' };",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. 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,"// solution for https://adventofcode.com/2024/day/21 part 2 // this solution doesn't check all combinations of directional commands // at any possible branch; // instead it uses only directional commands that performed better when // tested ""use strict"" const input = Deno.readTextFileSync(""day21-input.txt"").trim() const allCodes = [ ] const numericCommandsByMove = { // simplest commands only ""0 to 0"": [ ""A"" ], ""0 to 1"": [ ""^A"", "">^A"" ], ""0 to 4"": [ ""^^A"", "">^^A"" ], ""0 to 7"": [ ""^^^A"", "">^^^A"" ], ""0 to A"": [ "">A"" ], ""1 to 0"": [ "">vA"" ], ""1 to 1"": [ ""A"" ], ""1 to 2"": [ "">A"" ], ""1 to 3"": [ "">>A"" ], ""1 to 4"": [ ""^A"" ], ""1 to 5"": [ ""^>A"", "">^A"" ], ""1 to 6"": [ ""^>>A"", "">>^A"" ], ""1 to 7"": [ ""^^A"" ], ""1 to 8"": [ ""^^>A"", "">^^A"" ], ""1 to 9"": [ ""^^>>A"", "">>^^A"" ], ""1 to A"": [ "">>vA"" ], ""2 to 0"": [ ""vA"" ], ""2 to 1"": [ ""A"" ], ""2 to 4"": [ ""^A"", "">^A"" ], ""2 to 7"": [ ""^^A"", "">^^A"" ], ""2 to A"": [ ""v>A"", "">vA"" ], ""3 to 0"": [ ""vvvA"" ], ""4 to 1"": [ ""vA"" ], ""4 to 2"": [ ""v>A"", "">vA"" ], ""4 to 3"": [ ""v>>A"", "">>vA"" ], ""4 to 4"": [ ""A"" ], ""4 to 5"": [ "">A"" ], ""4 to 6"": [ "">>A"" ], ""4 to 7"": [ ""^A"" ], ""4 to 8"": [ ""^>A"", "">^A"" ], ""4 to 9"": [ ""^>>A"", "">>^A"" ], ""4 to A"": [ "">>vvA"" ], ""5 to 0"": [ ""vvA"" ], ""5 to 1"": [ ""vA"", "">vA"" ], ""5 to 4"": [ ""A"" ], ""5 to 7"": [ ""^A"", "">^A"" ], ""5 to A"": [ ""vv>A"", "">vvA"" ], ""6 to 0"": [ ""vvvvvA"" ], ""7 to 1"": [ ""vvA"" ], ""7 to 2"": [ ""vv>A"", "">vvA"" ], ""7 to 3"": [ ""vv>>A"", "">>vvA"" ], ""7 to 4"": [ ""vA"" ], ""7 to 5"": [ ""v>A"", "">vA"" ], ""7 to 6"": [ ""v>>A"", "">>vA"" ], ""7 to 7"": [ ""A"" ], ""7 to 8"": [ "">A"" ], ""7 to 9"": [ "">>A"" ], ""7 to A"": [ "">>vvvA"" ], ""8 to 0"": [ ""vvvA"" ], ""8 to 1"": [ ""vvA"", "">vvA"" ], ""8 to 4"": [ ""vA"", "">vA"" ], ""8 to 7"": [ ""A"" ], ""8 to A"": [ ""vvv>A"", "">vvvA"" ], ""9 to 0"": [ ""vvv"": ""v>A"", // "">vA"" does not result in the shortest sequence ""^ to A"": "">A"", ""v to ^"": ""^A"", ""v to v"": ""A"", ""v to <"": """": "">A"", ""v to A"": ""^>A"", // "">^A"" does not result in the shortest sequence ""< to ^"": "">^A"", ""< to v"": "">A"", ""< to <"": ""A"", ""< to >"": "">>A"", ""< to A"": "">>^A"", ""> to ^"": ""<^A"", // ""^ to v"": "" to <"": ""< to >"": ""A"", ""> to A"": ""^A"", ""A to ^"": """": ""vA"", ""A to A"": ""A"" } const memory = { } function main() { processInput() let complexity = 0 for (const code of allCodes) { complexity += calcComplexityOf(code) } console.log(""the answer is"", complexity) } function processInput() { const rawLines = input.split(""\n"") for (const rawLine of rawLines) { allCodes.push(rawLine.trim()) } } function calcComplexityOf(code) { const initialSequences = generateInitialSequences(code) const leastSteps = calcLeastSteps(initialSequences) return parseInt(code) * leastSteps } /////////////////////////////////////////////////////////////////////////////// function generateInitialSequences(code) { let lastButton = ""A"" let sequences = [ """" ] for (const button of code) { const temp = [ ] const commands = numericCommandsByMove[lastButton + "" to "" + button] lastButton = button for (const command of commands) { for (const sequence of sequences) { temp.push(sequence + command) } } sequences = temp } return sequences } /////////////////////////////////////////////////////////////////////////////// function calcLeastSteps(initialSequences) { let minLength = Infinity for (const sequence of initialSequences) { const length = findFutureLength(sequence) if (length < minLength) { minLength = length } } return minLength } function findFutureLength(sequence) { const tokens = tokenize(sequence) let length = 0 for (const token of tokens) { length += findLengthFromExpandedToken(token, 25) } return length } function tokenize(sequence) { const tokens = [ ] let token = """" for (const button of sequence) { token += button if (button == ""A"") { tokens. push(token); token = """" } } return tokens } /////////////////////////////////////////////////////////////////////////////// function findLengthFromExpandedToken(sourceToken, roundsToGo) { if (roundsToGo == 0) { return sourceToken.length } const id = sourceToken + ""~"" + roundsToGo if (memory[id] != undefined) { return memory[id] } // let length = 0 let lastButton = ""A"" for (const button of sourceToken) { const newToken = directionalCommandsByMove[lastButton + "" to "" + button] lastButton = button length += findLengthFromExpandedToken(newToken, roundsToGo - 1) } memory[id] = length return length } /////////////////////////////////////////////////////////////////////////////// console.time(""execution time"") main() 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. 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,"const fs = require('fs'); const NUMERIC_KEYS = { ""7"": [0, 0], ""8"": [1, 0], ""9"": [2, 0], ""4"": [0, 1], ""5"": [1, 1], ""6"": [2, 1], ""1"": [0, 2], ""2"": [1, 2], ""3"": [2, 2], ""0"": [1, 3], ""A"": [2, 3] }; const DIRECTIONAL_KEYS = { ""^"": [1, 0], ""A"": [2, 0], ""<"": [0, 1], ""v"": [1, 1], "">"": [2, 1] }; const ALLOWED_NUM_POS = new Set(Object.values(NUMERIC_KEYS).map(JSON.stringify)); const ALLOWED_DIR_POS = new Set(Object.values(DIRECTIONAL_KEYS).map(JSON.stringify)); const input = fs.readFileSync('input.txt', 'utf8').split(""\n"").map(x => x.trim()); function findKeystrokes(src, target, directional) { if (JSON.stringify(src) === JSON.stringify(target)) return [""A""]; if (!directional && !ALLOWED_NUM_POS.has(JSON.stringify(src))) return []; if (directional && !ALLOWED_DIR_POS.has(JSON.stringify(src))) return []; const [x1, y1] = src; const [x2, y2] = target; let res = []; if (x1 < x2) res = res.concat(findKeystrokes([x1 + 1, y1], target, directional).map(s => "">"" + s)); if (x1 > x2) res = res.concat(findKeystrokes([x1 - 1, y1], target, directional).map(s => ""<"" + s)); if (y1 < y2) res = res.concat(findKeystrokes([x1, y1 + 1], target, directional).map(s => ""v"" + s)); if (y1 > y2) res = res.concat(findKeystrokes([x1, y1 - 1], target, directional).map(s => ""^"" + s)); return res; } // Memoization to cache previous results of findShortestToClick to prevent redundant work const memoShortest = new Map(); function findShortestToClick(a, b, depth = 2) { const key = `${a},${b},${depth}`; if (memoShortest.has(key)) { return memoShortest.get(key); } const opts = findKeystrokes(DIRECTIONAL_KEYS[a], DIRECTIONAL_KEYS[b], true); if (depth === 1) { const minLen = Math.min(...opts.map(x => x.length)); memoShortest.set(key, minLen); return minLen; } const tmps = opts.map(o => { const tmp = []; tmp.push(findShortestToClick(""A"", o[0], depth - 1)); for (let i = 1; i < o.length; i++) { tmp.push(findShortestToClick(o[i - 1], o[i], depth - 1)); } return tmp.reduce((acc, val) => acc + val, 0); }); const minResult = Math.min(...tmps); memoShortest.set(key, minResult); return minResult; } function findShortest(code, levels) { let pos = NUMERIC_KEYS[""A""]; let shortest = 0; for (let key of code) { const possibleKeySequences = findKeystrokes(pos, NUMERIC_KEYS[key], false); const tmps = possibleKeySequences.map(sequence => { const tmp = []; tmp.push(findShortestToClick(""A"", sequence[0], levels)); for (let i = 1; i < sequence.length; i++) { tmp.push(findShortestToClick(sequence[i - 1], sequence[i], levels)); } return tmp.reduce((acc, val) => acc + val, 0); }); pos = NUMERIC_KEYS[key]; shortest += Math.min(...tmps); } return shortest; } function findTotalComplexity(codes, levels) { const complexities = codes.map(code => { const s = findShortest(code, levels); return s * parseInt(code.slice(0, -1), 10); }); return complexities.reduce((acc, val) => acc + val, 0); } 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. 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,"const fs = require('fs'); const NUM_MAP = { ""7"": [0, 0], ""8"": [1, 0], ""9"": [2, 0], ""4"": [0, 1], ""5"": [1, 1], ""6"": [2, 1], ""1"": [0, 2], ""2"": [1, 2], ""3"": [2, 2], ""0"": [1, 3], ""A"": [2, 3] }; const DIR_MAP = { ""^"": [1, 0], ""A"": [2, 0], ""<"": [0, 1], ""v"": [1, 1], "">"": [2, 1] }; const NUM_POS_SET = new Set(Object.values(NUM_MAP).map(JSON.stringify)); const DIR_POS_SET = new Set(Object.values(DIR_MAP).map(JSON.stringify)); const rawInput = fs.readFileSync('input.txt', 'utf8').split(""\n"").map(line => line.trim()); function generatePath(from, to, isDirectional) { if (JSON.stringify(from) === JSON.stringify(to)) return [""A""]; if (!isDirectional && !NUM_POS_SET.has(JSON.stringify(from))) return []; if (isDirectional && !DIR_POS_SET.has(JSON.stringify(from))) return []; const [xFrom, yFrom] = from; const [xTo, yTo] = to; let movements = []; if (xFrom < xTo) movements = movements.concat(generatePath([xFrom + 1, yFrom], to, isDirectional).map(move => "">"" + move)); if (xFrom > xTo) movements = movements.concat(generatePath([xFrom - 1, yFrom], to, isDirectional).map(move => ""<"" + move)); if (yFrom < yTo) movements = movements.concat(generatePath([xFrom, yFrom + 1], to, isDirectional).map(move => ""v"" + move)); if (yFrom > yTo) movements = movements.concat(generatePath([xFrom, yFrom - 1], to, isDirectional).map(move => ""^"" + move)); return movements; } const memoization = new Map(); function computeMinimalSteps(start, end, maxDepth = 2) { const cacheKey = `${start},${end},${maxDepth}`; if (memoization.has(cacheKey)) { return memoization.get(cacheKey); } const options = generatePath(DIR_MAP[start], DIR_MAP[end], true); if (maxDepth === 1) { const minLength = Math.min(...options.map(opt => opt.length)); memoization.set(cacheKey, minLength); return minLength; } const stepOptions = options.map(option => { const steps = []; steps.push(computeMinimalSteps(""A"", option[0], maxDepth - 1)); for (let i = 1; i < option.length; i++) { steps.push(computeMinimalSteps(option[i - 1], option[i], maxDepth - 1)); } return steps.reduce((sum, step) => sum + step, 0); }); const minResult = Math.min(...stepOptions); memoization.set(cacheKey, minResult); return minResult; } function calculateMinimalCost(sequence, depth) { let position = NUM_MAP[""A""]; let totalCost = 0; for (let digit of sequence) { const paths = generatePath(position, NUM_MAP[digit], false); const pathCosts = paths.map(path => { const cost = []; cost.push(computeMinimalSteps(""A"", path[0], depth)); for (let i = 1; i < path.length; i++) { cost.push(computeMinimalSteps(path[i - 1], path[i], depth)); } return cost.reduce((sum, cost) => sum + cost, 0); }); position = NUM_MAP[digit]; totalCost += Math.min(...pathCosts); } return totalCost; } function calculateTotalEffort(sequences, depth) { const efforts = sequences.map(sequence => { const cost = calculateMinimalCost(sequence, depth); return cost * parseInt(sequence.slice(0, -1), 10); }); return efforts.reduce((total, effort) => total + effort, 0); } 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. 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,"const fs = require('fs'); // Read the input file const input = fs.readFileSync('input.txt', { encoding: ""utf8"", flag: ""r"" }); const keypadCodes = input.split('\n'); // Keypad and Directional Pad definitions const keypad = [ ['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], [null, '0', 'A'], ]; const dirpad = [ [null, '^', 'A'], ['<', 'v', '>'] ]; // Function to count occurrences of characters in a string const count = (str) => { let countObj = {}; for (let char of str) { countObj[char] = (countObj[char] || 0) + 1; } return countObj; }; // Function to calculate all shortest best paths on the grid const allShortestBest = (start, grid) => { let pathsObj = {}; let seen = new Set(); seen.add(start.join('|')); let startVal = grid[start[0]][start[1]]; let queue = [[[start, '', startVal]]]; const nextStep = ([r, c], grid) => { return [[r - 1, c, '^'], [r, c + 1, '>'], [r + 1, c, 'v'], [r, c - 1, '<']].filter(([nr, nc, nd]) => grid?.[nr]?.[nc] !== undefined && !seen.has(`${nr}|${nc}`) && !!grid?.[nr]?.[nc] ).map(([nr, nc, nd]) => [[nr, nc], nd].concat(grid[nr][nc])); }; while (queue.length > 0) { let nextQueue = []; let queueSeen = []; queue.forEach((path) => { let [point, dir, val] = path.at(-1); let next = nextStep(point, grid); next.forEach(([np, nd, nv]) => { queueSeen.push(np.join('|')); let newPath = path.concat([[np, nd, nv]]); pathsObj[nv] ? pathsObj[nv].push(newPath.map((x) => x[1]).join('')) : pathsObj[nv] = [newPath.map((x) => x[1]).join('')]; nextQueue.push(newPath); }); }); queueSeen.forEach((x) => seen.add(x)); queue = nextQueue; } let bestPaths = {}; Object.entries(pathsObj).forEach(([k, paths]) => { if (paths.length === 1) { bestPaths[`${startVal}${k}`] = `${paths[0]}A`; if (startVal === 'A') bestPaths[k] = `${paths[0]}A`; } else { let order = ''; const pathscore = (path) => { let split = path.split(''); return split.slice(0, -1).map((y, yx) => { let score = 0; if (y !== split[yx + 1]) score += 10; if (order.indexOf(split[yx + 1]) < order.indexOf(y)) score += 5; return score; }).reduce((a, b) => a + b, 0); }; let scores = paths.map((x) => [pathscore(x), x]).sort((a, c) => a[0] - c[0]); bestPaths[`${startVal}${k}`] = `${scores[0][1]}A`; if (startVal === 'A') bestPaths[k] = `${scores[0][1]}A`; } }); return bestPaths; }; let numpadDirs = Object.assign(...keypad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], keypad))); let dirs = Object.assign(...dirpad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], dirpad))); dirs['A'] = 'A'; dirs['AA'] = 'A'; dirs['<<'] = 'A'; dirs['>>'] = 'A'; dirs['^^'] = 'A'; dirs['vv'] = 'A'; const codes = keypadCodes.map((x) => [''].concat(x.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1)).map((x) => x.map((y) => numpadDirs[y])); // First keyboard, array of button presses e.g. ['^^A','vvvA'] for example // Function to calculate the minimum presses required const minPresses = (keypadCodes, dircodes, keyboards) => { let keypadNums = keypadCodes.map((x) => parseInt(x.slice(0, -1))); let targetDepth = keyboards - 1; let result = 0; for (const [index, code] of dircodes.entries()) { let countObj = count(code); for (let i = 0; i < targetDepth; i++) { let newCountObj = {}; for (const [key, val] of Object.entries(countObj)) { if (key.length === 1) { let newKey = dirs[key]; newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; } else { let keySplit = [''].concat(key.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1); keySplit.forEach((sKey) => { let newKey = dirs[sKey]; newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; }); } } countObj = newCountObj; } result += (Object.entries(countObj).map(([k, v]) => k.length * v).reduce((a, b) => a + b, 0) * keypadNums[index]); } return result; }; // Performance tracking and calculation const t0 = performance.now(); let p1 = minPresses(keypadCodes, codes, 3); const t1 = performance.now(); let p2 = minPresses(keypadCodes, codes, 26); const t2 = performance.now(); console.log('Part 1 answer is ', p1, t1 - t0, 'ms'); console.log('Part 2 answer is ', p2, t2 - t1, 'ms'); // Old list of hardcoded directions (commented out for clarity) const olddirs = { '<': 'v<': 'vA', 'A': 'A', '<^': '>^A', 'A', '<>': '>>A', '>^A', '^<': 'v': 'v>A', '^A': '>A', 'v<': '': '>A', 'vA': '^>A', '><': '<v': '^': '<^A', '>A': '^A', 'A<': 'v<': 'vA', '<<': 'A', 'vv': 'A', '^^': 'A', '>>': 'A', 'AA': 'A' };",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. 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,"const fs = require('fs'); // Step transformation function function transformNumber(secret) { let transformed = secret; // Perform the 2000 transformations for (let i = 0; i < 2000; i++) { transformed ^= (transformed * 64) & 0xFFFFFF; transformed ^= Math.floor(transformed / 32) & 0xFFFFFF; transformed ^= (transformed * 2048) & 0xFFFFFF; } return transformed; } // Read the file input as a string and split it by lines, then convert to numbers function processInput(filePath) { const data = fs.readFileSync(filePath, 'utf-8'); const numbers = data.split('\n').map(Number); return numbers; } // Calculate the total by processing each number function calculateTotal(filePath) { const numbers = processInput(filePath); let totalSum = 0; // Process each number and accumulate the transformed values numbers.forEach(secret => { totalSum += transformNumber(secret); }); return totalSum; } // Run the main function function main() { const result = calculateTotal('input.txt'); console.log(result); } 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. 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,"const fs = require('fs'); // Function to generate secrets after 2000 iterations function generateSecrets(secret) { let result = []; for (let i = 0; i < 2000; i++) { secret ^= (secret << 6) & 0xFFFFFF; secret ^= (secret >> 5) & 0xFFFFFF; secret ^= (secret << 11) & 0xFFFFFF; result.push(secret); } return result; } // Read the input file and parse into an array of numbers const input = fs.readFileSync(""input.txt"", 'utf-8').trim().split(""\n"").map(Number); // Map each number in the input array to its secret numbers after 2000 steps const secrets = input.map(generateSecrets); // Calculate the total sum of the last secret number from each sequence let totalSum = 0; for (const secretArray of secrets) { totalSum += secretArray[secretArray.length - 1]; } // Output the result 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. 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,"const fs = require('fs'); const hsh = function* (secret) { for (let i = 0; i < 2000; i++) { secret ^= (secret << 6) & 0xFFFFFF; secret ^= (secret >> 5) & 0xFFFFFF; secret ^= (secret << 11) & 0xFFFFFF; yield secret; } }; const ns = fs.readFileSync(""input.txt"", 'utf-8').trim().split(""\n"").map(Number); 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);",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. 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,"// solution for https://adventofcode.com/2024/day/22 part 1 ""use strict"" const input = Deno.readTextFileSync(""day22-input.txt"").trim() const allNumbers = [ ] // BigInts function main() { processInput() let sum = BigInt(0) for (const secret of allNumbers) { sum += processSecretNumber(secret) } console.log(""the answer is"", sum) } function processInput() { const rawLines = input.split(""\n"") for (const rawLine of rawLines) { const number = BigInt(rawLine.trim()) allNumbers.push(number) } } /////////////////////////////////////////////////////////////////////////////// function processSecretNumber(secret) { for (let n = 0; n < 2000; n++) { secret = processSecretNumberOnce(secret) } return secret } function processSecretNumberOnce(secret) { // expecting BigInt const a = secret * BigInt(64) const b = a ^ secret const step1 = b % BigInt(16777216) const c = step1 / BigInt(32) // BigInt automatically rounds down const d = c ^ step1 const step2 = d % BigInt(16777216) const e = step2 * BigInt(2048) const f = e ^ step2 const step3 = f % BigInt(16777216) return step3 } /////////////////////////////////////////////////////////////////////////////// console.time(""execution time"") main() 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. 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,"const fs = require(""fs""); const data = fs.readFileSync(""input.txt"",""utf8"").trim().split(""\n"").map(Number); function nextSecret(s) { // Step 1 let m = s * 64; s ^= m; s &= 0xFFFFFF; // modulo 16777216 // Step 2 m = s >>> 5; // integer division by 32 s ^= m; s &= 0xFFFFFF; // Step 3 m = s * 2048; s ^= m; s &= 0xFFFFFF; return s; } function get2000thSecret(start) { let s = start; for (let i = 0; i < 2000; i++) { s = nextSecret(s); } return s; } const result = data.reduce((sum, val) => sum + get2000thSecret(val), 0); 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. 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,"const fs = require('fs'); function* hsh(secret) { for (let i = 0; i < 2000; i++) { secret ^= (secret << 6) & 0xFFFFFF; secret ^= (secret >> 5) & 0xFFFFFF; secret ^= (secret << 11) & 0xFFFFFF; yield secret; } } function loadFile(filename) { const data = fs.readFileSync(filename, 'utf-8'); return data.split('\n').map(Number); } function calculate() { const ns = loadFile(""input.txt""); const result = {}; for (let n of ns) { const ss = [...hsh(n)].map(s => s % 10); const diffs = ss.slice(1).map((s, i) => s - ss[i]); const changes = new Set(); for (let i = 0; i < 1996; i++) { const change = JSON.stringify(diffs.slice(i, i + 4)); if (!changes.has(change)) { changes.add(change); if (!result[change]) result[change] = 0; result[change] += ss[i + 4]; } } } const max = Math.max(...Object.values(result)); console.log(max); } 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. 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,"const fs = require('fs'); // Generate hash sequence from a given secret function* generateHash(secret) { for (let i = 0; i < 2000; i++) { secret ^= (secret << 6) & 0xFFFFFF; secret ^= (secret >> 5) & 0xFFFFFF; secret ^= (secret << 11) & 0xFFFFFF; yield secret; } } // Read and parse the input file, returning an array of numbers function readInputFile(file) { const fileData = fs.readFileSync(file, 'utf-8'); return fileData.split('\n').map(Number); } // Main calculation function function findMaxBananas() { const numbers = readInputFile(""input.txt""); let patterns = {}; // Store the patterns and their corresponding sums for (let number of numbers) { // Generate hash sequence and calculate prices const hashSequence = [...generateHash(number)].map(hash => hash % 10); const priceDifferences = hashSequence.slice(1).map((currentPrice, idx) => currentPrice - hashSequence[idx]); const uniqueChanges = new Set(); // Track unique 4-change sequences for (let i = 0; i < 1996; i++) { const changesSequence = JSON.stringify(priceDifferences.slice(i, i + 4)); if (!uniqueChanges.has(changesSequence)) { uniqueChanges.add(changesSequence); if (!patterns[changesSequence]) patterns[changesSequence] = 0; patterns[changesSequence] += hashSequence[i + 4]; // Add corresponding price to the sum } } } // Find the maximum sum from all patterns const maxSum = Math.max(...Object.values(patterns)); console.log(maxSum); // Output the result } 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. 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,"const fs = require(""fs""); const data = fs.readFileSync(""input.txt"",""utf8"").trim().split(""\n"").map(Number); function nextSecret(s) { let m = s * 64; s ^= m; s &= 0xFFFFFF; m = s >>> 5; s ^= m; s &= 0xFFFFFF; m = s * 2048; s ^= m; s &= 0xFFFFFF; return s; } // Precompute prices and earliest 4-change sequences for each buyer const buyers = data.map(start => { let secrets = [start]; for (let i = 0; i < 2000; i++) { secrets.push(nextSecret(secrets[secrets.length - 1])); } let prices = secrets.map(s => s % 10); let changesMap = new Map(); for (let i = 0; i < 2000; i++) { // four consecutive changes, if i+3 < 2000 if (i + 3 < 2000) { let c1 = prices[i+1] - prices[i]; let c2 = prices[i+2] - prices[i+1]; let c3 = prices[i+3] - prices[i+2]; let c4 = prices[i+4] - prices[i+3]; let key = `${c1},${c2},${c3},${c4}`; if (!changesMap.has(key)) { changesMap.set(key, i); } } } return { prices, changesMap }; }); // Try all possible 4-change sequences [-9..9] let bestSum = 0; for (let a = -9; a <= 9; a++) { for (let b = -9; b <= 9; b++) { for (let c = -9; c <= 9; c++) { for (let d = -9; d <= 9; d++) { let seqKey = `${a},${b},${c},${d}`; let sumBananas = 0; for (let buyer of buyers) { let idx = buyer.changesMap.get(seqKey); if (idx !== undefined) { // sell at prices[idx+4] sumBananas += buyer.prices[idx+4]; } } if (sumBananas > bestSum) bestSum = sumBananas; } } } } 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. 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,"const fs = require('fs'); // Step transformation function for hashing function* hsh(secret) { for (let i = 0; i < 2000; i++) { secret ^= (secret << 6) & 0xFFFFFF; secret ^= Math.floor(secret / 32) & 0xFFFFFF; secret ^= (secret * 2048) & 0xFFFFFF; yield secret; } } // Function to read and parse the input from the file function readInput(filePath) { const data = fs.readFileSync(filePath, 'utf-8'); return data.split('\n').map(Number); } // Function to calculate and find the result from the secret numbers function calculateMaxChange(inputNumbers) { const result = {}; inputNumbers.forEach((n) => { const ss = [...hsh(n)].map(s => s % 10); const diffs = []; // Calculate the differences between adjacent elements for (let i = 1; i < ss.length; i++) { diffs.push(ss[i] - ss[i - 1]); } const changes = new Set(); // Check for unique 4-length slices of the differences for (let i = 0; i < diffs.length - 4; i++) { const change = JSON.stringify(diffs.slice(i, i + 4)); if (!changes.has(change)) { changes.add(change); const sum = ss[i + 4]; result[change] = (result[change] || 0) + sum; } } }); return Math.max(...Object.values(result)); } // Main execution function main() { const inputNumbers = readInput('input.txt'); const result = calculateMaxChange(inputNumbers); console.log(result); } 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. 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,"""use strict"" const input = Deno.readTextFileSync(""day22-input.txt"").trim() const allNumbers = [ ] // BigInts const SIZE = 19 * 19 * 19 * 19 // four changes of 19 possibilities each (from -9 to +9) const market = [ ] const control = [ ] function main() { processInput() for (let n = 0; n < SIZE; n++) { market.push(0) // total bananas for that four change sequence control.push(-1) } processBuyers() let best = 0 for (const bananas of market) { if (bananas > best) { best = bananas } } console.log(""the answer is"", best) } function processInput() { const rawLines = input.split(""\n"") for (const rawLine of rawLines) { const number = BigInt(rawLine.trim()) allNumbers.push(number) } } /////////////////////////////////////////////////////////////////////////////// function processBuyers() { let buyer = -1 for (const secret of allNumbers) { buyer += 1 processBuyer(buyer, secret) } } function processBuyer(buyer, secret) { let lastPrice = parseInt(secret % BigInt(10)) const changes = [ ] // last four changes only for (let n = 0; n < 2000; n++) { secret = processSecretNumberOnce(secret) const price = parseInt(secret % BigInt(10)) const change = price - lastPrice lastPrice = price if (changes.length < 4) { changes.push(change); continue } changes[0] = changes[1] changes[1] = changes[2] changes[2] = changes[3] changes[3] = change const index = getIndex(changes[0], changes[1], changes[2], changes[3]) if (control[index] == buyer) { continue } // only the first occurrence matters control[index] = buyer market[index] += price } } /////////////////////////////////////////////////////////////////////////////// function getIndex(a, b, c, d) { return (19 * 19 * 19 * (a + 9)) + (19 * 19 * (b + 9)) + (19 * (c + 9)) + (d + 9) } /////////////////////////////////////////////////////////////////////////////// function processSecretNumberOnce(secret) { // expecting BigInt const a = secret * BigInt(64) const b = a ^ secret const step1 = b % BigInt(16777216) const c = step1 / BigInt(32) // BigInt automatically rounds down const d = c ^ step1 const step2 = d % BigInt(16777216) const e = step2 * BigInt(2048) const f = e ^ step2 const step3 = f % BigInt(16777216) return step3 } /////////////////////////////////////////////////////////////////////////////// console.time(""execution time"") main() 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). 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,"const fs = require('fs'); function main() { const input = fs.readFileSync(""input.txt"", 'utf-8').trim(); const lines = input.split(""\n""); const adj = {}; lines.forEach(line => { const [a, b] = line.split(""-""); if (!adj[a]) adj[a] = []; if (!adj[b]) adj[b] = []; adj[a].push(b); adj[b].push(a); }); const triangles = new Set(); for (const a in adj) { const neighborsA = adj[a]; neighborsA.forEach(i => { neighborsA.forEach(j => { if (adj[i].includes(j)) { triangles.add(JSON.stringify([a, i, j].sort())); } }); }); } let ans = 0; triangles.forEach(triangleStr => { const [a, b, c] = JSON.parse(triangleStr); if ([a, b, c].some(node => node.startsWith(""t""))) { ans += 1; } }); console.log(ans); } 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). 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,"const fs = require('fs'); function readFile() { const fileName = ""input.txt""; const mapping = {}; const lines = fs.readFileSync(fileName, 'utf-8').trim().split(""\n""); const tuples = lines.map(line => line.split(""-"")); // Add reverse order as well tuples.forEach(tuple => { mapping[tuple[0]] = mapping[tuple[0]] || []; mapping[tuple[0]].push(tuple[1]); mapping[tuple[1]] = mapping[tuple[1]] || []; mapping[tuple[1]].push(tuple[0]); }); return mapping; } function makeMappingPart1(mapping, computer, depth, lanParty, lanParties) { // We have reached 3 computers, make sure to close the loop if (depth === 0) { if (lanParty[0] === lanParty[lanParty.length - 1] && lanParty.some(computer => computer.startsWith(""t""))) { lanParties.add(JSON.stringify(lanParty.slice(0, 3).sort())); } return; } // Check all computers that are connected to the current one mapping[computer].forEach(val => { lanParty.push(val); makeMappingPart1(mapping, val, depth - 1, lanParty, lanParties); lanParty.pop(); }); } function part1(mapping) { const lanParties = new Set(); // Find all LAN parties with exactly 3 computers for (const computer in mapping) { makeMappingPart1(mapping, computer, 3, [computer], lanParties); } console.log(lanParties.size); } function main() { const mapping = readFile(); console.log(""Answer to part 1:""); part1(mapping); } 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). 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,"const fs = require('fs'); // Read the input file and split into lines const lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); // Initialize connections object using Map to mimic defaultdict const connections = new Map(); const pairs = lines.map(line => line.split('-')); // Create connections between nodes pairs.forEach(pair => { if (!connections.has(pair[0])) connections.set(pair[0], new Set()); if (!connections.has(pair[1])) connections.set(pair[1], new Set()); connections.get(pair[0]).add(pair[1]); connections.get(pair[1]).add(pair[0]); }); // Find trios by checking intersections of connections const trios = new Set(); pairs.forEach(pair => { const intersection = [...connections.get(pair[0])].filter(val => connections.get(pair[1]).has(val)); intersection.forEach(val => { const trio = [pair[0], pair[1], val].sort(); trios.add(JSON.stringify(trio)); }); }); // Filter trios with at least one value starting with 't' const triosWithT = [...trios].filter(trio => { const trioArray = JSON.parse(trio); return trioArray.some(v => v.startsWith('t')); }); 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). 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,"// solution for https://adventofcode.com/2024/day/23 part 1 ""use strict"" const input = Deno.readTextFileSync(""day23-input.txt"").trim() const allConnections = { } const allTargets = { } const alreadyDone = { } var targetCount = 0 function main() { processInput() fillAllTargets() console.log(""the answer is"", targetCount) } function processInput() { const rawLines = input.split(""\n"") for (const rawLine of rawLines) { const pair = rawLine.trim().split(""-"") const a = pair.shift() const b = pair.shift() if (allConnections[a] == undefined) { allConnections[a] = [ ] } if (allConnections[b] == undefined) { allConnections[b] = [ ] } allConnections[a].push(b) allConnections[b].push(a) } } /////////////////////////////////////////////////////////////////////////////// function fillAllTargets() { const allComputers = Object.keys(allConnections) for (const computer of allComputers) { fillTargetsFor(computer) } } function fillTargetsFor(computer) { alreadyDone[computer] = true const friends = allConnections[computer] const off = friends.length for (let a = 0; a < off - 1; a++) { for (let b = a + 1; b < off; b++) { const friendA = friends[a] const friendB = friends[b] if (computer[0] != ""t"" && friendA[0] != ""t"" && friendB[0] != ""t"") { continue } if (alreadyDone[friendA]) { continue } if (alreadyDone[friendB]) { continue } if (! allConnections[friendA].includes(friendB)) { continue } const id = [ computer, friendA, friendB ].sort().join(""~"") if (allTargets[id]) { continue } allTargets[id] = true targetCount += 1 } } } console.time(""execution time"") main() 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). 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,"const fs = require('fs'); function buildGraph(input) { const graph = new Map(); input.split('\n').forEach(line => { const [a, b] = line.split('-'); if (!graph.has(a)) graph.set(a, new Set()); if (!graph.has(b)) graph.set(b, new Set()); graph.get(a).add(b); graph.get(b).add(a); }); return graph; } function findConnectedTriples(graph) { const triples = new Set(); // For each node for (const [node1, neighbors1] of graph) { // For each neighbor of first node for (const node2 of neighbors1) { // For each neighbor of second node for (const node3 of graph.get(node2)) { // Check if third node connects back to first if (node3 !== node1 && graph.get(node3).has(node1)) { // Sort nodes to ensure unique combinations const triple = [node1, node2, node3].sort().join(','); triples.add(triple); } } } } return Array.from(triples); } function countTriplesWithT(triples) { return triples.filter(triple => triple.split(',').some(node => node.startsWith('t')) ).length; } function solve(input) { const graph = buildGraph(input); const triples = findConnectedTriples(graph); return countTriplesWithT(triples); } const input = fs.readFileSync('input.txt', 'utf8').trim(); 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). 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","const fs = require('fs'); // Parse input file function parse() { const lines = fs.readFileSync(""input.txt"", ""utf8"").split(""\n""); return lines.map(line => { const [a, b] = line.trim().split(""-""); return [a, b]; }); } // Generate graph (adjacency list) function generateGraph(connections) { const nodes = {}; connections.forEach(connection => { const [a, b] = connection; if (!nodes[a]) nodes[a] = new Set(); if (!nodes[b]) nodes[b] = new Set(); nodes[a].add(b); nodes[b].add(a); }); return nodes; } // Part 1: Find a three-length loop with at least one containing 't' function part1() { const connections = parse(); const graph = generateGraph(connections); const found = new Set(); for (const node in graph) { const neighbors = graph[node]; neighbors.forEach(neighbor => { graph[neighbor].forEach(neighborsNeighbor => { if (graph[neighborsNeighbor].has(node)) { if (node.startsWith(""t"") || neighbor.startsWith(""t"") || neighborsNeighbor.startsWith(""t"")) { const sortedNodes = [node, neighbor, neighborsNeighbor].sort(); found.add(sortedNodes.join(""-"")); } } }); }); } console.log(found.size); } // Check if a node's neighbors are all in the subgraph function neighborsAll(node, graph, subgraph) { for (const n of subgraph) { if (!graph[n].has(node)) { return false; } } return true; } // Part 2: Find the biggest subgraph where all nodes are connected to each other function part2() { const connections = parse(); const graph = generateGraph(connections); let biggestSubgraph = new Set(); for (const node in graph) { let result = new Set(); result.add(node); graph[node].forEach(neighbor => { if (neighborsAll(neighbor, graph, result)) { result.add(neighbor); } }); if (result.size > biggestSubgraph.size) { biggestSubgraph = result; } } const inOrder = Array.from(biggestSubgraph).sort(); console.log(inOrder.join("","")); } // Run Part 2 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). 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","const fs = require('fs'); function buildGraph(input) { const graph = new Map(); input.split('\n').forEach(line => { const [a, b] = line.split('-'); if (!graph.has(a)) graph.set(a, new Set()); if (!graph.has(b)) graph.set(b, new Set()); graph.get(a).add(b); graph.get(b).add(a); }); return graph; } function isClique(graph, nodes) { // Check if every node connects to every other node for (let i = 0; i < nodes.length; i++) { const neighbors = graph.get(nodes[i]); for (let j = 0; j < nodes.length; j++) { if (i !== j && !neighbors.has(nodes[j])) { return false; } } } return true; } function findMaximalClique(graph) { let maxClique = []; const nodes = Array.from(graph.keys()); // Helper function to extend current clique function extend(current, candidates) { if (candidates.length === 0) { if (current.length > maxClique.length) { maxClique = [...current]; } return; } for (let i = 0; i < candidates.length; i++) { const candidate = candidates[i]; const newCurrent = [...current, candidate]; // Only continue if this is still a valid clique if (isClique(graph, newCurrent)) { // Filter candidates to those that are connected to all current nodes const newCandidates = candidates.slice(i + 1).filter(node => newCurrent.every(currentNode => graph.get(currentNode).has(node) ) ); extend(newCurrent, newCandidates); } } } extend([], nodes); return maxClique; } function solve(input) { const graph = buildGraph(input); const maxClique = findMaximalClique(graph); return maxClique.sort().join(','); } const input = fs.readFileSync('input.txt', 'utf8').trim(); 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). 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","// solution for https://adventofcode.com/2024/day/23 part 2 ""use strict"" const input = Deno.readTextFileSync(""day23-input.txt"").trim() const allConnections = { } const allNetworks = [ ] var greatestNetworkLength = 0 var bestNetwork = [ ] function main() { processInput() fillAllNetworks() search() console.log(""the answer is"", bestNetwork.sort().join("","")) } /////////////////////////////////////////////////////////////////////////////// function processInput() { const rawLines = input.split(""\n"") for (const rawLine of rawLines) { const pair = rawLine.trim().split(""-"") const a = pair.shift() const b = pair.shift() if (allConnections[a] == undefined) { allConnections[a] = [ ] } if (allConnections[b] == undefined) { allConnections[b] = [ ] } allConnections[a].push(b) allConnections[b].push(a) } } function fillAllNetworks() { const allComputers = Object.keys(allConnections) for (const computer of allComputers) { const network = allConnections[computer].slice() network.unshift(computer) allNetworks.push(network) if (network.length > greatestNetworkLength) { greatestNetworkLength = network.length } } } /////////////////////////////////////////////////////////////////////////////// function search() { for (const network of allNetworks) { // searches without removing any member if (! allMembersAreFriends(network)) { continue } if (network.length > bestNetwork.length) { bestNetwork = network } if (bestNetwork.length == greatestNetworkLength) { return } } while (true) { searchRemovingTheWorstMember() if (bestNetwork.length != 0) { return } } } function searchRemovingTheWorstMember() { greatestNetworkLength -= 1 for (const network of allNetworks) { removeTheWorstMember(network) if (! allMembersAreFriends(network)) { continue } if (network.length > bestNetwork.length) { bestNetwork = network } if (bestNetwork.length == greatestNetworkLength) { return } } } /////////////////////////////////////////////////////////////////////////////// function removeTheWorstMember(network) { // expects network having at least one bad member const unfriendship = [ ] for (let n = 0; n < network.length; n++) { unfriendship.push(0) } let worstIndex = 0 let worstValue = -1 const off = network.length for (let a = 0; a < off - 1; a++) { const computerA = network[a] const connectionsA = allConnections[computerA] for (let b = a + 1; b < off; b++) { const computerB = network[b] if (connectionsA.includes(computerB)) { continue } unfriendship[a] += 1 unfriendship[b] += 1 if (unfriendship[a] > worstValue) { worstValue = unfriendship[a]; worstIndex = a } if (unfriendship[b] > worstValue) { worstValue = unfriendship[b]; worstIndex = b } } } // if (worstIndex == -1) { return } // not needed network.splice(worstIndex, 1) } /////////////////////////////////////////////////////////////////////////////// function allMembersAreFriends(network) { const off = network.length for (let a = 0; a < off - 1; a++) { const computerA = network[a] const connectionsA = allConnections[computerA] for (let b = a + 1; b < off; b++) { const computerB = network[b] if (! connectionsA.includes(computerB)) { return false } } } return true } /////////////////////////////////////////////////////////////////////////////// console.time(""execution time"") main() 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). 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","const fs = require('fs'); // Read the input file const inputText = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n""); const connections = {}; // Populate the connections map inputText.forEach(connection => { const [person1, person2] = connection.split(""-""); if (!connections[person1]) connections[person1] = new Set(); if (!connections[person2]) connections[person2] = new Set(); connections[person1].add(person2); connections[person2].add(person1); }); let maxCliqueSize = 0; let maxClique = new Set(); // bron-kerbosch algorithm function bronKerbosch(R, P, X) { if (P.size === 0 && X.size === 0 && R.size > maxCliqueSize) { maxClique = new Set(R); maxCliqueSize = R.size; } // Create a copy of P to iterate over P = new Set(P); P.forEach(person => { bronKerbosch( new Set([...R, person]), intersection(P, connections[person]), intersection(X, connections[person]) ); P.delete(person); X.add(person); }); } // Helper function to find intersection of two sets function intersection(set1, set2) { const result = new Set(); set1.forEach(value => { if (set2.has(value)) { result.add(value); } }); return result; } // Initialize P and X const allPersons = Object.keys(connections); bronKerbosch(new Set(), new Set(allPersons), new Set()); 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). 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","const fs = require('fs'); // Function to check if the nodes form a clique function isClique(connections, nodes) { for (let i = 0; i < nodes.length; i++) { for (let j = i + 1; j < nodes.length; j++) { if (!connections[nodes[i]].has(nodes[j])) { return false; } } } return true; } // Function to find the largest clique starting at a given node function maxCliqueStartingAt(connections, node) { const neighbors = Array.from(connections[node]); for (let i = neighbors.length; i > 1; i--) { const combinations = getCombinations(neighbors, i); for (let group of combinations) { if (isClique(connections, group)) { return new Set([node, ...group]); } } } return new Set(); } // Function to get combinations of a given size from an array function getCombinations(arr, size) { const result = []; const helper = (current, start) => { if (current.length === size) { result.push(current); return; } for (let i = start; i < arr.length; i++) { helper([...current, arr[i]], i + 1); } }; helper([], 0); return result; } // Read input file and process it const fileContent = fs.readFileSync('input.txt', 'utf8').trim().split(""\n""); const connections = {}; fileContent.forEach(line => { const [a, b] = line.split(""-""); if (!connections[a]) connections[a] = new Set(); if (!connections[b]) connections[b] = new Set(); connections[a].add(b); connections[b].add(a); }); // Find the largest clique let cliques = []; Object.keys(connections).forEach(node => { const clique = maxCliqueStartingAt(connections, node); if (clique.size > 0) { cliques.push(clique); } }); // Get the largest clique 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("",""));",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. 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,"const fs = require('fs'); // Helper function to parse the input file and initialize wire values function initializeWires(inputText) { const wires = {}; inputText.forEach(line => { const [wire, val] = line.split("": ""); wires[wire] = parseInt(val, 10); }); return wires; } // Helper function to evaluate gates and update wires function evaluateGates(wires, outVals) { let q = [...outVals]; while (q.length > 0) { const curr = q.shift(); const [wiresIn, outWire] = curr.split("" -> ""); const [left, op, right] = wiresIn.split("" ""); // Skip the gate if the required wires aren't available if (!(left in wires) || !(right in wires)) { q.push(curr); continue; } let result; switch (op) { case ""XOR"": result = wires[left] ^ wires[right]; break; case ""OR"": result = wires[left] | wires[right]; break; case ""AND"": result = wires[left] & wires[right]; break; default: throw new Error(`Unknown operation: ${op}`); } wires[outWire] = result; } } // Helper function to categorize wires by type function categorizeWires(wires) { const xWires = [], yWires = [], zWires = []; for (let wire in wires) { if (wire.includes(""x"")) { xWires.push(wire); } else if (wire.includes(""y"")) { yWires.push(wire); } else if (wire.includes(""z"")) { zWires.push(wire); } } return { xWires, yWires, zWires }; } // Helper function to convert wire values to binary and then decimal function toDecimal(wires, wireList) { const digits = wireList.map(w => wires[w].toString()); return parseInt(digits.join(''), 2); } // Main function function main() { // Read and parse the input file const inputText = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n\n""); const inVals = inputText[0].split(""\n""); const outVals = inputText[1].split(""\n""); // Initialize wires from the input let wires = initializeWires(inVals); // Evaluate the gates evaluateGates(wires, outVals); // Categorize wires into x, y, and z categories const { xWires, yWires, zWires } = categorizeWires(wires); // Sort the wires in reverse order xWires.sort((a, b) => b.localeCompare(a)); yWires.sort((a, b) => b.localeCompare(a)); zWires.sort((a, b) => b.localeCompare(a)); // Convert wire values to decimal const xDec = toDecimal(wires, xWires); const yDec = toDecimal(wires, yWires); const zDec = toDecimal(wires, zWires); // Print the result for part one console.log(""Part One:"", zDec); } // Run the main function 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. 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,"const fs = require('fs'); const readline = require('readline'); // Read input file const inputText = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n\n""); const inVals = inputText[0].split(""\n""); const outVals = inputText[1].split(""\n""); let wires = {}; inVals.forEach(line => { const [wire, val] = line.split("": ""); wires[wire] = parseInt(val, 10); }); let q = [...outVals]; while (q.length > 0) { const curr = q.shift(); const [wiresIn, outWire] = curr.split("" -> ""); const [left, op, right] = wiresIn.split("" ""); if (!(left in wires) || !(right in wires)) { q.push(curr); continue; } let result = -1; if (op === ""XOR"") { result = wires[left] ^ wires[right]; } else if (op === ""OR"") { result = wires[left] | wires[right]; } else if (op === ""AND"") { result = wires[left] & wires[right]; } wires[outWire] = result; } let xWires = [], yWires = [], zWires = []; for (let wire in wires) { if (wire.includes(""x"")) { xWires.push(wire); } else if (wire.includes(""y"")) { yWires.push(wire); } else if (wire.includes(""z"")) { zWires.push(wire); } } xWires.sort((a, b) => b.localeCompare(a)); yWires.sort((a, b) => b.localeCompare(a)); zWires.sort((a, b) => b.localeCompare(a)); let xDigits = xWires.map(w => wires[w].toString()); let yDigits = yWires.map(w => wires[w].toString()); let zDigits = zWires.map(w => wires[w].toString()); let xDec = parseInt(xDigits.join(''), 2); let yDec = parseInt(yDigits.join(''), 2); let zDec = parseInt(zDigits.join(''), 2); let partOne = zDec; 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. 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,"// solution for https://adventofcode.com/2024/day/24 part 1 ""use strict"" const input = Deno.readTextFileSync(""day24-input.txt"").trim() const allWires = { } var gatesToRun = [ ] function main() { processInput() runCircuit() console.log(""the answer is"", calcResult()) } /////////////////////////////////////////////////////////////////////////////// function processInput() { const sections = input.split(""\n\n"") const rawGates = sections.pop().trim().split(""\n"") // doing gates first, some wires will be overriden for (const rawGate of rawGates) { const parts = rawGate.trim().split("" "") const wire1 = parts.shift() const kind = parts.shift() const wire2 = parts.shift() parts.shift() // -> const wire3 = parts.shift() gatesToRun.push(createGateObj(kind, wire1, wire2, wire3)) allWires[wire1] = -1 allWires[wire2] = -1 allWires[wire3] = -1 } const rawWires = sections.pop().trim().split(""\n"") for (const rawWire of rawWires) { const parts = rawWire.split("": "") const wire = parts.shift() const value = parseInt(parts.shift()) allWires[wire] = value } } function createGateObj(kind, wire1, wire2, wire3) { return { ""kind"": kind, ""wire1"": wire1, ""wire2"": wire2, ""wire3"": wire3 } } /////////////////////////////////////////////////////////////////////////////// function runCircuit() { while (gatesToRun.length != 0) { gatesToRun = runCircuitOnce() } } function runCircuitOnce() { const remainingGatesToRun = [ ] for (const gate of gatesToRun) { const value1 = allWires[gate.wire1] if (value1 == -1) { remainingGatesToRun.push(gate); continue } const value2 = allWires[gate.wire2] if (value2 == -1) { remainingGatesToRun.push(gate); continue } const sum = value1 + value2 let output = 0 if (gate.kind == ""AND"") { if (sum == 2) { output = 1 } } else if (gate.kind == ""OR"") { if (sum != 0) { output = 1 } } else if (gate.kind == ""XOR"") { if (sum == 1) { output = 1 } } allWires[gate.wire3] = output } return remainingGatesToRun } /////////////////////////////////////////////////////////////////////////////// function calcResult() { let binary = """" let reversedPos = -1 while (true) { reversedPos += 1 const prefix = (reversedPos < 10) ? ""0"" : """" const wire = ""z"" + prefix + reversedPos const value = allWires[wire] if (value == undefined) { break } binary = value + binary } return parseInt(binary, 2) } console.time(""execution time"") main() 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. 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,"const fs = require('fs'); class Wire { constructor(name, wireVal) { this.name = name; this.wireVal = wireVal; } } class Gate { constructor(logic, input1, input2) { this.logic = logic; this.input1 = input1; this.input2 = input2; } getOutput(wireDict) { if (this.logic === ""AND"") { return (wireDict[this.input1].wireVal === ""1"" && wireDict[this.input2].wireVal === ""1"") ? ""1"" : ""0""; } else if (this.logic === ""OR"") { return (wireDict[this.input1].wireVal === ""1"" || wireDict[this.input2].wireVal === ""1"") ? ""1"" : ""0""; } else if (this.logic === ""XOR"") { return (wireDict[this.input1].wireVal !== wireDict[this.input2].wireVal) ? ""1"" : ""0""; } } } const inputText = fs.readFileSync(""input.txt"", ""utf8"").split(""\n""); let wires = {}; let gates = {}; inputText.forEach(line => { line = line.trim(); if (line.includes("":"")) { const [name, value] = line.split("": ""); wires[name] = new Wire(name, value); } else if (line.includes(""->"")) { const parts = line.split("" ""); gates[parts[4]] = new Gate(parts[1], parts[0], parts[2]); } }); while (Object.keys(gates).some(gate => !(gate in wires))) { Object.keys(gates).forEach(gate => { const currentGate = gates[gate]; if (wires[currentGate.input1] && wires[currentGate.input2]) { const outputVal = currentGate.getOutput(wires); wires[gate] = new Wire(gate, outputVal); } }); } const zWires = Object.keys(wires) .filter(wire => wires[wire].name.startsWith(""z"")) .sort(); let zBits = zWires.reverse().map(z => wires[z].wireVal).join(''); 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. 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,"const fs = require('fs'); // Read input from file const inputText = fs.readFileSync('input.txt', 'utf8').split('\n'); // Initialize wires and gates let wires = {}; let gates = []; let initial = true; inputText.forEach(line => { if (line === '') { initial = false; return; } if (initial) { const [wire, value] = line.split(' '); wires[wire.slice(0, -1)] = parseInt(value); } else { const gate = line.trim().split(' '); gates.push([gate[0], gate[1], gate[2], gate[4], false]); } }); // Initialize wires for gates gates.forEach(gate => { if (!(gate[0] in wires)) { wires[gate[0]] = -1; } if (!(gate[2] in wires)) { wires[gate[2]] = -1; } }); // Process gates until all are done let allDone = false; while (!allDone) { console.log('*', ''); allDone = true; gates.forEach(gate => { if (wires[gate[0]] !== -1 && wires[gate[2]] !== -1 && !gate[4]) { if (gate[1] === 'AND') { wires[gate[3]] = (wires[gate[0]] + wires[gate[2]] === 2) ? 1 : 0; } else if (gate[1] === 'OR') { wires[gate[3]] = (wires[gate[0]] + wires[gate[2]] >= 1) ? 1 : 0; } else { wires[gate[3]] = (wires[gate[0]] !== wires[gate[2]]) ? 1 : 0; } gate[4] = true; console.log('.', ''); } else if (!gate[4]) { allDone = false; } }); } let output = {}; for (const [key, val] of Object.entries(wires)) { if (key[0] === 'z') { output[key] = val; } } let sortedOutput = Object.entries(output).sort((a, b) => { return a[0].localeCompare(b[0]); }); let dec = 0; let power = 0; sortedOutput.forEach(([key, val]) => { console.log(key, val); dec += val * Math.pow(2, power); power += 1; }); 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. 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","const fs = require('fs'); function parseInput(file) { const data = fs.readFileSync(file, 'utf8').trim().split('\n'); const wireValues = {}; const gates = []; data.forEach(line => { if (line.includes('->')) { gates.push(line); } else { const [wire, value] = line.split(': '); wireValues[wire] = parseInt(value, 10); } }); return { wireValues, gates }; } function collectOutputs(wireValues, prefix) { return Object.keys(wireValues) .filter(key => key.startsWith(prefix)) .sort() .map(key => wireValues[key]); } function isInput(operand) { return operand.startsWith('x') || operand.startsWith('y'); } function buildUsageMap(gates) { const usageMap = new Map(); gates.forEach(gate => { const [left, op, right, _, result] = gate.split(' '); [left, right].forEach(key => { if (!usageMap.has(key)) { usageMap.set(key, []); } usageMap.get(key).push(gate); }); }); return usageMap; } function validateXOR(left, right, result, usageMap) { if (isInput(left)) { if (!isInput(right) || (result.startsWith('z') && result !== 'z00')) { return true; } const usageOps = usageMap.get(result)?.map(op => op.split(' ')[1]) || []; if (result !== 'z00' && usageOps.sort().join(',') !== 'AND,XOR') { return true; } } else if (!result.startsWith('z')) { return true; } return false; } function validateAND(left, right, result, usageMap) { if (isInput(left) && !isInput(right)) { return true; } const usageOps = usageMap.get(result)?.map(op => op.split(' ')[1]) || []; return usageOps.join(',') !== 'OR'; } function validateOR(left, right, result, usageMap) { if (isInput(left) || isInput(right)) { return true; } const usageOps = usageMap.get(result)?.map(op => op.split(' ')[1]) || []; return usageOps.sort().join(',') !== 'AND,XOR'; } function findSwappedWires(wireValues, gates) { const usageMap = buildUsageMap(gates); const swappedWires = new Set(); gates.forEach(gate => { const [left, op, right, _, result] = gate.split(' '); if (result === 'z45' || left === 'x00') return; if ((op === 'XOR' && validateXOR(left, right, result, usageMap)) || (op === 'AND' && validateAND(left, right, result, usageMap)) || (op === 'OR' && validateOR(left, right, result, usageMap))) { swappedWires.add(result); } }); return [...swappedWires].sort(); } const { wireValues, gates } = parseInput('input.txt'); 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. 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","import { readFileSync } from ""fs""; export default function day24() { let input = readFileSync('input.txt', 'utf-8'); let [inputsS, ops] = input.split(/(?:\r?\n){2}/) let adjList = {}; for(let line of ops.split(/\r?\n/)) { let [v, output] = line.split(' -> '); let [_, v0, op, v1] = v.match(/(\w+) (\w+) (\w+)/); let operation = [v0, op, v1]; adjList[output] = operation; } let [definitelyBroken, maybeBrokenMap] = getBreakages(false); let maybeBrokenArr = [...maybeBrokenMap.keys()]; let definitelyBrokenIndexes = [...definitelyBroken].map(x => maybeBrokenArr.findIndex(z => z === x)); // console.log(...maybeBrokenMap.entries()) console.log(definitelyBroken) console.log(maybeBrokenMap) let result = dfs(maybeBrokenArr, new Set()); return result.sort().join(','); function dfs(maybeBroken, used) { if(used.size === 8) { for(let idx of definitelyBrokenIndexes) { if(!used.has(idx)) { return false; } } let [_, maybeBroken2] = getBreakages(true); if(!maybeBroken2.size) { return [...used].map(x => maybeBroken[x]); } return false; } for(let i = 0; i < maybeBroken.length; ++i) { if(!definitelyBrokenIndexes.includes(i) && used.size < definitelyBrokenIndexes.length) { continue; } if(used.has(i)) { continue; } used.add(i); for(let j = i+1; j < maybeBroken.length; ++j) { if(used.has(j)) { continue; } used.add(j); let v1 = maybeBroken[i]; let v2 = maybeBroken[j]; [adjList[v1], adjList[v2]] = [adjList[v2], adjList[v1]]; let ret = dfs(maybeBroken, used); if(ret) { return ret; } [adjList[v1], adjList[v2]] = [adjList[v2], adjList[v1]]; used.delete(j); } used.delete(i); } } function getBreakages(bailEarly) { let definitelyBroken = new Set(); let maybeBrokenMap = new Map(); function maybeBroken(...nodes) { if(nodes.length < 2) { definitelyBroken.add(nodes[0]); } for(let node of nodes) { if(node) { maybeBrokenMap.set(node, (maybeBrokenMap.get(node)??0)+1); } } return false; } for(let i = 0; i < 45; ++i) { if(maybeBrokenMap.size && bailEarly) { return [definitelyBroken, maybeBrokenMap]; } let v = `z${i.toString().padStart(2, '0')}`; derive(v, i) } return [definitelyBroken, maybeBrokenMap]; function derive(v0, num) { //expected: XOR(XOR(n), NEXT) if(num < 1) { if(!isXorFor(v0, num)) { return maybeBroken(v0); } return true; } let next = adjList[v0]; if(next[1] !== 'XOR') { // console.log(`broke -1 -->${v0}<--:..... (${i})`); return maybeBroken(v0); } let [v1, op, v2] = next; if(!adjList[v1] || !adjList[v2]) { return maybeBroken(v0); } if(adjList[v2][1] === 'XOR') { [v1, v2] = [v2, v1]; } if(adjList[v1][1] !== 'XOR') { return maybeBroken(v0, v1, v2);//TODO not sure which?! } if(!isXorFor(v1, num)) { return maybeBroken(v0, v1, v2); } //XOR OK... NOW FOR CARRY return deriveCarry(v2, num-1); } function deriveCarry(v0, num) { let [v1, op, v2] = adjList[v0]; if(num === 0) { if(isAndFor(v0, num)) { return true; } return maybeBroken(v0); } if(op !== 'OR') { return maybeBroken(v0); } if(isAndFor(v2, num)) { [v2, v1] = [v1, v2]; } if(!isAndFor(v1, num)) { return maybeBroken(v0, v1, v2); } return deriveCarry2(v2, num); } function isAndFor(v0, num) { if(!adjList[v0]) { return maybeBroken(v0); } let [v1, op, v2] = adjList[v0]; if(op !== 'AND' || !isForNum(v0, num)) { return false; } return true; } function isXorFor(v0, num) { if(!adjList[v0]) { return maybeBroken(v0); } let [v1, op, v2] = adjList[v0]; if(op !== 'XOR' || !isForNum(v0, num)) { return false; } return true; } function isForNum(v0, num) { let [v1, op, v2] = adjList[v0]; let digit1 = String.fromCharCode((Math.floor(num/10) % 10) + '0'.charCodeAt(0)); let digit2 = String.fromCharCode((num % 10) + '0'.charCodeAt(0)); return !(v1[1] !== digit1 || v1[2] !== digit2 || v2[1] !== digit1 || v2[2] !== digit2); } function deriveCarry2(v0, num) { let [v1, op, v2] = adjList[v0]; if(op !== 'AND') { return maybeBroken(v0); } if(isXorFor(v2, num)) { [v1, v2] = [v2, v1]; } if(!isXorFor(v1, num)) { return maybeBroken(v0, v1, v2); } return deriveCarry(v2, num-1) } } } console.time() console.log(day24()); 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. 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","const fs = require('fs'); function getExprForOutput(output) { return outputToExpr[swaps[output] || output]; } function getOutputForExpr(expr) { const output = exprToOutput[expr]; return swaps[output] || output; } function swap(outA, outB) { console.log(`SWAP: ${outA} for ${outB}`); swaps[outA] = outB; swaps[outB] = outA; } function findMatchingExpr(output, op) { const matching = Object.keys(exprToOutput).filter(expr => { const [left, right, operator] = expr.split(','); return operator === op && [left, right].includes(output); }); if (matching.length === 0) { return null; } if (matching.length > 1) { throw new Error('More than one matching expression found'); } return matching[0].split(','); } const outputToExpr = {}; const exprToOutput = {}; const swaps = {}; const carries = []; let maxInputBitIndex = -1; const lines = fs.readFileSync('input.txt', 'utf8').split('\n'); lines.forEach(line => { if (line.includes(""->"")) { const [expr, wire] = line.split("" -> ""); const [left, op, right] = expr.split("" ""); const sortedOperands = [left, right].sort(); outputToExpr[wire] = [sortedOperands[0], sortedOperands[1], op]; exprToOutput[`${sortedOperands[0]},${sortedOperands[1]},${op}`] = wire; } if (line.includes("":"")) { maxInputBitIndex = Math.max(maxInputBitIndex, parseInt(line.split("":"")[0].slice(1))); } }); const numInputBits = maxInputBitIndex + 1; for (let i = 0; i < numInputBits; i++) { const zOutput = `z${i.toString().padStart(2, '0')}`; const inputXorExpr = [`x${i.toString().padStart(2, '0')}`, `y${i.toString().padStart(2, '0')}`, ""XOR""]; const inputAndExpr = [`x${i.toString().padStart(2, '0')}`, `y${i.toString().padStart(2, '0')}`, ""AND""]; const inputXorOutput = getOutputForExpr(inputXorExpr); const inputAndOutput = getOutputForExpr(inputAndExpr); if (i === 0) { if (zOutput === inputXorOutput) { carries.push(inputAndOutput); continue; } else { throw new Error(""Error in first digits""); } } let resultExpr = findMatchingExpr(inputXorOutput, ""XOR""); if (resultExpr === null) { resultExpr = findMatchingExpr(carries[i - 1], ""XOR""); const actualInputXorOutput = resultExpr[0] === carries[i - 1] ? resultExpr[1] : resultExpr[0]; swap(actualInputXorOutput, inputXorOutput); } else { const carryInput = resultExpr[0] === inputXorOutput ? resultExpr[1] : resultExpr[0]; if (carryInput !== carries[i - 1]) { swap(carryInput, carries[i - 1]); carries[i - 1] = carryInput; } } if (zOutput !== getOutputForExpr(resultExpr)) { swap(zOutput, getOutputForExpr(resultExpr)); } const intermediateCarryExpr = [getOutputForExpr(inputXorExpr), carries[i - 1]].sort().concat(""AND""); const intermediateCarryOutput = getOutputForExpr(intermediateCarryExpr); let carryExpr = findMatchingExpr(intermediateCarryOutput, ""OR""); if (carryExpr === null) { console.log(""TODO""); } else { const expectedInputAndOutput = carryExpr[0] === intermediateCarryOutput ? carryExpr[1] : carryExpr[0]; if (expectedInputAndOutput !== getOutputForExpr(inputAndExpr)) { swap(getOutputForExpr(inputAndExpr), expectedInputAndOutput); } } const carryExprSorted = [getOutputForExpr(inputAndExpr), intermediateCarryOutput].sort().concat(""OR""); const carryOutput = getOutputForExpr(carryExprSorted); carries.push(carryOutput); } 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. 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","// solution for https://adventofcode.com/2024/day/24 part 2 // *NOT* EXPECTING TWO GATES TO HAVE THE SAME OUTPUT WIRE // this puzzle is about a circuit for binary sum (x + y = z); // for each set of three bits (x,y,z) there is a small standard // circuit of wires and gates that is repeated many times (45 in my input) // this small *standard* circuit always starts by connecting a xy bit pair to // a pair of bottom gates (one gate is AND, the other gate is XOR); any error // only happens after this part // this solution compares each part of the small circuits, searching for the // misplaced output wires that breaks the *pattern*, level by level ""use strict"" const input = Deno.readTextFileSync(""day24-input.txt"").trim() var xySlotsLength = 0 const gatesByOutput = { } const gatesByInput = { } const misplacedOutputWires = [ ] function main() { processInput() let gates = processBottomGates() while (true) { searchMisplacedWires(gates) if (misplacedOutputWires.length == 8) { break } gates = processNextLevelGates(gates) } console.log(""the answer is"", misplacedOutputWires.sort().join("","")) } /////////////////////////////////////////////////////////////////////////////// function processInput() { const sections = input.split(""\n\n"") xySlotsLength = sections.shift().trim().split(""\n"").length // despising xyWires const rawGates = sections.shift().trim().split(""\n"") for (const rawGate of rawGates) { const parts = rawGate.trim().split("" "") const wire1 = parts.shift() const kind = parts.shift() const wire2 = parts.shift() parts.shift() // -> const wire3 = parts.shift() processThisInput(kind, wire1, wire2, wire3) } } function processThisInput(kind, wire1, wire2, wire3) { const gate = createGateObj(kind, wire1, wire2, wire3) gatesByOutput[wire3] = gate if (gatesByInput[wire1] == undefined) { gatesByInput[wire1] = [ ] } if (gatesByInput[wire2] == undefined) { gatesByInput[wire2] = [ ] } gatesByInput[wire1].push(gate) gatesByInput[wire2].push(gate) } function createGateObj(kind, wire1, wire2, wire3) { return { ""kind"": kind, ""wire1"": wire1, ""wire2"": wire2, ""wire3"": wire3, ""paste"": """", ""forward"": """" } } /////////////////////////////////////////////////////////////////////////////// function processBottomGates() { const bottomGates = new Array(xySlotsLength) for (const gate of Object.values(gatesByOutput)) { if (gate.wire1[0] != ""x"" && gate.wire1[0] != ""y"") { continue } const xySlot = gate.wire1.substr(1) const index = (2 * parseInt(xySlot)) + (gate.kind == ""AND"" ? 0 : 1) bottomGates[index] = gate gate.paste = ""xy"" gate.forward = findGateForward(gate.wire3) } return bottomGates } /////////////////////////////////////////////////////////////////////////////// function processNextLevelGates(parentList) { const childrenList = [ ] for (const parent of parentList) { const wire = parent.wire3 if (wire[0] == ""z"") { continue } if (misplacedOutputWires.includes(wire)) { continue } const nextGates = gatesByInput[wire] for (const nextGate of nextGates) { nextGate.paste = parent.paste + "" "" + parent.kind nextGate.forward = findGateForward(nextGate.wire3) childrenList.push(nextGate) } } return childrenList } /////////////////////////////////////////////////////////////////////////////// function findGateForward(wire) { if (wire[0] == ""z"") { return ""FINAL"" } const list = [ ] for (const destinyGate of gatesByInput[wire]) { list.push(destinyGate.kind) } return list.sort().join(""-"") } /////////////////////////////////////////////////////////////////////////////// function searchMisplacedWires(gates) { const patterns = { } for (const gate of gates) { const pattern = [ gate.paste, gate.kind, gate.forward ].join("" . "") if (isSpecialCase(gate, pattern)) { continue } if (patterns[pattern] == undefined) { patterns[pattern] = [ ] } patterns[pattern].push(gate.wire3) } for (const list of Object.values(patterns)) { if (list.length > 8) { continue } for (const wire of list) { misplacedOutputWires.push(wire) } } } function isSpecialCase(gate, pattern) { if (pattern == ""xy . XOR . FINAL"") { return isFirstXYSlot(gate) } if (pattern == ""xy . AND . AND-XOR"") { return isFirstXYSlot(gate) } if (pattern == ""xy AND . OR . FINAL"") { return isLastZSlot(gate) } return false } function isFirstXYSlot(gate) { return gate.wire1.substr(1) == ""00"" } function isLastZSlot(gate) { if (gate.wire3[0] != ""z"") { return false } const zSlot = parseInt(gate.wire3.substr(1)) return zSlot == xySlotsLength / 2 } /////////////////////////////////////////////////////////////////////////////// function show(gates) { console.log("""") for (const gate of gates) { showGate(gate) } } function showGate(gate) { // slot is only meaningful for base gates! console.log({ ""slot"": gate.wire1.substr(1), ""kind"": gate.kind, ""paste"": gate.paste, ""forward"": gate.forward }) } /////////////////////////////////////////////////////////////////////////////// console.time(""execution time"") main() 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. 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","const fs = require('fs'); function collectOutputs(wireValues, prefix) { return Object.entries(wireValues) .filter(([key]) => key.startsWith(prefix)) .sort() .map(([, value]) => value); } function isInput(operand) { return operand[0] === 'x' || operand[0] === 'y'; } function getUsageMap(gates) { const usageMap = {}; gates.forEach(gate => { const parts = gate.split(' '); if (!usageMap[parts[0]]) usageMap[parts[0]] = []; if (!usageMap[parts[2]]) usageMap[parts[2]] = []; usageMap[parts[0]].push(gate); usageMap[parts[2]].push(gate); }); return usageMap; } function checkXorConditions(left, right, result, usageMap) { if (isInput(left)) { if (!isInput(right) || (result[0] === 'z' && result !== 'z00')) { return true; } const usageOps = (usageMap[result] || []).map(op => op.split(' ')[1]); if (result !== 'z00' && usageOps.sort().toString() !== ['AND', 'XOR'].toString()) { return true; } } else if (result[0] !== 'z') { return true; } return false; } function checkAndConditions(left, right, result, usageMap) { if (isInput(left) && !isInput(right)) { return true; } const usageOps = (usageMap[result] || []).map(op => op.split(' ')[1]); if (usageOps.toString() !== ['OR'].toString()) { return true; } return false; } function checkOrConditions(left, right, result, usageMap) { if (isInput(left) || isInput(right)) { return true; } const usageOps = (usageMap[result] || []).map(op => op.split(' ')[1]); if (usageOps.sort().toString() !== ['AND', 'XOR'].toString()) { return true; } return false; } function findSwappedWires(wireValues, gates) { const usageMap = getUsageMap(gates); const swappedWires = new Set(); gates.forEach(gate => { const [left, op, right, , result] = gate.split(' '); if (result === 'z45' || left === 'x00') return; if (op === 'XOR' && checkXorConditions(left, right, result, usageMap)) { swappedWires.add(result); } else if (op === 'AND' && checkAndConditions(left, right, result, usageMap)) { swappedWires.add(result); } else if (op === 'OR' && checkOrConditions(left, right, result, usageMap)) { swappedWires.add(result); } else { console.log(gate, 'unknown op'); } }); return Array.from(swappedWires).sort(); } function parseInput(fileName) { const data = fs.readFileSync(fileName, 'utf8').split('\n'); const wireValues = {}; const gates = []; data.forEach(line => { const [expr, result] = line.split(' -> '); if (!result) return; // Skip lines that don't have a valid result const [left, op, right] = expr.split(' '); if (result && result.startsWith('z')) { wireValues[result] = 0; // Set default value for z wires } gates.push(`${left} ${op} ${right} -> ${result}`); }); return [wireValues, gates]; } const [wireValues, gates] = parseInput('input.txt'); const swappedWires = findSwappedWires(wireValues, gates); const result = swappedWires.join(','); 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. 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,"const fs = require('fs'); const lines = fs.readFileSync('input.txt','utf8') .trim().split(/\n\s*\n/).map(chunk => chunk.split('\n')); function isLock(p) { return p[0] === '#####'; } function parseLockHeights(p) { const res = []; for (let c=0; c<5; c++){ let h=0; for (let r=1; r<=5; r++){ if (p[r][c] === '#') h++; else break; } res.push(h); } return res; } function parseKeyHeights(p) { const res = []; for (let c=0; c<5; c++){ let h=0; for (let r=5; r>=1; r--){ if (p[r][c] === '#') h++; else break; } res.push(h); } return res; } const locks = [], keys = []; for (const pat of lines) { const arr = isLock(pat) ? parseLockHeights(pat) : parseKeyHeights(pat); isLock(pat) ? locks.push(arr) : keys.push(arr); } let count=0; for (const lock of locks){ for (const key of keys){ if (lock.every((l,i)=>l+key[i]<=5)) count++; } } 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. 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,"const fs = require(""fs""); const inputText = ""./input.txt""; fs.readFile(inputText, ""utf8"", (err, data) => { if (err) { console.error('Error reading file:', err); return; } const lockKeyData = { locks: [], keys: [] }; data.split(""\n\n"").forEach(group => { const rows = group.split(""\n""); let topRow = rows.shift().split(""""); let bottomRow = rows.pop().split(""""); let zeroPinHeights = new Array(rows[0].length).fill(0); const pinHeights = rows.reduce((heights, row) => { row.split("""").forEach((char, i) => { if (char === ""#"") heights[i]++; }); return heights; }, zeroPinHeights); let isLock = topRow.every(item => item === ""#"") && bottomRow.every(item => item === "".""); let isKey = topRow.every(item => item === ""."") && bottomRow.every(item => item === ""#""); if (isLock) lockKeyData.locks.push(pinHeights); if (isKey) lockKeyData.keys.push(pinHeights); }) console.log(part1(lockKeyData)); // console.log(part2(data)); // part2(data); }); const part1 = (lockKeyData) => { const { locks, keys } = lockKeyData; let pairs = 0; locks.forEach(lock => { keys.forEach(key => { const hasOverlap = lock.some((pin, index) => pin + key[index] > 5); if (!hasOverlap) pairs++; }); }); return pairs; } // 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. 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,"const fs = require('fs'); // Read the input file and split by empty lines const lines = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); // Function to parse each schematic function parse(schematic) { const isLock = schematic[0][0] === ""#""; const vals = []; if (isLock) { // Lock parsing for (let j = 0; j < 5; j++) { for (let i = 0; i < 7; i++) { if (schematic[i][j] === ""."") { vals.push(i); break; } } } return [vals, isLock]; } // Key parsing for (let j = 0; j < 5; j++) { for (let i = 6; i >= 0; i--) { if (schematic[i][j] === ""."") { vals.push(6 - i); break; } } } return [vals, isLock]; } // Separate locks and keys const locks = []; const keys = []; lines.forEach(line => { const [vals, isLock] = parse(line.split(""\n"")); if (isLock) { locks.push(vals); } else { keys.push(vals); } }); // Calculate the answer let ans = 0; locks.forEach(lock => { keys.forEach(key => { let good = true; for (let j = 0; j < 5; j++) { if (lock[j] + key[j] > 7) { good = false; break; } } if (good) ans++; }); }); 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. 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,"const fs = require('fs'); // Read the input file and split by empty lines const lines = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); // Process the schematics const schematics = lines.map(line => line.split('\n')); let partOne = 0; const keys = new Set(); const locks = new Set(); schematics.forEach(schematic => { const isLock = schematic[0][0] === '#'; const width = schematic[0].length; // Transpose the columns const cols = Array.from({ length: width }, (_, i) => schematic.map(row => row[i])); // Calculate heights const heights = cols.map(c => c.filter(cell => cell === '#').length - 1); // Add to locks or keys set if (isLock) { locks.add(JSON.stringify(heights)); } else { keys.add(JSON.stringify(heights)); } }); // Compare locks and keys locks.forEach(lockStr => { const lock = JSON.parse(lockStr); keys.forEach(keyStr => { const key = JSON.parse(keyStr); const maxKey = lock.map(h => 5 - h); if (key.every((h, i) => h <= maxKey[i])) { partOne += 1; } }); }); 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. 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,"const fs = require('fs'); // Read the input file const lines = fs.readFileSync('input.txt', 'utf8').split('\n'); // Initialize arrays to hold locks and keys let locks = []; let keys = []; // Process the schematic data for (let i = 0; i < lines.length; i += 8) { const schematic = lines.slice(i + 1, i + 6).map(line => line.trim()); const schematic_transposed = schematic[0].split('').map((_, index) => schematic.map(row => row[index])); const pins = schematic_transposed.map(a => a.filter(c => c === '#').length); if (lines[i] === '#####') { locks.push(pins); // lock } else if (lines[i] === '.....') { keys.push(pins); // key } } // Calculate the sum let sum = 0; locks.forEach(lock => { keys.forEach(key => { const test = lock.map((pin, i) => pin + key[i]); if (Math.max(...test) < 6) { sum += 1; } }); }); 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