year,day,part,question,answer,solution,language 2024,2,1,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,2,1,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,2,1,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,2,1,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,2,2,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,2,2,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,2,2,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,2,2,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,2,2,"--- Day 2: Red-Nosed Reports --- Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. 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:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,1,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,1,2,"--- Day 1: Historian Hysteria --- The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. 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:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,1,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,3,2,"--- Day 3: Mull It Over --- ""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. 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:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,1,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,4,2,"--- Day 4: Ceres Search --- ""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! 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:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,1,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,5,2,"--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. 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:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,6,1,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,6,2,"--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. 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:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,1,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 2024,7,2,"--- Day 7: Bridge Repair --- The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? 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:3.9 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:3.9 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:3.9 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:3.9 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:3.9 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:3.9 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:3.9 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:3.9 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:3.9 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:3.9 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:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,1,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,9,2,"--- Day 9: Disk Fragmenter --- Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. 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:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,10,1,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,10,2,"--- Day 10: Hoof It --- You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. 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:3.9 2024,11,1,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"stones = open('input.txt').read().strip().split(' ') stones = [int(x) for x in stones] def get_next_stones(): for i in range(len(stones)): if stones[i] == 0: stones[i] = 1 elif len(str(stones[i])) % 2 == 0: num = str(stones[i]) # print(num) stones[i] = int(num[:len(num)//2]) stones.append(int(num[len(num)//2:])) else: stones[i] *= 2024 for i in range(25): # print(stones) get_next_stones() print(len(stones))",python:3.9.21-slim 2024,11,1,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def rules(n): if n == 0: return [1] s = str(n) if len(s) % 2 == 0: l = len(s) // 2 return [int(s[:l]), int(s[l:])] return [n * 2024] def calc(stone, blinks): if blinks == 0: return 1 new = rules(stone) return sum(calc(num, blinks - 1) for num in new) res = 0 stones = list(map(int, open('i.txt').read().split())) for stone in stones: res += calc(stone, 25) print(res)",python:3.9.21-slim 2024,11,1,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def blink(stones): newStones = [] for stone in stones: if stone == 0: newStones.append(1) continue n = len(str(stone)) if n % 2 == 0: newStones.append(int(str(stone)[:(n//2)])) newStones.append(int(str(stone)[(n//2):])) continue newStones.append(stone * 2024) return newStones def get_num_stones(stones): for _ in range(25): stones = blink(stones) return len(stones) if __name__ == ""__main__"": # Open file 'day11-1.txt' in read mode with open('day11-1.txt', 'r') as f: stones = [] for line in f: stones = [int(val) for val in line.strip().split()] print(""Number of Stones: "" + str(get_num_stones(stones)))",python:3.9.21-slim 2024,11,1,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"def get_next_array(stones): res = [] for stone in stones: if stone == 0: res.append(1) elif len(str(stone)) % 2 == 0: stone_str = str(stone) res.append(int(stone_str[0:len(stone_str)//2])) res.append(int(stone_str[len(stone_str)//2:])) else: res.append(stone * 2024) return res with open('input.txt') as f: stones = [int(s) for s in f.read().split()] for i in range(25): stones = get_next_array(stones) print(len(stones))",python:3.9.21-slim 2024,11,1,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"from functools import cache @cache def blink(value, times): if times == 0: return 1 if value == 0: return blink(1, times - 1) digits = len(str(value)) if digits % 2 == 0: return blink(int(str(value)[:digits // 2]), times - 1) + blink( int(str(value)[digits // 2:]), times - 1) return blink(value * 2024, times - 1) with open(""input.txt"") as file: stones = file.read().strip().split() result = sum([blink(int(stone), 25) for stone in stones]) print(result)",python:3.9.21-slim 2024,11,2,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import cache with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() @cache def stones_created(num, rounds): if rounds == 0: return 1 elif num == 0: return stones_created(1, rounds - 1) elif len(str(num)) % 2 == 0: return stones_created( int(str(num)[: len(str(num)) // 2]), rounds - 1 ) + stones_created(int(str(num)[len(str(num)) // 2 :]), rounds - 1) else: return stones_created(num * 2024, rounds - 1) nums = [int(x) for x in input_text[0].split()] print(sum(stones_created(x, 75) for x in nums))",python:3.9.21-slim 2024,11,2,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import cache @cache def blink(value, times): if times == 0: return 1 if value == 0: return blink(1, times - 1) digits = len(str(value)) if digits % 2 == 0: return blink(int(str(value)[:digits // 2]), times - 1) + blink( int(str(value)[digits // 2:]), times - 1) return blink(value * 2024, times - 1) with open(""input.txt"") as file: stones = file.read().strip().split() result = sum([blink(int(stone), 75) for stone in stones]) print(result)",python:3.9.21-slim 2024,11,2,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"from functools import lru_cache def is_even(num): count = 0 a = num while a: a //= 10 count += 1 return count % 2 == 0 @lru_cache(maxsize=1000_000) def check_stone(stone): if stone == 0: return (1, -1) if is_even(stone): s = str(stone) l = s[: len(s) // 2] r = s[len(s) // 2 :] return (int(l), int(r)) return (stone * 2024, -1) in_date = """" with open(""input.txt"") as f: in_date = f.read() init_stones = [int(i) for i in in_date.strip().split()] total_nums = {} for i in init_stones: res = total_nums.get(i, 0) + 1 total_nums[i] = res for iter in range(75): new_total_nums = {} for n, c in total_nums.items(): l, r = check_stone(n) if r != -1: r_count = new_total_nums.get(r, 0) new_total_nums[r] = r_count + (1 * c) l_count = new_total_nums.get(l, 0) new_total_nums[l] = l_count + (1 * c) total_nums = new_total_nums total = sum(total_nums.values()) print(total)",python:3.9.21-slim 2024,11,2,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"from collections import defaultdict import sys sys.setrecursionlimit(2**30) with open(""./day_11.in"") as fin: raw_nums = list(map(int, fin.read().strip().split())) nums = defaultdict(int) for x in raw_nums: nums[x] += 1 def blink(nums: dict): new_nums = defaultdict(int) for x in nums: l = len(str(x)) if x == 0: new_nums[1] += nums[0] elif l % 2 == 0: new_nums[int(str(x)[:l//2])] += nums[x] new_nums[int(str(x)[l//2:])] += nums[x] else: new_nums[x * 2024] += nums[x] return new_nums for i in range(75): nums = blink(nums) ans = 0 for x in nums: ans += nums[x] print(ans)",python:3.9.21-slim 2024,11,2,"--- Day 11: Plutonian Pebbles --- The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. The strange part is that every time you blink, the stones change. Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: The first stone, 0, becomes a stone marked 1. The second stone, 1, is multiplied by 2024 to become 2024. The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. The fourth stone, 99, is split into two stones marked 9. The fifth stone, 999, is replaced by a stone marked 2021976. So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. Here is a longer example: Initial arrangement: 125 17 After 1 blink: 253000 1 7 After 2 blinks: 253 0 2024 14168 After 3 blinks: 512072 1 20 24 28676032 After 4 blinks: 512 72 2024 2 0 2 4 2867 6032 After 5 blinks: 1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 After 6 blinks: 2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? Your puzzle answer was 193607. --- Part Two --- The Historians sure are taking a long time. To be fair, the infinite corridors are very large. How many stones would you have after blinking a total of 75 times?",229557103025807,"try: with open(""11/input.txt"", ""r"") as file: data = file.read() except Exception: with open(""input.txt"", ""r"") as file: data = file.read() data = data.split("" "") class Stone: def __init__(self, n, ntimes = 1): self.n = int(n) self.ntimes = ntimes def evolve(self): if self.n == 0: self.n = 1 return [self] elif len(str(self.n)) % 2 == 0: return [Stone(str(self.n)[:len(str(self.n))//2], self.ntimes), Stone(str(self.n)[len(str(self.n))//2:], self.ntimes)] else: self.n = self.n*2024 return [self] def __str__(self): return ""{""+str(self.n)+"",""+str(self.ntimes)+""}"" stones = [] for i in data: stones.append(Stone(i)) blinks = 75 for blink in range(blinks): newstones = [] print(""Blink "", blink) #print("" "".join([x.__str__() for x in stones])) print(len(stones)) for i in range(len(stones)): for stone in stones[i].evolve(): newstones.append(stone) stones = newstones if True: i = -1 while i < len(stones)-1: i = i+1 j = i while j < len(stones)-1: j = j+1 if stones[i].n == stones[j].n: stones[i].ntimes += stones[j].ntimes del stones[j] j = j-1 print(""\n\n"", len(stones)) res = 0 for i in stones: res += i.ntimes print(res)",python:3.9.21-slim 2024,12,1,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"def visit(x, y, visited): area = 1 visited.add((x, y)) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if ((x + dx, y + dy) not in visited and 0 <= x + dx < width and 0 <= y + dy < height and garden[y][x] == garden[y + dy][x + dx]): d_area, _ = visit(x + dx, y + dy, visited) area += d_area return area, visited def perimeter(plot): min_x = min(plot, key=lambda p: p[0])[0] min_y = min(plot, key=lambda p: p[1])[1] max_x = max(plot, key=lambda p: p[0])[0] max_y = max(plot, key=lambda p: p[1])[1] perim = 0 for ray_x in range(min_x , max_x + 1): is_in = False side_count = 0 for ray_y in range(min_y, max_y + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in side_count += 1 perim += side_count for ray_y in range(min_y , max_y + 1): is_in = False side_count = 0 for ray_x in range(min_x, max_x + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in side_count += 1 perim += side_count return perim def main(): visited = set() result = 0 for y, row in enumerate(garden): for x, column in enumerate(row): if (x, y) not in visited: area, v = visit(x, y, set()) perim = perimeter(v) visited.update(v) result += area * perim print(result) with open(""12_input.txt"", ""r"") as f: garden = [line.strip() for line in f.readlines()] width = len(garden[0]) height = len(garden) if __name__ == '__main__': main()",python:3.9.21-slim 2024,12,1,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"from collections import deque inp = [] with open('day12-data.txt', 'r') as f: for line in f: inp.append(list(line.strip())) # print(inp) num_rows = len(inp) num_cols = len(inp[0]) def in_bounds(rc): r, c = rc return (0 <= r < num_rows) and (0 <= c < num_cols) def get_plant(rc): r, c = rc return inp[r][c] def get_neighbors(rc): r, c = rc neighbors = [] ds = [(-1, 0), (0, 1), (1, 0), (0, -1)] # NESW for (dr, dc) in ds: neighbors.append((r + dr, c + dc)) return [n for n in neighbors if in_bounds(n)] def get_plant_neighbors(rc): neighbors = get_neighbors(rc) return [n for n in neighbors if get_plant(n)==get_plant(rc)] # BFS def get_region(rc): visited = set() region = set() queue = deque([rc]) while queue: node = queue.popleft() if node not in visited: visited.add(node) # visit node region.add(node) # add all unvisited neighbors to the queue neighbors = get_plant_neighbors(node) unvisited_neighbors = [n for n in neighbors if n not in visited] # print(f'At node {node}, ns: {neighbors}, unvisited: {unvisited_neighbors}') queue.extend(unvisited_neighbors) return region def calc_perimeter(region): perimeter = 0 for rc in region: plant = get_plant(rc) neighbors = get_plant_neighbors(rc) # Boundary adds to perimeter perimeter += 4 - len(neighbors) return perimeter regions = [] visited = set() for r in range(num_rows): for c in range(num_cols): rc = (r, c) if rc not in visited: region = get_region(rc) visited |= region regions.append(region) # print(regions) total_price = 0 for region in regions: plant = get_plant(next(iter(region))) area = len(region) perimeter = calc_perimeter(region) price = area * perimeter total_price += price # print(f'{plant} (area: {area}, perimeter: {perimeter}): {region}') print(total_price)",python:3.9.21-slim 2024,12,1,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"input = open(""day_12\input.txt"", ""r"").read().splitlines() directions = [(1,0), (0,1), (-1, 0), (0, -1)] total = 0 def add_padding(matrix): padding_row = ['!' * (len(matrix[0]) + 2)] padded_matrix = [f""{'!'}{row}{'!'}"" for row in matrix] return padding_row + padded_matrix + padding_row def explore(char, i, j): global area, perimeter if not input[i][j] == char: perimeter += 1 return visited.add((i,j)) global_visited.add((i, j)) area += 1 for (dy, dx) in directions: if not (i + dy, j + dx) in visited: explore(char, i + dy, j + dx) input = [list(line) for line in add_padding(input)] global_visited = set() for i in range(len(input)): for j in range(len(input[i])): if not input[i][j] == ""!"" and not (i, j) in global_visited: visited = set() area = 0 perimeter = 0 explore(input[i][j], i, j) total += area * perimeter print(f""The total price of fencing all the regions is {total}"")",python:3.9.21-slim 2024,12,1,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"from collections import deque with open('input.txt') as f: data = f.read().splitlines() xmax = len(data[0]) ymax = len(data) total_seen = set() def calc_plot(x, y): plant = data[y][x] perimeter = 0 area = 0 seen = set() q = deque() q.append((x, y)) while q: xi, yi = q.popleft() if (xi, yi) in seen: continue if xi < 0 or xi >= xmax or yi < 0 or yi >= ymax or data[yi][xi] != plant: perimeter += 1 continue seen.add((xi, yi)) area += 1 q.append((xi + 1, yi)) q.append((xi - 1, yi)) q.append((xi, yi + 1)) q.append((xi, yi - 1)) total_seen.update(seen) return area * perimeter total = 0 for yi in range(ymax): for xi in range(xmax): if (xi, yi) in total_seen: continue total += calc_plot(xi, yi) print(total)",python:3.9.21-slim 2024,12,1,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map?",1377008,"from typing import List from pprint import pprint as pprint INPUT_FILE = ""input.txt"" visited = set() class Plot: def __init__(self, plant: str, area: int, perimeter: int): self.plant = plant self.area = area self.perimeter = perimeter def __repr__(self): return f""Plot({self.plant}, {self.area}, {self.perimeter})"" def __str__(self): return f""Plot({self.plant}, {self.area}, {self.perimeter})"" def readInput() -> List[List[str]]: with open(INPUT_FILE, 'r') as f: return [list(line.strip()) for line in f.readlines()] def findPlot(grid: List[List[str]], currentPlot: Plot, currentLocation: tuple[int, int]) -> Plot: plot = Plot(currentPlot.plant, currentPlot.area, currentPlot.perimeter) visited.add(currentLocation) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] for direction in directions: x = currentLocation[0] + direction[0] y = currentLocation[1] + direction[1] if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]): plot.perimeter += 1 continue if grid[x][y] != plot.plant: plot.perimeter += 1 continue if (x, y) in visited: continue plot.area += 1 plot = findPlot(grid, plot, (x, y)) return plot def getPlots(grid: List[List[str]]) -> List[Plot]: plots = [] for i in range(len(grid)): for j in range(len(grid[0])): if (i, j) in visited: continue plot = findPlot(grid, Plot(grid[i][j], 1, 0), (i, j)) plots.append(plot) return plots def calculateCosts(plots: List[Plot]) -> int: cost = 0 for plot in plots: cost += plot.area * plot.perimeter return cost def main(): grid = readInput() pprint(grid) plots = getPlots(grid) pprint(plots) print(f'Cost: {calculateCosts(plots)}') if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,12,2,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"input = open(""day_12\input.txt"", ""r"").read().splitlines() directions = [(1,0), (0,1), (-1, 0), (0, -1)] total = 0 def add_padding(matrix): padding_row = ['!' * (len(matrix[0]) + 2)] padded_matrix = [f""{'!'}{row}{'!'}"" for row in matrix] return padding_row + padded_matrix + padding_row def explore(char, i, j): global area, sides visited.add((i,j)) global_visited.add((i,j)) area += 1 for (dy,dx) in directions: if input[i + dy][j + dx] != char: sides += [((dy,dx), (i,j))] elif not (i + dy, j + dx) in visited: explore(char, i + dy, j + dx) def calculate_sides(sides): unique_sides = 0 while len(sides) > 0: current_side = sides[0] sides = explore_side(current_side, sides[0:]) unique_sides += 1 if current_side in sides: sides.remove(current_side) return unique_sides def explore_side(side, sides): if side[0] == (1, 0) or side[0] == (-1, 0): targets = [(side[0], (side[1][0], side[1][1] - 1)), (side[0], (side[1][0], side[1][1] + 1))] for target in targets: if target in sides: sides.remove(target) sides = explore_side(target, sides) elif side[0] == (0, 1) or side[0] == (0, -1): targets = [(side[0], (side[1][0] + 1, side[1][1])), (side[0], (side[1][0] - 1, side[1][1]))] for target in targets: if target in sides: sides.remove(target) sides = explore_side(target, sides) return sides input = [list(line) for line in add_padding(input)] global_visited = set() for i in range(len(input)): for j in range(len(input[i])): if input[i][j] != ""!"" and not (i, j) in global_visited: visited = set() area = 0 sides = [] explore(input[i][j], i, j) total += area * calculate_sides(sides) print(f""The total price of fencing all the regions is {total}"")",python:3.9.21-slim 2024,12,2,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"def add_to_region_from(grid, loc, region, visited): region.add(loc) visited.add(loc) neighbors = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)] neighbors = [pt for pt in neighbors if pt[0] in range(len(grid)) and pt[1] in range(len(grid))] for neighbor in neighbors: if grid[loc[0]][loc[1]] == grid[neighbor[0]][neighbor[1]] and not neighbor in visited: add_to_region_from(grid, neighbor, region, visited) def get_area(region): return len(region) def get_sides(region): sides = 0 visited_edges = set() sorted_region = sorted(list(region)) for loc in sorted_region: above = (loc[0] - 1, loc[1]) if above not in region: visited_edges.add((above, 'bottom')) if ((above[0], above[1] - 1), 'bottom') not in visited_edges and ((above[0], above[1] + 1), 'bottom') not in visited_edges: sides += 1 below = (loc[0] + 1, loc[1]) if below not in region: visited_edges.add((below, 'top')) if ((below[0], below[1] - 1), 'top') not in visited_edges and ((below[0], below[1] + 1), 'top') not in visited_edges: sides += 1 left = (loc[0], loc[1] - 1) if left not in region: visited_edges.add((left, 'right')) if ((left[0] - 1, left[1]), 'right') not in visited_edges and ((left[0] + 1, left[1]), 'right') not in visited_edges: sides += 1 right = (loc[0], loc[1] + 1) if right not in region: visited_edges.add((right, 'left')) if ((right[0] - 1, right[1]), 'left') not in visited_edges and ((right[0] + 1, right[1]), 'left') not in visited_edges: sides += 1 return sides def get_corners(region): corners = 0 for loc in region: outer_top_left = [((0, -1), False), ((-1, 0), False)] outer_top_right = [((0, 1), False), ((-1, 0), False)] outer_bottom_right = [((0, 1), False), ((1, 0), False)] outer_bottom_left = [((0, -1), False), ((1, 0), False)] inner_top_left = [((0, 1), True), ((1, 0), True), ((1, 1), False)] inner_top_right = [((0, -1), True), ((1, 0), True), ((1, -1), False)] inner_bottom_right = [((0, -1), True), ((-1, 0), True), ((-1, -1), False)] inner_bottom_left = [((0, 1), True), ((-1, 0), True), ((-1, 1), False)] all_neighbors = [outer_top_left, outer_top_right, outer_bottom_right, outer_bottom_left, inner_top_left, inner_top_right, inner_bottom_right, inner_bottom_left] corners += sum([all([((loc[0] + pt[0][0], loc[1] + pt[0][1]) in region) == pt[1] for pt in neighbor]) for neighbor in all_neighbors]) return corners def get_perimeter(region): perimeter = 0 for loc in region: neighbors = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)] perimeter += len([pt for pt in neighbors if pt not in region]) return perimeter with open('input.txt') as f: grid = [[c for c in line] for line in f.read().splitlines()] visited = set() regions = [] for i in range(len(grid)): for j in range(len(grid[i])): if not (i, j) in visited: region = set() add_to_region_from(grid, (i, j), region, visited) regions.append(region) visited.add((i, j)) total_price = 0 for region in regions: price = get_area(region) * get_corners(region) total_price += price print(total_price)",python:3.9.21-slim 2024,12,2,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"from collections import deque with open('input.txt') as f: data = f.read().splitlines() xmax = len(data[0]) ymax = len(data) total_seen = set() def count_corners(plant, x, y): up = data[y - 1][x] if y - 1 >= 0 else None down = data[y + 1][x] if y + 1 < ymax else None left = data[y][x - 1] if x - 1 >= 0 else None right = data[y][x + 1] if x + 1 < xmax else None count = sum(1 for i in (up, down, left, right) if i == plant) corners = 0 if count == 0: return 4 if count == 1: return 2 if count == 2: if left == right == plant or up == down == plant: return 0 corners += 1 if up == left == plant and (y - 1 >= 0 and x - 1 >= 0) and data[y - 1][x - 1] != plant: corners += 1 if up == right == plant and (y - 1 >= 0 and x + 1 < xmax) and data[y - 1][x + 1] != plant: corners += 1 if down == left == plant and (y + 1 < ymax and x - 1 >= 0) and data[y + 1][x - 1] != plant: corners += 1 if down == right == plant and (y + 1 < ymax and x + 1 < xmax) and data[y + 1][x + 1] != plant: corners += 1 return corners def calc_plot(x, y): plant = data[y][x] perimeter = 0 area = 0 corners = 0 seen = set() q = deque() q.append((x, y)) while q: xi, yi = q.popleft() if (xi, yi) in seen: continue if xi < 0 or xi >= xmax or yi < 0 or yi >= ymax or data[yi][xi] != plant: perimeter += 1 continue seen.add((xi, yi)) area += 1 corners += count_corners(plant, xi, yi) q.append((xi + 1, yi)) q.append((xi - 1, yi)) q.append((xi, yi + 1)) q.append((xi, yi - 1)) total_seen.update(seen) return area * corners total = 0 for yi in range(ymax): for xi in range(xmax): if (xi, yi) in total_seen: continue total += calc_plot(xi, yi) print(total)",python:3.9.21-slim 2024,12,2,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"def visit(x, y, visited): area = 1 visited.add((x, y)) for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if ((x + dx, y + dy) not in visited and 0 <= x + dx < width and 0 <= y + dy < height and garden[y][x] == garden[y + dy][x + dx]): d_area, _ = visit(x + dx, y + dy, visited) area += d_area return area, visited def perimeter(plot): min_x = min(plot, key=lambda p: p[0])[0] min_y = min(plot, key=lambda p: p[1])[1] max_x = max(plot, key=lambda p: p[0])[0] max_y = max(plot, key=lambda p: p[1])[1] # vertical rays hits = {} for ray_x in range(min_x - 1, max_x + 1): is_in = False hits[ray_x] = [] for ray_y in range(min_y - 1, max_y + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in hits[ray_x].append((ray_y, is_in)) side_count = 0 for i, hit_x in enumerate(hits): if i > 0: for (y, is_in) in hits[hit_x]: if (y, is_in) not in hits[hit_x - 1]: side_count += 1 # horizontal rays hits = {} for ray_y in range(min_y - 1, max_y + 1): is_in = False hits[ray_y] = [] for ray_x in range(min_x - 1, max_x + 2): if (not is_in and (ray_x, ray_y) in plot) or (is_in and (ray_x, ray_y) not in plot): is_in = not is_in hits[ray_y].append((ray_x, is_in)) for i, hit_y in enumerate(hits): if i > 0: for (y, is_in) in hits[hit_y]: if (y, is_in) not in hits[hit_y - 1]: side_count += 1 return side_count def main(): visited = set() result = 0 for y, row in enumerate(garden): for x, column in enumerate(row): if (x, y) not in visited: area, v = visit(x, y, set()) perim = perimeter(v) visited.update(v) result += area * perim print(result) with open(""12_input.txt"", ""r"") as f: garden = [line.strip() for line in f.readlines()] width = len(garden[0]) height = len(garden) if __name__ == '__main__': main()",python:3.9.21-slim 2024,12,2,"--- Day 12: Garden Groups --- Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: AAAA BBCD BBCC EEEC This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: +-+-+-+-+ |A A A A| +-+-+-+-+ +-+ |D| +-+-+ +-+ +-+ |B B| |C| + + + +-+ |B B| |C C| +-+-+ +-+ + |C| +-+-+-+ +-+ |E E E| +-+-+-+ Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: OOOOO OXOXO OOOOO OXOXO OOOOO The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). Here's a larger example: RRRRIICCFF RRRRIICCCF VVRRRCCFFF VVRCCCJFFF VVVVCJJCFE VVIVCCJJEE VVIIICJJEE MIIIIIJJEE MIIISIJEEE MMMISSJEEE It contains: A region of R plants with price 12 * 18 = 216. A region of I plants with price 4 * 8 = 32. A region of C plants with price 14 * 28 = 392. A region of F plants with price 10 * 18 = 180. A region of V plants with price 13 * 20 = 260. A region of J plants with price 11 * 20 = 220. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 18 = 234. A region of I plants with price 14 * 22 = 308. A region of M plants with price 5 * 12 = 60. A region of S plants with price 3 * 8 = 24. So, it has a total price of 1930. What is the total price of fencing all regions on your map? Your puzzle answer was 1377008. --- Part Two --- Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. Consider this example again: AAAA BBCD BBCC EEEC The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. The second example above (full of type X and O plants) would have a total price of 436. Here's a map that includes an E-shaped region full of type E plants: EEEEE EXXXX EEEEE EXXXX EEEEE The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. This map has a total price of 368: AAAAAA AAABBA AAABBA ABBAAA ABBAAA AAAAAA It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the M������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������bius Fencing Company instead, but their contract terms were too one-sided.) The larger example from before now has the following updated prices: A region of R plants with price 12 * 10 = 120. A region of I plants with price 4 * 4 = 16. A region of C plants with price 14 * 22 = 308. A region of F plants with price 10 * 12 = 120. A region of V plants with price 13 * 10 = 130. A region of J plants with price 11 * 12 = 132. A region of C plants with price 1 * 4 = 4. A region of E plants with price 13 * 8 = 104. A region of I plants with price 14 * 16 = 224. A region of M plants with price 5 * 6 = 30. A region of S plants with price 3 * 6 = 18. Adding these together produces its new total price of 1206. What is the new total price of fencing all regions on your map?",815788,"from collections import deque def get_total_cost(farm): n = len(farm) m = len(farm[0]) def in_bounds(r, c): return (0 <= r < n) and (0 <= c < m) def get_val(r, c): return farm[r][c] def get_neighbours(r, c): neighbours = [] dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)] for (dr, dc) in dirs: neighbours.append((r + dr, c + dc)) return [neighbour for neighbour in neighbours if in_bounds(neighbour[0], neighbour[1])] def get_val_neighbours(r, c): neighbours = get_neighbours(r, c) return [neighbour for neighbour in neighbours if get_val(neighbour[0], neighbour[1]) == get_val(r, c)] def get_region(r, c): visited = set() region = set() queue = deque([(r, c)]) while queue: node = queue.popleft() if node not in visited: visited.add(node) region.add(node) neighbours = get_val_neighbours(node[0], node[1]) neighbours = [neighbour for neighbour in neighbours if neighbour not in visited] queue.extend(neighbours) return region def calc_edges(region): edges = 0 for (r, c) in region: if ((r - 1, c) not in region): if not (((r, c - 1) in region) and ((r - 1, c - 1) not in region)): edges += 1 if ((r + 1, c) not in region): if not (((r, c - 1) in region) and ((r + 1, c - 1) not in region)): edges += 1 if ((r, c - 1) not in region): if not (((r - 1, c) in region) and ((r - 1, c - 1) not in region)): edges += 1 if ((r, c + 1) not in region): if not (((r - 1, c) in region) and ((r - 1, c + 1) not in region)): edges += 1 return edges regions = [] visited = set() for i in range(n): for j in range(m): if (i, j) not in visited: region = get_region(i, j) visited |= region regions.append(region) cost = 0 for region in regions: nextRegion = next(iter(region)) val = get_val(nextRegion[0], nextRegion[1]) area = len(region) edges = calc_edges(region) price = area * edges cost += price return cost if __name__ == ""__main__"": # Open file 'day12-2.txt' in read mode with open('day12-2.txt', 'r') as f: farm = [] for line in f: farm.append(line.strip()) print(""Total fencing cost: "" + str(get_total_cost(farm)))",python:3.9.21-slim 2024,13,1,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() total = 0 for problem in range((len(input_text) + 1) // 4): button_a_move_x, button_a_move_y = ( input_text[problem * 4].removeprefix(""Button A: "").split("", "") ) button_a_move = ( int(button_a_move_x.removeprefix(""X+"")), int(button_a_move_y.removeprefix(""Y+"")), ) button_b_move_x, button_b_move_y = ( input_text[problem * 4 + 1].removeprefix(""Button B: "").split("", "") ) button_b_move = ( int(button_b_move_x.removeprefix(""X+"")), int(button_b_move_y.removeprefix(""Y+"")), ) target_x, target_y = input_text[problem * 4 + 2].removeprefix(""Prize: "").split("", "") target = (int(target_x.removeprefix(""X="")), int(target_y.removeprefix(""Y=""))) min_cost = float(""inf"") for a_presses in range(101): for b_presses in range(101): if ( a_presses * button_a_move[0] + b_presses * button_b_move[0], a_presses * button_a_move[1] + b_presses * button_b_move[1], ) == target: min_cost = min(min_cost, a_presses * 3 + b_presses) if min_cost < float(""inf""): total += min_cost print(total)",python:3.9.21-slim 2024,13,1,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"import re with open(""./day_13.in"") as fin: lines = fin.read().strip().split(""\n\n"") def parse(x): lines = x.split(""\n"") a = list(map(int, re.findall(r""Button A: X\+(\d+), Y\+(\d+)"", lines[0])[0])) b = list(map(int, re.findall(r""Button B: X\+(\d+), Y\+(\d+)"", lines[1])[0])) p = list(map(int, re.findall(r""Prize: X=(\d+), Y=(\d+)"", lines[2])[0])) return a, b, p prices = [] for a, b, p in [parse(line) for line in lines]: def test(i, j): x = a[0] * i + b[0] * j y = a[1] * i + b[1] * j return (x, y) == tuple(p) va = 1<<30 for i in range(100): for j in range(100): if test(i, j): va = min(va, 3*i + j) if va < 1<<30: prices.append(va) spent = 0 print(sum(prices))",python:3.9.21-slim 2024,13,1,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"from typing import List from pprint import pprint as pprint from functools import cache INPUT_FILE = ""input.txt"" MAX_PRIZE = 401 class Button: def __init__(self, price: int, d_x: int, d_y: int): self.price = price self.d_x = d_x self.d_y = d_y def __repr__(self): return f""Button({self.price}, {self.d_x}, {self.d_y})"" def __str__(self): return f""Button({self.price}, {self.d_x}, {self.d_y})"" class Prize: def __init__(self, x: int, y: int): self.x = x self.y = y def __repr__(self): return f""Price({self.x}, {self.y})"" def __str__(self): return f""Price({self.x}, {self.y})"" def readInput() -> List[str]: with open(INPUT_FILE, 'r') as f: return f.read().split('\n\n') def parseInput(data: str) -> tuple[Prize, tuple[Button, Button]]: a, b, prize = data.splitlines() button_a = Button(3, int(a.split(""X+"")[1].split("","")[0]), int(a.split(""Y+"")[1])) button_b = Button(1, int(b.split(""X+"")[1].split("","")[0]), int(b.split(""Y+"")[1])) prize = Prize(int(prize.split(""X="")[1].split("","")[0]), int(prize.split(""Y="")[1])) return (prize, (button_a, button_b)) @cache def getCost(prize: Prize, buttons: tuple[Button, Button]) -> int: # lowest_cost = MAX_PRIZE for a in range(100): for b in range(100): if prize.x == buttons[0].d_x*a+buttons[1].d_x*b and prize.y == buttons[0].d_y*a+buttons[1].d_y*b: return a * buttons[0].price + b * buttons[1].price return 0 def costs(machines: List[tuple[Prize, tuple[Button, Button]]]) -> List[int]: costs = [] for machine in machines: costs.append(getCost(machine[0], machine[1])) return costs def main(): data = readInput() # pprint(data) machines = [parseInput(line) for line in data] # pprint(machines) costs_list = costs(machines) # pprint(costs_list) print(f""Result: {sum(costs_list)}"") if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,13,1,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"f = open(""input.txt"") machines = [elem.split(""\n"") for elem in f.read().split(""\n\n"")] def find_solution(A_button, B_button, prize): X_a, Y_a = A_button X_b, Y_b = B_button X_prize, Y_prize = prize b = (X_prize * Y_a - Y_prize * X_a) / (X_b * Y_a - X_a * Y_b) a = (X_prize * Y_b - Y_prize * X_b) / (X_a * Y_b - X_b * Y_a) if (int(a) == a and a <= 100 and int(b) == b and b <= 100): return (a,b) return () def get_cost(solution): return solution[0]*3 + solution[1] total = 0 for machine in machines: A_button = tuple([int(text[3:]) for text in machine[0].split("":"")[1].split("","")]) B_button = tuple([int(text[3:]) for text in machine[1].split("":"")[1].split("","")]) prize = tuple([int(text[3:]) for text in machine[2].split("":"")[1].split("","")]) solution = find_solution(A_button, B_button, prize) if solution != (): cost = get_cost(solution) total += cost print(total)",python:3.9.21-slim 2024,13,1,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",34787,"import os def reader(): return open(f""input.txt"", 'r').read().splitlines() def part1(): f = list(map(lambda s: s.split('\n'), '\n'.join(reader()).split('\n\n'))) M = [] for l in f: Ax = int(l[0][(l[0].find('X+') + 2):l[0].find(',')]) Ay = int(l[0][(l[0].find('Y+') + 2):]) Bx = int(l[1][(l[1].find('X+') + 2):l[1].find(',')]) By = int(l[1][(l[1].find('Y+') + 2):]) X = int(l[2][(l[2].find('X=') + 2):l[2].find(',')]) Y = int(l[2][(l[2].find('Y=') + 2):]) M.append([(Ax, Ay), (Bx, By), (X, Y)]) t = 0 for m in M: l = -1, 0 for i in range(101): for j in range(101): cost = 3 * i + j pos = i * m[0][0] + j * m[1][0], i * m[0][1] + j * m[1][1] if pos == m[2]: l = (0, cost) if l[0] == -1 else (0, min(l[1], cost)) if l[0] == 0: t += l[1] print(t) part1()",python:3.9.21-slim 2024,13,2,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"def get_cheapest(machine): A = machine[0] B = machine[1] prize = (machine[2][0] + 10000000000000, machine[2][1] + 10000000000000) af = (A[1] / A[0]) bf = (B[1] / B[0]) xIntersection = round((prize[0] * af - prize[1]) / (af - bf)) if xIntersection % B[0] != 0: return 0 b = xIntersection // B[0] rem = ((prize[0] - B[0] * b), (prize[1] - B[1] * b)) if rem[0] % A[0] != 0: return 0 a = rem[0] // A[0] if ((B[0] * b) + (A[0] * a) == prize[0] and (B[1] * b) + (A[1] * a)) == prize[1]: return b + (a * 3) return 0 def get_fewest_tokens(machines): tokens = 0 for machine in machines: tokens += get_cheapest(machine) return tokens if __name__ == ""__main__"": # Open file 'day13-2.txt' in read mode with open('day13-2.txt', 'r') as f: machines = [] A = (0, 0) B = (0, 0) prize = (0, 0) for i, line in enumerate(f): line = line.strip() if i % 4 == 0: A = (int(line[line.find('+') + 1: line.find(',')]), int(line[line.find(',') + 4:])) elif i % 4 == 1: B = (int(line[line.find('+') + 1: line.find(',')]), int(line[line.find(',') + 4:])) elif i % 4 == 2: prize = (int(line[line.find('=') + 1: line.find(',')]), int(line[line.find(',') + 4:])) machines.append([ A, B, prize ]) else: A = (0, 0) B = (0, 0) prize = (0, 0) print(""Fewest number of tokens: "" + str(get_fewest_tokens(machines)))",python:3.9.21-slim 2024,13,2,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"f = open(""input.txt"") machines = [elem.split(""\n"") for elem in f.read().split(""\n\n"")] def find_solution(A_button, B_button, prize): X_a, Y_a = A_button X_b, Y_b = B_button X_prize, Y_prize = prize X_prize += 10000000000000 Y_prize += 10000000000000 b = (X_prize * Y_a - Y_prize * X_a) / (X_b * Y_a - X_a * Y_b) a = (X_prize * Y_b - Y_prize * X_b) / (X_a * Y_b - X_b * Y_a) if (int(a) == a and int(b) == b): return (a,b) return () def get_cost(solution): return solution[0]*3 + solution[1] total = 0 for machine in machines: A_button = tuple([int(text[3:]) for text in machine[0].split("":"")[1].split("","")]) B_button = tuple([int(text[3:]) for text in machine[1].split("":"")[1].split("","")]) prize = tuple([int(text[3:]) for text in machine[2].split("":"")[1].split("","")]) solution = find_solution(A_button, B_button, prize) if solution != (): cost = get_cost(solution) total += cost print(total)",python:3.9.21-slim 2024,13,2,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"import re from typing import Tuple, List def parse_input(file_path: str) -> List[Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]]: """""" Parses the input file to extract button and prize coordinates. The input file should contain lines formatted as: ""Button A: X+, Y+ Button B: X+, Y+ Prize: X=, Y="" Args: file_path (str): The path to the input file. Returns: List[Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]]: A list of tuples, each containing: - A tuple representing the coordinates of Button A (X, Y). - A tuple representing the coordinates of Button B (X, Y). - A tuple representing the coordinates of the Prize (X, Y) with 10000000000000 added to each coordinate. """""" pattern = re.compile(r""Button A: X\+(\d+), Y\+(\d+)\s+Button B: X\+(\d+), Y\+(\d+)\s+Prize: X=(\d+), Y=(\d+)"") results = [] with open(file_path, 'r') as file: content = file.read() matches = pattern.findall(content) for match in matches: button_a = (int(match[0]), int(match[1])) button_b = (int(match[2]), int(match[3])) prize = (int(match[4]) + 10000000000000, int(match[5]) + 10000000000000) results.append((button_a, button_b, prize)) return results def solve(scenario: Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]) -> int: """""" Solves the given scenario by finding integers a and b such that the linear combination of the vectors (ax, ay) and (bx, by) equals the target vector (tx, ty). Args: scenario (Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int]]): A tuple containing three tuples, each representing a vector in the form (x, y). The first two tuples are the vectors (ax, ay) and (bx, by), and the third tuple is the target vector (tx, ty). Returns: int: The result of the expression 3 * a + b if the linear combination is valid, otherwise 0. """""" (ax, ay), (bx, by), (tx, ty) = scenario b = (tx * ay - ty * ax) // (ay * bx - by * ax) a = (tx * by - ty * bx) // (by * ax - bx * ay) if ax * a + bx * b == tx and ay * a + by * b == ty: return 3 * a + b else: return 0 if __name__ == ""__main__"": file_path = 'input.txt' parsed_data = parse_input(file_path) results = [solve(scenario) for scenario in parsed_data] print(sum(results))",python:3.9.21-slim 2024,13,2,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"import re def min_cost_for_prize(prize, a, b): prize_x = prize[0] prize_y = prize[1] a_x = a[0] a_y = a[1] b_x = b[0] b_y = b[1] if (prize_x * b_y - b_x * prize_y) % (a_x * b_y - b_x * a_y) != 0: return (False, -1) a_val = (prize_x * b_y - b_x * prize_y) // (a_x * b_y - b_x * a_y) if (prize_x - a_x * a_val) % b_x != 0: return (False, -1) b_val = (prize_x - a_x * a_val) // b_x return (True, 3 * a_val + b_val) with open('input.txt') as f: claw_strs = f.read().split(""\n\n"") claw_data = [] for claw_input in claw_strs: lines = claw_input.splitlines() claw = dict() claw['A'] = tuple(map(int, re.match(""Button A: X\\+(\\d+), Y\\+(\\d+)"", lines[0]).groups())) claw['B'] = tuple(map(int, re.match(""Button B: X\\+(\\d+), Y\\+(\\d+)"", lines[1]).groups())) claw['Prize'] = tuple(map(lambda n: n + 10000000000000, map(int, re.match(""Prize: X=(\\d+), Y=(\\d+)"", lines[2]).groups()))) claw_data.append(claw) total_cost = 0 for claw in claw_data: res = min_cost_for_prize(claw['Prize'], claw['A'], claw['B']) if res[0]: total_cost += res[1] print(total_cost)",python:3.9.21-slim 2024,13,2,"--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 34787. --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?",85644161121698,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() total = 0 for problem in range((len(input_text) + 1) // 4): button_a_move_x, button_a_move_y = ( input_text[problem * 4].removeprefix(""Button A: "").split("", "") ) button_a_move = ( int(button_a_move_x.removeprefix(""X+"")), int(button_a_move_y.removeprefix(""Y+"")), ) button_b_move_x, button_b_move_y = ( input_text[problem * 4 + 1].removeprefix(""Button B: "").split("", "") ) button_b_move = ( int(button_b_move_x.removeprefix(""X+"")), int(button_b_move_y.removeprefix(""Y+"")), ) target_x, target_y = input_text[problem * 4 + 2].removeprefix(""Prize: "").split("", "") target = ( int(target_x.removeprefix(""X="")) + 10000000000000, int(target_y.removeprefix(""Y="")) + 10000000000000, ) sol_a, sol_b = ( (button_b_move[1] * target[0] - button_b_move[0] * target[1]) // (button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0]), (-button_a_move[1] * target[0] + button_a_move[0] * target[1]) // (button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0]), ) if ( ( (button_b_move[1] * target[0] - button_b_move[0] * target[1]) % ( button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0] ) ) == 0 and ( (-button_a_move[1] * target[0] + button_a_move[0] * target[1]) % ( button_a_move[0] * button_b_move[1] - button_a_move[1] * button_b_move[0] ) ) == 0 and sol_a > 0 and sol_b > 0 ): total += 3 * sol_a + sol_b print(total)",python:3.9.21-slim 2024,14,1,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"import re def read_input(): robots = [] with open(""./input.txt"") as f: while True: line = f.readline() if not line: break numbers = re.findall(r""-?\d+"", line) robots.append([int(s) for s in numbers]) return robots def move_robot_n_step(robot, width, height, n): x0 = robot[0] y0 = robot[1] vx = robot[2] vy = robot[3] for i in range(n): x0 = (x0 + vx) % width y0 = (y0 + vy) % height return x0, y0 def move_robot_one_step(robot, width, height): x0 = robot[0] y0 = robot[1] vx = robot[2] vy = robot[3] robot[0] = (x0 + vx) % width robot[1] = (y0 + vy) % height def get_quadrant(x, y, width, height): cx = width // 2 cy = height // 2 if x < cx and y < cy: return 4 elif x < cx and y > cy: return 3 elif x > cx and y < cy: return 1 elif x > cx and y > cy: return 2 else: return -1 def solve_part1(robots, width, height): q = {1:0, 2:0, 3:0, 4:0, -1:0} for robot in robots: x,y = move_robot_n_step(robot, width, height, 100) iq = get_quadrant(x, y, width, height) q[iq] += 1 print(f""q1: {q[1]}, q2: {q[2]}, q3: {q[3]}, q4: {q[4]}"") return q[1] * q[2] * q[3] * q[4] def solve_part2(robots, width, height): best_iter = None min_safe = float('inf') for i in range(width * height): q = {1:0, 2:0, 3:0, 4:0, -1:0} for robot in robots: x,y = move_robot_n_step(robot, width, height, 1) robot[0] = x robot[1] = y iq = get_quadrant(x, y, width, height) q[iq] += 1 safe = q[1] * q[2] * q[3] * q[4] if safe < min_safe: min_safe = safe best_iter = i if i == 99: print(""At 100 sec, "", safe) print(f""best iter {best_iter}, min safe {min_safe}"") if __name__ == ""__main__"": robots = read_input() width = 101 height = 103 multiply = solve_part1(robots, width, height) print(f""Part 1: the product is {multiply}"") solve_part2(robots, width, height)",python:3.9.21-slim 2024,14,1,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"from collections import Counter import re width = 101 #11 half_width = width // 2 height = 103 #7 half_height = height // 2 class Robot: def __init__(self, px, py, vx, vy) -> None: self.px = px self.py = py self.vx = vx self.vy = vy self.q = None def move(self, seconds): self.px = (self.px + self.vx * seconds) % width self.py = (self.py + self.vy * seconds) % height self.q = self.quadrant() def quadrant(self): quadrants = { (True, True): 1, (True, False): 3, (False, True): 2, (False, False): 4, } return quadrants[(self.px < half_width, self.py < half_height)] if self.px != half_width and self.py != half_height else None with open('input.txt') as f: robots = [Robot(*map(int, re.findall(r'(-?\d+)', line))) for line in f] def print_grid(robots: list[Robot]): grid = [list('.' * width) for _ in range(height)] for robot in robots: val = grid[robot.py][robot.px] grid[robot.py][robot.px] = '1' if val == '.' else str(int(val) + 1) print('\n'.join(''.join(row) for row in grid)) quadrants = [] for robot in robots: robot.move(100) quadrants.append(robot.q) counter = Counter(quadrants) counter.pop(None) print(counter[1] * counter[2] * counter[3] * counter[4])",python:3.9.21-slim 2024,14,1,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"#!/usr/bin/python3 class Robot: def __init__(self, position, velocity): self.position = position self.velocity = velocity def teleport(self, pos:int, dim:int): """"""Move to opposite side rather than out of the space."""""" return pos - dim if pos >= dim else dim - abs(pos) if pos < 0 else pos def move_robot(self, width:int, height:int): """"""Move robot according to its velocity."""""" self.position = [self.position[0] + self.velocity[0], self.position[1] + self.velocity[1]] if self.position[0] not in range(width): self.position[0] = self.teleport(self.position[0], width) if self.position[1] not in range(height): self.position[1] = self.teleport(self.position[1], height) # Get initial position and velocity for each robot. with open(""input.txt"") as file: robots = {} for l, line in enumerate(file): robot_name = ""robot_"" + str(l+1) pos = line.split()[0].strip(""p="").split("","") vel = line.split()[1].strip(""v="").split("","") robots[robot_name] = Robot([int(pos[0]),int(pos[1])], [int(vel[0]),int(vel[1])]) # Move robots for 100 seconds in a space 101 tiles wide and 103 tiles tall. for robot in robots: for sec in range(100): robots[robot].move_robot(101, 103) # Determine the safety factor. quadrant_1 = [robots[robot].position for robot in robots if robots[robot].position[0] < 50 and robots[robot].position[1] < 51] quadrant_2 = [robots[robot].position for robot in robots if robots[robot].position[0] > 50 and robots[robot].position[1] < 51] quadrant_3 = [robots[robot].position for robot in robots if robots[robot].position[0] < 50 and robots[robot].position[1] > 51] quadrant_4 = [robots[robot].position for robot in robots if robots[robot].position[0] > 50 and robots[robot].position[1] > 51] print(""Safety factor after 100 seconds:"", len(quadrant_1) * len(quadrant_2) * len(quadrant_3) * len(quadrant_4))",python:3.9.21-slim 2024,14,1,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"from typing import List EXAMPLE: bool = False WIDTH: int = 11 if EXAMPLE else 101 HEIGHT: int = 7 if EXAMPLE else 103 INPUT_FILE: str = ""e_input.txt"" if EXAMPLE else ""input.txt"" class Robot: def __init__(self, x: int, y: int, v_x: int, v_y: int): self.x = x self.y = y self.v_x = v_x self.v_y = v_y def move(self): self.x += self.v_x self.y += self.v_y if self.x < 0: self.x = WIDTH + self.x if self.y < 0: self.y = HEIGHT + self.y if self.x >= WIDTH: self.x -= WIDTH if self.y >= HEIGHT: self.y -= HEIGHT def __str__(self): return f""Robot: x={self.x}, y={self.y}, v_x={self.v_x}, v_y={self.v_y}"" def __repr__(self): return self.__str__() def read_input() -> List[str]: with open(INPUT_FILE, ""r"") as f: return f.read().splitlines() def parse_input(input: List[str]) -> List[Robot]: robots: List[Robot] = [] for line in input: line = line.split("" "") pos = line[0][2:].split("","") x, y = int(pos[0]), int(pos[1]) velo = line[1][2:].split("","") v_x, v_y = int(velo[0]), int(velo[1]) robots.append(Robot(x, y, v_x, v_y)) return robots def predict(robots: List[Robot], seconds: int) -> List[Robot]: for i in range(seconds): for robot in robots: robot.move() return robots def print_grid(robots: List[Robot]): for y in range(HEIGHT): for x in range(WIDTH): r = 0 for robot in robots: if robot.x == x and robot.y == y: r += 1 if r == 0: print(""."", end="""") else: print(str(r), end="""") print() def safety_score(robots: List[Robot]) -> int: quadrant_one = 0 quadrant_two = 0 quadrant_three = 0 quadrant_four = 0 for robot in robots : if robot.x < WIDTH // 2 and robot.y < HEIGHT // 2: quadrant_one += 1 elif robot.x > WIDTH // 2 and robot.y < HEIGHT // 2: quadrant_two += 1 elif robot.x < WIDTH // 2 and robot.y > HEIGHT // 2: quadrant_three += 1 elif robot.x > WIDTH // 2 and robot.y > HEIGHT // 2: quadrant_four += 1 return quadrant_one * quadrant_two * quadrant_three * quadrant_four def main(): robots = parse_input(read_input()) robots = predict(robots, 100) print(safety_score(robots)) if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,14,1,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?",219150360,"import re from functools import reduce from operator import mul result = 0 width = 101 height = 103 duration = 100 robots = [] with open(""14_input.txt"", ""r"") as f: for line in f: px, py, vx, vy = map(int, re.findall(r""(-?\d+)"", line)) for sec in range(duration): px = (px + vx) % width py = (py + vy) % height robots.append((px, py)) q_width = width // 2 q_height = height // 2 quadrants = {0: 0, 1: 0, 2: 0, 3: 0} for robot in robots: if robot[0] < q_width: if robot[1] < q_height: quadrants[0] += 1 elif robot[1] > q_height: quadrants[1] += 1 elif robot[0] > q_width: if robot[1] < q_height: quadrants[2] += 1 elif robot[1] > q_height: quadrants[3] += 1 print(reduce(mul, quadrants.values()))",python:3.9.21-slim 2024,14,2,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"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:3.9.21-slim 2024,14,2,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"from collections import defaultdict from statistics import stdev with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() num_x = 101 num_y = 103 initial_positions = [] velocities = [] for line in input_text: p_sec, v_sec = line.split() initial_positions.append([int(i) for i in p_sec.split(""="")[1].split("","")]) velocities.append([int(i) for i in v_sec.split(""="")[1].split("","")]) for counter in range(10000): block_counts = defaultdict(int) new_initial_positions = [] for initial_pos, velocity in zip(initial_positions, velocities): new_position = [ (initial_pos[0] + velocity[0]) % num_x, (initial_pos[1] + velocity[1]) % num_y, ] new_initial_positions.append(new_position) block_counts[(new_position[0] // 5, new_position[1] // 5)] += 1 if stdev(block_counts.values()) > 3: print(counter + 1) initial_positions = new_initial_positions",python:3.9.21-slim 2024,14,2,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import re; 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:3.9.21-slim 2024,14,2,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"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:3.9.21-slim 2024,14,2,"--- Day 14: Restroom Redoubt --- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters. Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines. You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: p=0,4 v=3,-3 p=6,3 v=-1,-3 p=10,3 v=-1,2 p=2,0 v=2,-1 p=0,0 v=1,3 p=3,0 v=-2,-2 p=7,6 v=-1,-3 p=3,0 v=-1,-2 p=9,3 v=2,3 p=7,3 v=-1,2 p=2,4 v=2,-3 p=9,5 v=-3,-3 Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner. Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up. The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall. The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this: 1.12....... ........... ........... ......11.11 1.1........ .........1. .......1... These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds: Initial state: ........... ........... ........... ........... ..1........ ........... ........... After 1 second: ........... ....1...... ........... ........... ........... ........... ........... After 2 seconds: ........... ........... ........... ........... ........... ......1.... ........... After 3 seconds: ........... ........... ........1.. ........... ........... ........... ........... After 4 seconds: ........... ........... ........... ........... ........... ........... ..........1 After 5 seconds: ........... ........... ........... .1......... ........... ........... ........... The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds? In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: ......2..1. ........... 1.......... .11........ .....1..... ...12...... .1....1.... To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are: ..... 2..1. ..... ..... 1.... ..... ..... ..... ...12 ..... .1... 1.... In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed? Your puzzle answer was 219150360. --- Part Two --- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree. What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import 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:3.9.21-slim 2024,15,1,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"def get_next(pos, move): move_dict = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} return tuple(map(sum, zip(pos, move_dict[move]))) grid = [] moves = [] with open('input.txt') as f: for line in f.read().splitlines(): if line.startswith(""#""): grid += [[c for c in line]] elif not line == """": moves += [c for c in line] for i in range(len(grid)): for j in range(len(grid)): if grid[i][j] == '@': robot_pos = (i, j) break for move in moves: next_i, next_j = get_next(robot_pos, move) if grid[next_i][next_j] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) elif grid[next_i][next_j] == 'O': available = get_next((next_i, next_j), move) while grid[available[0]][available[1]] == 'O': available = get_next(available, move) if grid[available[0]][available[1]] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' grid[available[0]][available[1]] = 'O' robot_pos = (next_i, next_j) total = 0 for i in range(len(grid)): for j in range(len(grid)): if grid[i][j] == 'O': total += 100 * i + j print(total)",python:3.9.21-slim 2024,15,1,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"pos = (0, 0) collision = {} directions = { '<': (-1, 0), '>': (1, 0), '^': (0, -1), 'v': (0, 1), } commands = [] def check_spot(position, directon): if (item := collision.get(position)) is None: return True if item == 'Wall': return False return item.can_move(directon) def can_move(position, direction): x, y = position dir = directions[direction] new_pos = (x + dir[0], y + dir[1]) return check_spot(new_pos, direction) def move(position, direction): dir = directions[direction] return (position[0] + dir[0], position[1] + dir[1]) class Box: def __init__(self, x, y): self.x = x self.y = y @property def position(self): return (self.x, self.y) def can_move(self, direction): x, y = self.position dir = directions[direction] new_pos = (x + dir[0], y + dir[1]) return check_spot(new_pos, direction) def move(self, direction): dir = directions[direction] collision[self.position] = None self.x += dir[0] self.y += dir[1] box = collision.get(self.position) if isinstance(box, Box): box.move(direction) collision[self.position] = self @property def score(self): return self.x + (self.y * 100) with open('input.txt') as f: has_read = False for yi, line in enumerate(f): if not has_read: for xi, c in enumerate(line): if len(line.strip()) == 0: has_read = True continue if not has_read: if c == '#': collision[(xi, yi)] = ""Wall"" elif c == '@': pos = (xi, yi) elif c == 'O': box = Box(xi, yi) collision[(xi, yi)] = box else: commands.append(line.strip()) commands = ''.join(commands) def print_grid(): mx, my = max(collision.keys()) grid = [['.'] * (mx + 1) for _ in range(my + 1)] for k, v in collision.items(): if v is None: continue x, y = k if v == 'Wall': grid[y][x] = '#' elif isinstance(v, Box): bx, by = v.position grid[by][bx] = 'O' grid[pos[1]][pos[0]] = '@' print('\n'.join(''.join(x) for x in grid)) for direction in commands: if can_move(pos, direction): pos = move(pos, direction) if isinstance(collision.get(pos), Box): collision[pos].move(direction) print_grid() boxes = set(collision[x] for x in collision if isinstance(collision[x], Box)) print(sum(x.score for x in boxes))",python:3.9.21-slim 2024,15,1,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"import re from typing import List, Tuple def parse_input(file_path: str) -> Tuple[List[List[str]], List[str]]: with open(file_path, 'r') as file: content = file.read().strip() grid_part, instructions_part = content.split('\n\n') grid = [list(line) for line in grid_part.split('\n')] instructions = list(''.join(instructions_part.split('\n'))) return grid, instructions def find_robot_position(grid: List[List[str]]) -> Tuple[int, int]: for y, row in enumerate(grid): for x, cell in enumerate(row): if cell == '@': return x, y return -1, -1 def move_robot(grid: List[List[str]], instructions: List[str]) -> List[List[str]]: direction_map = { '^': (0, -1), 'v': (0, 1), '<': (-1, 0), '>': (1, 0) } x, y = find_robot_position(grid) for instruction in instructions: dx, dy = direction_map[instruction] new_x, new_y = x + dx, y + dy if not (0 <= new_x < len(grid[0]) and 0 <= new_y < len(grid)): continue if grid[new_y][new_x] == '#': continue elif grid[new_y][new_x] == 'O': # Check if we can push the box box_x, box_y = new_x, new_y while 0 <= box_x + dx < len(grid[0]) and 0 <= box_y + dy < len(grid) and grid[box_y][box_x] == 'O': box_x += dx box_y += dy if not (0 <= box_x + dx < len(grid[0]) and 0 <= box_y + dy < len(grid)) or grid[box_y][box_x] == '#': break else: # Move the robot and push the boxes while (box_x, box_y) != (new_x, new_y): box_x -= dx box_y -= dy grid[box_y + dy][box_x + dx] = 'O' grid[new_y][new_x] = '@' grid[y][x] = '.' x, y = new_x, new_y else: grid[new_y][new_x] = '@' grid[y][x] = '.' x, y = new_x, new_y return grid def calculate_gps_sum(grid: List[List[str]]) -> int: gps_sum = 0 for y, row in enumerate(grid): for x, cell in enumerate(row): if cell == 'O': gps_sum += 100 * y + x return gps_sum if __name__ == ""__main__"": file_path = 'input.txt' grid, instructions = parse_input(file_path) print(""Initial Grid:"") for row in grid: print(''.join(row)) grid = move_robot(grid, instructions) print(""\nFinal Grid:"") for row in grid: print(''.join(row)) gps_sum = calculate_gps_sum(grid) print(f""\nSum of all boxes' GPS coordinates: {gps_sum}"")",python:3.9.21-slim 2024,15,1,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"input = open(""day_15\input.txt"", ""r"").read().splitlines() warehouse_map = [] movements = """" cur_pos = (0,0) total = 0 movement_dict = { ""v"": (1, 0), ""^"": (-1, 0), "">"": (0, 1), ""<"": (0, -1) } def find_open_spot(pos, move): while True: pos = tuple(map(sum, zip(pos, move))) pos_value = warehouse_map[pos[0]][pos[1]] if pos_value == ""#"": return False elif pos_value == ""."": return pos i = 0 while input[i] != """": if ""@"" in input[i]: cur_pos = (i, input[i].index(""@"")) warehouse_map.append(list(input[i])) i += 1 i += 1 while i < len(input): movements += input[i] i += 1 for move in movements: destination = tuple(map(sum, zip(cur_pos, movement_dict[move]))) destination_value = warehouse_map[destination[0]][destination[1]] if destination_value == ""O"": open_spot = find_open_spot(destination, movement_dict[move]) if open_spot: warehouse_map[open_spot[0]][open_spot[1]] = ""O"" warehouse_map[destination[0]][destination[1]] = ""@"" warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" cur_pos = destination elif destination_value == ""."": warehouse_map[destination[0]][destination[1]] = ""@"" warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" cur_pos = destination for i in range(len(warehouse_map)): for j in range(len(warehouse_map[i])): if warehouse_map[i][j] == ""O"": total += 100 * i + j print(f""The sum of all boxes' GPS coordinates is {total}"")",python:3.9.21-slim 2024,15,1,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"from collections import deque def find_start(grid, n, m): for i in range(n): for j in range(m): if grid[i][j] == '@': return (i, j) return (0, 0) def in_bounds(i, j, n, m): return (0 <= i < n) and (0 <= j < m) def move(grid, loc, dir, n, m): curr = (loc[0], loc[1]) addStack = deque() addStack.append('@') while True: newPos = (curr[0] + dir[0], curr[1] + dir[1]) if in_bounds(newPos[0], newPos[1], n, m): val = grid[newPos[0]][newPos[1]] if val == '#': return loc elif val == 'O': addStack.append('O') elif val == '.': revDir = (-dir[0], -dir[1]) while addStack: movedVal = addStack.pop() grid[newPos[0]] = grid[newPos[0]][:newPos[1]] + movedVal + grid[newPos[0]][newPos[1] + 1:] newPos = (newPos[0] + revDir[0], newPos[1] + revDir[1]) grid[loc[0]] = grid[loc[0]][:loc[1]] + '.' + grid[loc[0]][loc[1] + 1:] return (loc[0] + dir[0], loc[1] + dir[1]) else: return loc curr = (newPos[0], newPos[1]) def get_box_coords(grid, instructions): n = len(grid) m = len(grid[0]) loc = find_start(grid, n, m) dirMap = {'^': (-1, 0), '>': (0, 1), 'v': (1, 0), '<': (0, -1)} for instruction in instructions: loc = move(grid, loc, dirMap.get(instruction), n, m) total = 0 for i in range(n): for j in range(m): if grid[i][j] == 'O': total += ((100 * i) + j) return total if __name__ == ""__main__"": # Open file 'day15-1.txt' in read mode with open('day15-1.txt', 'r') as f: grid = [] ended = False instructions = [] for line in f: if line == '\n': ended = True line = line.strip() if not ended: grid.append(line) else: instructions.extend(list(line)) print(""Final Coordinates of Boxes: "" + str(get_box_coords(grid, instructions)))",python:3.9.21-slim 2024,15,2,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### bool: return 0 <= y < len(self.grid) and 0 <= x < len(self.grid[y]) def is_wall(self, x: int, y: int) -> bool: return self.is_valid(x, y) and self.grid[y][x] == ""#"" def is_box(self, x: int, y: int) -> bool: if self.is_valid(x, y): if self.grid[y][x] == ""O"": return True if self.grid[y][x] == ""["" or self.grid[y][x] == ""]"": return True return False def is_empty(self, x: int, y: int) -> bool: return self.is_valid(x, y) and self.grid[y][x] == ""."" def get_robot_pos(self) -> tuple[int, int]: if self.robot_pos != None: return self.robot_pos for y in range(len(self.grid)): for x in range(len(self.grid[y])): if self.grid[y][x] == ""@"": self.set_robot_pos(x, y) return (x, y) return None def set_robot_pos(self, x: int, y: int): self.robot_pos = (x, y) def swap(self, x1: int, y1: int, x2: int, y2: int): if self.is_valid(x1, y1) and self.is_valid(x2, y2): temp = self.grid[y1][x1] self.grid[y1][x1] = self.grid[y2][x2] self.grid[y2][x2] = temp def __str__(self): out = """" for row in self.grid: line = """" for val in row: line += val out += line + ""\n"" return out def parse() -> tuple[Grid, str]: grid_input, moves = open(""input.txt"").read().split(""\n\n"") grid = Grid([[val for val in line] for line in grid_input.splitlines()]) return (grid, moves) def move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): if move(grid, new_x, new_y, delta_x, delta_y): grid.swap(new_x, new_y, x, y) return True else: return False if grid.is_wall(new_x, new_y): return False return False def can_move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): return True if grid.is_box(new_x, new_y): possible_to_move = False if delta_y != 0: if grid.grid[new_y][new_x] == ""["": possible_to_move |= can_move(grid, new_x + 1, new_y, delta_x, delta_y) else: possible_to_move |= can_move(grid, new_x - 1, new_y, delta_x, delta_y) return possible_to_move and can_move(grid, new_x, new_y, delta_x, delta_y) else: return can_move(grid, new_x, new_y, delta_x, delta_y) if grid.is_wall(new_x, new_y): return False return False def wide_move(grid: Grid, x: int, y: int, delta_x: int, delta_y: int) -> bool: new_x, new_y = x + delta_x, y + delta_y if grid.is_empty(new_x, new_y): grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): if delta_y != 0: if grid.grid[new_y][new_x] == ""["": wide_move(grid, new_x + 1, new_y, delta_x, delta_y) else: wide_move(grid, new_x - 1, new_y, delta_x, delta_y) wide_move(grid, new_x, new_y, delta_x, delta_y) grid.swap(new_x, new_y, x, y) return True if grid.is_box(new_x, new_y): return False def part1(): grid, moves = parse() for robot_move in moves: x, y = grid.get_robot_pos() delta_x, delta_y = (1 if robot_move == "">"" else -1 if robot_move == ""<"" else 0, 1 if robot_move == ""v"" else -1 if robot_move == ""^"" else 0) if move(grid, x, y, delta_x, delta_y): grid.set_robot_pos(x + delta_x, y + delta_y) print(grid) coords = [100 * y + x if grid.is_box(x, y) else 0 for y in range(len(grid.grid)) for x in range(len(grid.grid[y]))] print(sum(coords)) def part2(): grid, moves = parse() new_grid = [[]] for idx, row in enumerate(grid.grid): new_grid.append([]) for val in row: if val == ""#"": new_grid[idx].append(""#"") new_grid[idx].append(""#"") elif val == ""O"": new_grid[idx].append(""["") new_grid[idx].append(""]"") elif val == ""."": new_grid[idx].append(""."") new_grid[idx].append(""."") elif val == ""@"": new_grid[idx].append(""@"") new_grid[idx].append(""."") grid.grid = new_grid for robot_move in moves: x, y = grid.get_robot_pos() delta_x, delta_y = (1 if robot_move == "">"" else -1 if robot_move == ""<"" else 0, 1 if robot_move == ""v"" else -1 if robot_move == ""^"" else 0) if can_move(grid, x, y, delta_x, delta_y): if wide_move(grid, x, y, delta_x, delta_y): grid.set_robot_pos(x + delta_x, y + delta_y) # print(grid) print(grid) coords = [100 * y + x if grid.grid[y][x] == ""["" else 0 for y in range(len(grid.grid)) for x in range(len(grid.grid[y]))] print(sum(coords)) part2()",python:3.9.21-slim 2024,15,2,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### ': (0, 1), 'v': (1, 0), '<': (0, -1)} return tuple(map(sum, zip(pos, move_dict[move]))) def get_chars(c): if c == '@': return '@.' elif c == 'O': return '[]' else: return c + c def can_push(grid, pos, move): if move in ['<', '>']: next_pos = get_next(get_next(pos, move), move) if grid[next_pos[0]][next_pos[1]] == '.': return True if grid[next_pos[0]][next_pos[1]] in ['[', ']']: return can_push(grid, next_pos, move) return False if move in ['^', 'v']: if grid[pos[0]][pos[1]] == '[': left, right = (pos, (pos[0], pos[1] + 1)) else: left, right = ((pos[0], pos[1] - 1), pos) next_left = get_next(left, move) next_right = get_next(right, move) if grid[next_left[0]][next_left[1]] == '#' or grid[next_right[0]][next_right[1]] == '#': return False return (grid[next_left[0]][next_left[1]] == '.' or can_push(grid, next_left, move)) and (grid[next_right[0]][next_right[1]] == '.' or can_push(grid, next_right, move)) def push(grid, pos, move): if move in ['<', '>']: j = pos[1] while grid[pos[0]][j] != '.': _, j = get_next((pos[0], j), move) if j < pos[1]: grid[pos[0]][j:pos[1]] = grid[pos[0]][j+1:pos[1]+1] else: grid[pos[0]][pos[1]+1:j+1] = grid[pos[0]][pos[1]:j] if move in ['^', 'v']: if grid[pos[0]][pos[1]] == '[': left, right = (pos, (pos[0], pos[1] + 1)) else: left, right = ((pos[0], pos[1] - 1), pos) next_left = get_next(left, move) next_right = get_next(right, move) if grid[next_left[0]][next_left[1]] == '[': push(grid, next_left, move) else: if grid[next_left[0]][next_left[1]] == ']': push(grid, next_left, move) if grid[next_right[0]][next_right[1]] == '[': push(grid, next_right, move) grid[next_left[0]][next_left[1]] = '[' grid[next_right[0]][next_right[1]] = ']' grid[left[0]][left[1]] = '.' grid[right[0]][right[1]] = '.' def print_grid(grid): for line in grid: print("""".join(line)) grid = [] moves = [] with open('input.txt') as f: for line in f.read().splitlines(): if line.startswith(""#""): row = """" for c in line: row += get_chars(c) grid += [[c for c in row]] elif not line == """": moves += [c for c in line] for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == '@': robot_pos = (i, j) break for move in moves: next_i, next_j = get_next(robot_pos, move) if grid[next_i][next_j] == '.': grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) elif grid[next_i][next_j] in ['[', ']']: if can_push(grid, (next_i, next_j), move): push(grid, (next_i, next_j), move) grid[robot_pos[0]][robot_pos[1]] = '.' grid[next_i][next_j] = '@' robot_pos = (next_i, next_j) total = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == '[': total += 100 * i + j print(total)",python:3.9.21-slim 2024,15,2,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### = width or y < 0 or y >= height: return False if (x, y) in walls: return False # horizontal move: if move[1] == 0: # left move: if move[0] == -1: if (x + move[0], x, y) in boxes: # need to move (x + move[0], x, y) box to left to_move.add((x + move[0], x, y)) return can_move(x + move[0], y, move, width, height, to_move) # right move else: if (x, x + move[0], y) in boxes: to_move.add((x, x + move[0], y)) return can_move(x + move[0], y, move, width, height, to_move) # vertical move: if move[0] == 0: if (x - 1, x, y) in boxes: to_move.add((x - 1, x, y)) return can_move(x - 1, y, move, width, height, to_move) and can_move(x, y, move, width, height, to_move) if (x, x + 1, y) in boxes: to_move.add((x, x + 1, y)) return can_move(x, y, move, width, height, to_move) and can_move(x + 1, y, move, width, height, to_move) return True def move_robot(x, y, width, height): for move in moves: to_move = set() if can_move(x, y, move, width, height, to_move): for each in to_move: boxes.remove(each) for each in to_move: boxes.add((each[0] + move[0], each[1] + move[0], each[2] + move[1])) x += move[0] y += move[1] def main(): warehouse_done = False robot_x = 0 robot_y = 0 width = 0 height = 0 y = 0 with open(""15_input.txt"", ""r"") as f: for line in f: line = line.strip() if line != """": if warehouse_done: moves.extend([char_map[c] for c in line]) else: x = 0 for char in line: if char == '#': walls.append((x, y)) walls.append((x + 1, y)) elif char == ""O"": boxes.add((x, x + 1, y)) elif char == ""@"": robot_x = x robot_y = y x += 2 if x > width: width = x else: warehouse_done = True if not warehouse_done: y += 1 if y > height: height = y move_robot(robot_x, robot_y, width, height) result = 0 for box in boxes: result += 100 * box[2] + box[0] print(result) char_map = {""^"": (0, -1), "">"": (1, 0), ""<"": (-1, 0), ""v"": (0, 1)} walls = [] boxes = set() moves = [] if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,15,2,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### "": (1, 0), ""^"": (0, -1), ""v"": (0, 1)} class Warehouse: def __init__(self, width): self.width = width self.robot_location = (0, 0) self.walls = [] self.boxes = {} self.moves = [] def print(self): for y in range(self.height): for x in range(self.width): p = (x, y) if p == self.robot_location: print(ROBOT, end="""") elif p in self.boxes: print(self.boxes[p], end="""") elif p in self.walls: print(WALL, end="""") else: print(""."", end="""") print() def add_wall(self, wall): wall_position = (wall[0] * 2, wall[1]) self.walls.append(wall_position) self.walls.append((wall_position[0] + 1, wall_position[1])) def add_box(self, box): box_position = (box[0] * 2, box[1]) self.boxes[box_position] = BOX_LEFT self.boxes[(box_position[0] + 1, box_position[1])] = BOX_RIGHT def set_robot_location(self, location): self.robot_location = (location[0] * 2, location[1]) def set_height(self, height): self.height = height def print_moves(self): for move in self.moves: print(move) def move(self, move): dx, dy = MOVES[move] new_location = (self.robot_location[0] + dx, self.robot_location[1] + dy) if new_location in self.walls: return if new_location in self.boxes: self.move_box(new_location, move) if new_location in self.boxes or new_location in self.walls: return self.robot_location = new_location def move_box(self, box, move): dx, dy = MOVES[move] if self.boxes[box] == BOX_RIGHT: box_left = (box[0] - 1, box[1]) box_right = box new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) else: box_left = box box_right = (box[0] + 1, box[1]) new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) # if horizontal if move == ""<"" or move == "">"": if self.boxes[box] == BOX_RIGHT: if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_right != box_left: if new_box_left in self.boxes or new_box_right in self.boxes: if not self.move_box(new_box_left, move): return False if new_box_left in self.boxes: if not self.move_box(new_box_left, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT elif self.boxes[box] == BOX_LEFT: if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_left != box_right: if new_box_left in self.boxes or new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False if new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT else: if self.collision_check(box, move): return False if new_box_left in self.walls or new_box_right in self.walls: return False if new_box_left in self.boxes: if not self.move_box(new_box_left, move): return False if new_box_right in self.boxes: if not self.move_box(new_box_right, move): return False self.boxes.pop(box_left) self.boxes.pop(box_right) self.boxes[new_box_left] = BOX_LEFT self.boxes[new_box_right] = BOX_RIGHT return True def collision_check(self, box, move): collision = False dx, dy = MOVES[move] if self.boxes[box] == BOX_RIGHT: box_left = (box[0] - 1, box[1]) box_right = box new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) else: box_left = box box_right = (box[0] + 1, box[1]) new_box_left = (box_left[0] + dx, box_left[1] + dy) new_box_right = (box_right[0] + dx, box_right[1] + dy) if new_box_left in self.walls or new_box_right in self.walls: return True if new_box_left in self.boxes: if self.collision_check(new_box_left, move): return True if new_box_right in self.boxes: if self.collision_check(new_box_right, move): return True return collision def run(self): for move in self.moves: self.move(move) def sum_of_box_locations(self): result = 0 for x, y in self.boxes: if self.boxes[(x, y)] == BOX_LEFT: result += x + 100 * y return result def read_file(): with open(INPUT_FILE, ""r"") as f: lines = f.readlines() width = len(lines[0].strip()) * 2 warehouse = Warehouse(width) moves = [] for y, line in enumerate(lines): if line[0] == ""#"": for x, c in enumerate(line.strip()): p = (x, y) if c == WALL: warehouse.add_wall(p) elif c == ROBOT: warehouse.set_robot_location(p) elif c == BOX: warehouse.add_box(p) elif line[0] == ""\n"": warehouse.set_height(y) else: for move in line.strip(): moves.append(move) warehouse.moves = moves return warehouse warehouse = read_file() warehouse.print() warehouse.run() print(warehouse.sum_of_box_locations())",python:3.9.21-slim 2024,15,2,"--- Day 15: Warehouse Woes --- You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well? You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. For example: ########## #..O..O.O# #......O.# #.OO..O.O# #..O@..O.# #O#..O...# #O..O..O.# #.OO.O.OO# #....O...# ########## ^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< <>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ ^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< ^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ <><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> ^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) Here is a smaller example to get started: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## <^^>>>vv>v<< Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: Initial state: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move <: ######## #..O.O.# ##@.O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move ^: ######## #.@O.O.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #..@OO.# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move >: ######## #...@OO# ##..O..# #...O..# #.#.O..# #...O..# #......# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##..@..# #...O..# #.#.O..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.@...# #...O..# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #..@O..# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #...@O.# #.#.O..# #...O..# #...O..# ######## Move >: ######## #....OO# ##.....# #....@O# #.#.O..# #...O..# #...O..# ######## Move v: ######## #....OO# ##.....# #.....O# #.#.O@.# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## Move <: ######## #....OO# ##.....# #.....O# #.#O@..# #...O..# #...O..# ######## The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: ########## #.O.O.OOO# #........# #OO......# #OO@.....# #O#.....O# #O.....OO# #O.....OO# #OO....OO# ########## The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. ####### #...O.. #...... The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? Your puzzle answer was 1499739. --- Part Two --- The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: If the tile is #, the new map contains ## instead. If the tile is O, the new map contains [] instead. If the tile is ., the new map contains .. instead. If the tile is @, the new map contains @. instead. This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) The larger example from before would now look like this: #################### ##....[]....[]..[]## ##............[]..## ##..[][]....[]..[]## ##....[]@.....[]..## ##[]##....[]......## ##[]....[]....[]..## ##..[][]..[]..[][]## ##........[]......## #################### Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: ####### #...#.# #.....# #..OO@# #..O..# #.....# ####### "": (0, 1), ""<"": (0, -1) } def move_horizontally(pos, move): while True: pos = tuple(map(sum, zip(pos, move))) pos_value = warehouse_map[pos[0]][pos[1]] if pos_value == ""#"": return False elif pos_value == ""."": if move[1] == 1: warehouse_map[pos[0]][pos[1]] = ""]"" else: warehouse_map[pos[0]][pos[1]] = ""["" while warehouse_map[pos[0]][pos[1] - move[1]] != ""@"": pos = (pos[0], pos[1] - move[1]) warehouse_map[pos[0]][pos[1]] = ""]"" if warehouse_map[pos[0]][pos[1]] == ""["" else ""["" return True def move_vertically(positions, move): involved_boxes = set(positions) next_positions = set(positions) while True: involved_boxes |= next_positions if len(next_positions) == 0: boxes_dict = {(x,y): warehouse_map[x][y] for (x,y) in involved_boxes} for box in involved_boxes: if not (box[0] - move[0], box[1]) in boxes_dict: warehouse_map[box[0]][box[1]] = ""."" warehouse_map[box[0] + move[0]][box[1]] = boxes_dict[box] return True positions = next_positions.copy() next_positions.clear() for pos in positions: next_pos = tuple(map(sum, zip(pos, move))) next_pos_value = warehouse_map[next_pos[0]][next_pos[1]] if next_pos_value == ""["": next_positions.add(next_pos) next_positions.add((next_pos[0], next_pos[1] + 1)) elif next_pos_value == ""]"": next_positions.add(next_pos) next_positions.add((next_pos[0], next_pos[1] - 1)) elif next_pos_value == ""#"": return False i = 0 while input[i] != """": modified_input = [] for char in input[i]: if char == ""#"": modified_input += [""#"", ""#""] elif char == ""O"": modified_input += [""["", ""]""] elif char == ""."": modified_input += [""."", "".""] else: modified_input += [""@"", "".""] cur_pos = (i, modified_input.index(""@"")) warehouse_map.append(modified_input) i += 1 i += 1 while i < len(input): movements += input[i] i += 1 for move in movements: destination = tuple(map(sum, zip(cur_pos, movement_dict[move]))) destination_value = warehouse_map[destination[0]][destination[1]] if destination_value == ""["" or destination_value == ""]"": if move == ""<"" or move == "">"": open_spot = move_horizontally(destination, movement_dict[move]) else: if destination_value == ""["": open_spot = move_vertically([destination, (destination[0], destination[1] + 1)], movement_dict[move]) else: open_spot = move_vertically([destination, (destination[0], destination[1] - 1)], movement_dict[move]) if open_spot: warehouse_map[destination[0]][destination[1]] = ""@"" warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" cur_pos = destination elif destination_value == ""."": warehouse_map[destination[0]][destination[1]] = ""@"" warehouse_map[cur_pos[0]][cur_pos[1]] = ""."" cur_pos = destination for i in range(len(warehouse_map)): for j in range(len(warehouse_map[i])): if warehouse_map[i][j] == ""["": total += 100 * i + j print(f""The sum of all boxes' final GPS coordinates is {total}"")",python:3.9.21-slim 2024,16,1,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"from heapq import heappop, heappush def get_lowest_score(maze): m = len(maze) n = len(maze[0]) start = (-1, -1) end = (-1, -1) for i in range(m): for j in range(n): if maze[i][j] == 'S': start = (i, j) elif maze[i][j] == 'E': end = (i, j) maze[end[0]][end[1]] = '.' dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] visited = set() heap = [(0, 0, *start)] while heap: score, dI, i, j = heappop(heap) if (i, j) == end: break if (dI, i, j) in visited: continue visited.add((dI, i, j)) x = i + dirs[dI][0] y = j + dirs[dI][1] if maze[x][y] == '.' and (dI, x, y) not in visited: heappush(heap, (score + 1, dI, x, y)) left = (dI - 1) % 4 if (left, i, j) not in visited: heappush(heap, (score + 1000, left, i, j)) right = (dI + 1) % 4 if (right, i, j) not in visited: heappush(heap, (score + 1000, right, i, j)) return score if __name__ == ""__main__"": # Open file 'day16-1.txt' in read mode with open('day16-1.txt', 'r') as f: maze = [] for line in f: line = line.strip() maze.append(list(line)) print(""Lowest Score:"", get_lowest_score(maze))",python:3.9.21-slim 2024,16,1,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"import heapq def dijkstra(grid): for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': start = ((i, j), (0, 1)) pq = [(0, start)] costs = { start: 0 } while len(pq) > 0: cost, (pos, direction) = heapq.heappop(pq) if grid[pos[0]][pos[1]] == 'E': return cost turns = [(1000, (pos, turn)) for turn in [(direction[1] * i, direction[0] * i) for i in [-1,1]]] step = tuple(map(sum, zip(pos, direction))) neighbors = turns + ([(1, (step, direction))] if grid[step[0]][step[1]] != '#' else []) for neighbor in neighbors: next_cost = cost + neighbor[0] if next_cost < costs.get(neighbor[1], float('inf')): heapq.heappush(pq, (next_cost, neighbor[1])) costs[neighbor[1]] = next_cost print(""Could not find min path"") return None with open('input.txt') as f: grid = [[c for c in line] for line in f.read().splitlines()] print(dijkstra(grid))",python:3.9.21-slim 2024,16,1,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"# Python heap implementation from heapq import heappush, heappop with open(""./day_16.in"") as fin: grid = fin.read().strip().split(""\n"") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == ""S"": start = (i, j) elif grid[i][j] == ""E"": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # DIjkstra's q = [(0, 0, *start)] seen = set() while len(q) > 0: top = heappop(q) cost, d, i, j = top if (d, i, j) in seen: continue seen.add((d, i, j)) if grid[i][j] == ""#"": continue if grid[i][j] == ""E"": print(cost) break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(cost + 1, d, ii, jj), (cost + 1000, (d + 1) % 4, i, j), (cost + 1000, (d + 3) % 4, i, j)]: if nbr[1:] in seen: continue heappush(q, nbr)",python:3.9.21-slim 2024,16,1,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"import re from typing import List, Tuple import heapq def parse_input(file_path: str): """""" Parse the input file to extract the data. Args: file_path (str): The path to the input file. Returns: List[str]: A list of strings representing the data from the file. """""" with open(file_path, 'r') as file: return [line.strip() for line in file] def find_starting_position(grid: List[str]) -> Tuple[int, int]: """""" Find the starting position marked as 'S' in the grid. Args: grid (List[str]): A list of strings representing the grid. Returns: Tuple[int, int]: A tuple containing the row and column indices of the starting position. """""" for i, row in enumerate(grid): for j, cell in enumerate(row): if cell == 'S': return i, j return -1, -1 # given a grid and a current position as well as a direction, # return the list of next possible moves either moving forward in the current direction or turning left or right def get_possible_moves(grid: List[str], i: int, j: int, direction: str) -> List[Tuple[int, int, str]]: """""" Get the possible moves from the current position in the grid. Args: grid (List[str]): A list of strings representing the grid. i (int): The row index of the current position. j (int): The column index of the current position. direction (str): The current direction ('N', 'E', 'S', 'W'). Returns: List[Tuple[int, int, str]]: A list of tuples where each tuple contains the row index, column index, and the direction of the possible moves. """""" rows, cols = len(grid), len(grid[0]) moves = {'N': (-1, 0), 'E': (0, 1), 'S': (1, 0), 'W': (0, -1)} left_turns = {'N': 'W', 'E': 'N', 'S': 'E', 'W': 'S'} right_turns = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'} possible_moves = [] # Check forward move dx, dy = moves[direction] new_i, new_j = i + dx, j + dy if 0 <= new_i < rows and 0 <= new_j < cols and grid[new_i][new_j] != '#': possible_moves.append((new_i, new_j, direction)) # Check left turn left_direction = left_turns[direction] left_dx, left_dy = moves[left_direction] left_i, left_j = i + left_dx, j + left_dy if 0 <= left_i < rows and 0 <= left_j < cols and grid[left_i][left_j] != '#': possible_moves.append((i, j, left_direction)) # Check right turn right_direction = right_turns[direction] right_dx, right_dy = moves[right_direction] right_i, right_j = i + right_dx, j + right_dy if 0 <= right_i < rows and 0 <= right_j < cols and grid[right_i][right_j] != '#': possible_moves.append((i, j, right_direction)) return possible_moves def find_lowest_score(grid: List[str], i: int, j: int, direction: str) -> int: """""" Finds the shortest path in a grid from a starting position (i, j) in a given direction. Args: grid (List[str]): A 2D grid represented as a list of strings. i (int): The starting row index. j (int): The starting column index. direction (str): The initial direction of movement. Returns: int: The shortest path score to reach the target 'E' in the grid. If the target is not reachable, returns float('inf'). """""" visited = set() heap = [(0, i, j, direction)] # (score, row, col, direction) while heap: score, i, j, direction = heapq.heappop(heap) if (i, j, direction) in visited: continue visited.add((i, j, direction)) if grid[i][j] == 'E': return score for new_i, new_j, new_direction in get_possible_moves(grid, i, j, direction): new_score = score + 1 if new_direction == direction else score + 1000 heapq.heappush(heap, (new_score, new_i, new_j, new_direction)) return float('inf') if __name__ == ""__main__"": file_path = 'input.txt' parsed_data = parse_input(file_path) i, j = find_starting_position(parsed_data) score = find_lowest_score(parsed_data, i, j, 'E') print(score)",python:3.9.21-slim 2024,16,1,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"# Python heap implementation from heapq import heappush, heappop from collections import defaultdict with open(""16.in"") as fin: grid = fin.read().strip().split(""\n"") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == ""S"": start = (i, j) elif grid[i][j] == ""E"": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # Dijkstra's q = [(0, 0, *start, 0, *start)] cost = {} deps = defaultdict(list) while len(q) > 0: top = heappop(q) c, d, i, j, pd, pi, pj = top if (d, i, j) in cost: if cost[(d, i, j)] == c: deps[(d, i, j)].append((pd, pi, pj)) continue never_seen_pos = True for newd in range(4): if (newd, i, j) in cost: never_seen_pos = True break if never_seen_pos: deps[(d, i, j)].append((pd, pi, pj)) cost[(d, i, j)] = c if grid[i][j] == ""#"": continue if grid[i][j] == ""E"": end_dir = d print(c) break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(c + 1, d, ii, jj, d, i, j), (c + 1000, (d + 1) % 4, i, j, d, i, j), (c + 1000, (d + 3) % 4, i, j, d, i, j)]: heappush(q, nbr)",python:3.9.21-slim 2024,16,2,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"# Python heap implementation from heapq import heappush, heappop from collections import defaultdict with open(""16.in"") as fin: grid = fin.read().strip().split(""\n"") n = len(grid) for i in range(n): for j in range(n): if grid[i][j] == ""S"": start = (i, j) elif grid[i][j] == ""E"": end = (i, j) dd = [[0, 1], [1, 0], [0, -1], [-1, 0]] # Dijkstra's q = [(0, 0, *start, 0, *start)] cost = {} deps = defaultdict(list) while len(q) > 0: top = heappop(q) c, d, i, j, pd, pi, pj = top if (d, i, j) in cost: if cost[(d, i, j)] == c: deps[(d, i, j)].append((pd, pi, pj)) continue never_seen_pos = True for newd in range(4): if (newd, i, j) in cost: never_seen_pos = True break if never_seen_pos: deps[(d, i, j)].append((pd, pi, pj)) cost[(d, i, j)] = c if grid[i][j] == ""#"": continue if grid[i][j] == ""E"": end_dir = d break ii = i + dd[d][0] jj = j + dd[d][1] for nbr in [(c + 1, d, ii, jj, d, i, j), (c + 1000, (d + 1) % 4, i, j, d, i, j), (c + 1000, (d + 3) % 4, i, j, d, i, j)]: heappush(q, nbr) # Go back through deps stack = [(end_dir, *end)] seen = set() seen_pos = set() while len(stack) > 0: top = stack.pop() if top in seen: continue seen.add(top) seen_pos.add(top[1:]) for nbr in deps[top]: stack.append(nbr) print(len(seen_pos))",python:3.9.21-slim 2024,16,2,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"#d16 part 2 from heapq import heappop, heappush def part2(puzzle_input): grid = puzzle_input.split('\n') m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] == 'S': start = (i, j) elif grid[i][j] == 'E': end = (i, j) grid[end[0]] = grid[end[0]].replace('E', '.') def can_visit(d, i, j, score): prev_score = visited.get((d, i, j)) if prev_score and prev_score < score: return False visited[(d, i, j)] = score return True directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] heap = [(0, 0, *start, {start})] visited = {} lowest_score = None winning_paths = set() while heap: score, d, i, j, path = heappop(heap) if lowest_score and lowest_score < score: break if (i, j) == end: lowest_score = score winning_paths |= path continue if not can_visit(d, i, j, score): continue x = i + directions[d][0] y = j + directions[d][1] if grid[x][y] == '.' and can_visit(d, x, y, score+1): heappush(heap, (score + 1, d, x, y, path | {(x, y)})) left = (d - 1) % 4 if can_visit(left, i, j, score + 1000): heappush(heap, (score + 1000, left, i, j, path)) right = (d + 1) % 4 if can_visit(right, i, j, score + 1000): heappush(heap, (score + 1000, right, i, j, path)) return len(winning_paths) with open(r'16.txt','r') as f: input_text = f.read() res = part2(input_text) res",python:3.9.21-slim 2024,16,2,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import heapq from sys import maxsize maze = open(""16.txt"").read().splitlines() seen = [[[maxsize for _ in range(4)] for x in range(len(maze[0]))] for y in range(len(maze))] velocities = [(-1, 0), (0, 1), (1, 0), (0, -1)] start_pos = None end_pos = None for j, r in enumerate(maze): for i, c in enumerate(r): if c == 'S': start_pos = (j, i) if c == 'E': end_pos = (j, i) # TODO For C, need a better track of path than shoving it all into a list lmao # I saw on da reddit a lot of folks searching backwards through the maze scores # for all scores where score is -1 or -1001 from current, starting at end. pq = [(0, (*start_pos, 1), [start_pos])] # start facing EAST paths = [] best_score = maxsize while pq and pq[0][0] <= best_score: score, (y, x, dir), path = heapq.heappop(pq) if (y, x) == end_pos: best_score = score paths.append(path) continue if seen[y][x][dir] < score: continue seen[y][x][dir] = score for i in range(4): dy, dx = velocities[i] ny, nx = y + dy, x + dx if maze[ny][nx] != '#' and (ny, nx) not in path: cost = 1 if i == dir else 1001 heapq.heappush(pq, (score + cost, (ny, nx, i), path + [(ny, nx)])) seats = set() for path in paths: seats |= set(path) print(len(seats))",python:3.9.21-slim 2024,16,2,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import heapq from typing import Dict, List, Tuple class MinHeap: """""" Min heap implementation using heapq library """""" def __init__(self): self.heap = [] def insert(self, element: Tuple[int, str]): heapq.heappush(self.heap, element) def extract_min(self) -> Tuple[int, str]: return heapq.heappop(self.heap) def size(self) -> int: return len(self.heap) DIRECTIONS = [ {""x"": 1, ""y"": 0}, {""x"": 0, ""y"": 1}, {""x"": -1, ""y"": 0}, {""x"": 0, ""y"": -1}, ] def dijkstra( graph: Dict[str, Dict[str, int]], start: Dict[str, int], directionless: bool ) -> Dict[str, int]: queue = MinHeap() distances = {} starting_key = ( f""{start['x']},{start['y']},0"" if not directionless else f""{start['x']},{start['y']}"" ) queue.insert((0, starting_key)) distances[starting_key] = 0 while queue.size() > 0: current_score, current_node = queue.extract_min() if distances[current_node] < current_score: continue if current_node not in graph: continue for next_node, weight in graph[current_node].items(): new_score = current_score + weight if next_node not in distances or distances[next_node] > new_score: distances[next_node] = new_score queue.insert((new_score, next_node)) return distances def parse_grid(grid: List[str]): width, height = len(grid[0]), len(grid) start = {""x"": 0, ""y"": 0} end = {""x"": 0, ""y"": 0} forward = {} reverse = {} for y in range(height): for x in range(width): if grid[y][x] == ""S"": start = {""x"": x, ""y"": y} if grid[y][x] == ""E"": end = {""x"": x, ""y"": y} if grid[y][x] != ""#"": for i, direction in enumerate(DIRECTIONS): position = {""x"": x + direction[""x""], ""y"": y + direction[""y""]} key = f""{x},{y},{i}"" move_key = f""{position['x']},{position['y']},{i}"" if ( 0 <= position[""x""] < width and 0 <= position[""y""] < height and grid[position[""y""]][position[""x""]] != ""#"" ): forward.setdefault(key, {})[move_key] = 1 reverse.setdefault(move_key, {})[key] = 1 for rotate_key in [ f""{x},{y},{(i + 3) % 4}"", f""{x},{y},{(i + 1) % 4}"", ]: forward.setdefault(key, {})[rotate_key] = 1000 reverse.setdefault(rotate_key, {})[key] = 1000 for i in range(len(DIRECTIONS)): key = f""{end['x']},{end['y']}"" rotate_key = f""{end['x']},{end['y']},{i}"" forward.setdefault(rotate_key, {})[key] = 0 reverse.setdefault(key, {})[rotate_key] = 0 return {""start"": start, ""end"": end, ""forward"": forward, ""reverse"": reverse} def tilesApartFromMaze() -> int: with open(""input.txt"") as file: con = file.read() grid = con.strip().split(""\n"") parsed = parse_grid(grid) from_start = dijkstra(parsed[""forward""], parsed[""start""], False) to_end = dijkstra(parsed[""reverse""], parsed[""end""], True) end_key = f""{parsed['end']['x']},{parsed['end']['y']}"" target = from_start[end_key] spaces = set() for position in from_start: if ( position != end_key and from_start[position] + to_end.get(position, float(""inf"")) == target ): x, y, *_ = position.split("","") # Unpack and ignore direction in the key spaces.add(f""{x},{y}"") print(len(spaces)) tilesApartFromMaze()",python:3.9.21-slim 2024,16,2,"--- Day 16: Reindeer Maze --- It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score. You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: ############### #.......#....E# #.#.###.#.###.# #.....#.#...#.# #.###.#####.#.# #.#.#.......#.# #.#.#####.###.# #...........#.# ###.#.#####.#.# #...#.....#.#.# #.#.#.###.#.#.# #.....#...#.#.# #.###.#.#.#.#.# #S..#.....#...# ############### There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: ############### #.......#....E# #.#.###.#.###^# #.....#.#...#^# #.###.#####.#^# #.#.#.......#^# #.#.#####.###^# #..>>>>>>>>v#^# ###^#.#####v#^# #>>^#.....#v#^# #^#.#.###.#v#^# #^....#...#v#^# #^###.#.#.#v#^# #S..#.....#>>^# ############### Here's a second example: ################# #...#...#...#..E# #.#.#.#.#.#.#.#.# #.#.#.#...#...#.# #.#.#.#.###.#.#.# #...#.#.#.....#.# #.#.#.#.#.#####.# #.#...#.#.#.....# #.#.#####.#.###.# #.#.#.......#...# #.#.###.#####.### #.#.#...#.....#.# #.#.#.#####.###.# #.#.#.........#.# #.#.#.#########.# #S#.............# ################# In this maze, the best paths cost 11048 points; following one such path would look like this: ################# #...#...#...#..E# #.#.#.#.#.#.#.#^# #.#.#.#...#...#^# #.#.#.#.###.#.#^# #>>v#.#.#.....#^# #^#v#.#.#.#####^# #^#v..#.#.#>>>>^# #^#v#####.#^###.# #^#v#..>>>>^#...# #^#v###^#####.### #^#v#>>^#.....#.# #^#v#^#####.###.# #^#v#^........#.# #^#v#^#########.# #S#>>^..........# ################# Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. Analyze your map carefully. What is the lowest score a Reindeer could possibly get? Your puzzle answer was 94444. --- Part Two --- Now that you know what the best paths look like, you can figure out the best spot to sit. Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: ############### #.......#....O# #.#.###.#.###O# #.....#.#...#O# #.###.#####.#O# #.#.#.......#O# #.#.#####.###O# #..OOOOOOOOO#O# ###O#O#####O#O# #OOO#O....#O#O# #O#O#O###.#O#O# #OOOOO#...#O#O# #O###.#.#.#O#O# #O..#.....#OOO# ############### In the second example, there are 64 tiles that are part of at least one of the best paths: ################# #...#...#...#..O# #.#.#.#.#.#.#.#O# #.#.#.#...#...#O# #.#.#.#.###.#.#O# #OOO#.#.#.....#O# #O#O#.#.#.#####O# #O#O..#.#.#OOOOO# #O#O#####.#O###O# #O#O#..OOOOO#OOO# #O#O###O#####O### #O#O#OOO#..OOO#.# #O#O#O#####O###.# #O#O#OOOOOOO..#.# #O#O#O#########.# #O#OOO..........# ################# Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"import time from collections import deque POSSIBLE_DIRS = (1, -1, 1j, -1j) def calculate_min_scores( start: complex, walls: set[complex] ) -> dict[complex, dict[complex, int]]: scores = {1: {start: 0}, -1: {}, 1j: {}, -1j: {}} points = deque([(start, 1)]) while points: p, d = points.popleft() score = scores[d][p] for move, dir, cost in [(p + d, d, 1), (p, d * -1j, 1000), (p, d * 1j, 1000)]: if move in walls: continue if move in scores[dir] and scores[dir][move] <= score + cost: continue scores[dir][move] = score + cost points.append((move, dir)) return scores def parse(text: str): walls: set[complex] = set() start: complex = 0j end: complex = 0j for y, row in enumerate(text.splitlines()): for x, c in enumerate(row): match c: case ""#"": walls.add(complex(x, y)) case ""S"": start = complex(x, y) case ""E"": end = complex(x, y) case _: pass return start, end, walls def solve_part_2(text: str): start, end, walls = parse(text) scores = calculate_min_scores(start, walls) path: set[complex] = {start, end} cost = min(scores[dir][end] for dir in POSSIBLE_DIRS if end in scores[dir]) points = deque( [ (end, dir, cost) for dir in POSSIBLE_DIRS if end in scores[dir] and scores[dir][end] == cost ] ) while points: p, d, cost = points.popleft() for move, dir, c1 in [ (p - d, d, cost - 1), (p, d * 1j, cost - 1000), (p, d * -1j, cost - 1000), ]: if move in scores[dir] and scores[dir][move] == c1: path.add(move) points.append((move, dir, c1)) return len(path) if __name__ == ""__main__"": with open(""input.txt"", ""r"") as f: quiz_input = f.read() p_2_solution = int(solve_part_2(quiz_input))",python:3.9.21-slim 2024,17,1,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","ADV = 0 BXL = 1 BST = 2 JNZ = 3 BXC = 4 OUT = 5 BDV = 6 CDV = 7 def get_combo_operand(operand, reg): if 0 <= operand <= 3: return operand if 4 <= operand <= 6: return reg[chr(ord('A') + operand - 4)] raise ValueError(f""Unexpected operand {operand}"") with open('input.txt') as f: lines = f.read().splitlines() reg = { 'A': int(lines[0].split("": "")[1]), 'B': int(lines[1].split("": "")[1]), 'C': int(lines[2].split("": "")[1])} instructions = list(map(int, lines[4].split("": "")[1].split("",""))) output = [] instr_ptr = 0 while instr_ptr < len(instructions): jump = False opcode, operand = instructions[instr_ptr:instr_ptr + 2] if opcode == ADV: reg['A'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) elif opcode == BXL: reg['B'] = reg['B'] ^ operand elif opcode == BST: reg['B'] = get_combo_operand(operand, reg) % 8 elif opcode == JNZ: if reg['A'] != 0: instr_ptr = operand jump = True elif opcode == BXC: reg['B'] = reg['B'] ^ reg['C'] elif opcode == OUT: output += [get_combo_operand(operand, reg) % 8] elif opcode == BDV: reg['B'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) elif opcode == CDV: reg['C'] = reg['A'] // (2 ** get_combo_operand(operand, reg)) else: raise ValueError(f""Unexpected opcode {opcode}"") if not jump: instr_ptr += 2 print("","".join(map(str, output)))",python:3.9.21-slim 2024,17,1,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","from collections.abc import Generator def get_out(a: int) -> int: b = (a % 8) ^ 1 return (b ^ (a // 2**b) ^ 4) % 8 def get_all_out(a: int) -> list[int]: out: list[int] = [] while a > 0: out.append(get_out(a)) a = a // 8 return out def next_A(seq: int, a: int) -> Generator[int]: while True: out = get_out(a) if out == seq: yield a a += 1 def main() -> None: seq: list[int] = [0, 3, 5, 5, 3, 0, 4, 1, 7, 4, 5, 7, 1, 1, 4, 2] a: int = 0 steps: dict[int, Generator[int]] = {} i = 1 while True: if i == len(seq) + 1: break s = seq[i - 1] if i not in steps: steps[i] = next_A(s, a) a = next(steps[i]) out = get_all_out(a) if out == list(reversed(seq[:i])): i += 1 a *= 8 print(a // 8) if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,17,1,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","#!/usr/bin/python3 def combo_operand(op:int) -> int: combo_operands = {4:""A"",5:""B"",6:""C""} return op if op < 4 else registers[combo_operands[op]] def adv(op:int) -> int: return int(registers[""A""] / 2 ** combo_operand(op)) def bxl(op:int) -> int: return registers[""B""] ^ op def bst(op:int) -> int: return combo_operand(op) % 8 def jnz(inst_pointer:int, op:int) -> int: return op if registers[""A""] != 0 else inst_pointer + 2 def bxc(op:int) -> int: return registers[""B""] ^ registers[""C""] def out(op:int) -> str: return str(combo_operand(op) % 8) def bdv(op:int) -> int: return adv(op) def cdv(op:int) -> int: return adv(op) with open(""input.txt"") as file: registers = {} for line in file: if ""Register"" in line: line = line.strip().split() registers[line[1].strip("":"")] = int(line[2]) elif ""Program"" in line: line = line.strip(""Program: "") program = [int(n) for n in line.strip().split("","")] instruction_pointer = 0 output = [] while instruction_pointer < len(program): opcode = program[instruction_pointer] operand = program[instruction_pointer + 1] if opcode == 0: registers[""A""] = adv(operand) elif opcode == 1: registers[""B""] = bxl(operand) elif opcode == 2: registers[""B""] = bst(operand) elif opcode == 3: instruction_pointer = jnz(instruction_pointer, operand) continue elif opcode == 4: registers[""B""] = bxc(operand) elif opcode == 5: output.append(out(operand)) elif opcode == 6: registers[""B""] = bdv(operand) elif opcode == 7: registers[""C""] = cdv(operand) instruction_pointer += 2 print(""Program output:"", "","".join(output))",python:3.9.21-slim 2024,17,1,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","output = """" i = 0 def get_result_string(regs, instructions): global output n = len(instructions) global i def get_combo(operand): if 0 <= operand < 4: return operand elif operand == 4: return regs['a'] elif operand == 5: return regs['b'] elif operand == 6: return regs['c'] return 0 def adv(operand): operand = get_combo(operand) regs['a'] = int(regs['a'] // (2**operand)) return def bxl(operand): regs['b'] = int(regs['b'] ^ operand) return def bst(operand): operand = get_combo(operand) regs['b'] = int(operand % 8) return def jnz(operand): global i if regs['a'] != 0: i = int(operand) - 1 return def bxc(operand): regs['b'] = int(regs['b'] ^ regs['c']) return def out(operand): global output operand = get_combo(operand) output += str(operand % 8) return def bdv(operand): operand = get_combo(operand) regs['b'] = int(regs['a'] // (2**operand)) return def cdv(operand): operand = get_combo(operand) regs['c'] = int(regs['a'] // (2**operand)) return while i < n: curr = instructions[i] if curr[0] == 0: adv(curr[1]) elif curr[0] == 1: bxl(curr[1]) elif curr[0] == 2: bst(curr[1]) elif curr[0] == 3: jnz(curr[1]) elif curr[0] == 4: bxc(curr[1]) elif curr[0] == 5: out(curr[1]) elif curr[0] == 6: bdv(curr[1]) elif curr[0] == 7: cdv(curr[1]) i += 1 return ','.join(list(output)) if __name__ == ""__main__"": regs = {} instructions = [] # Open file 'day17-1.txt' in read mode with open('day17-1.txt', 'r') as f: for line in f: line = line.strip() if regs.get('a') is None: regs['a'] = int(line[line.find(':') + 2:]) elif regs.get('b') is None: regs['b'] = int(line[line.find(':') + 2:]) elif regs.get('c') is None: regs['c'] = int(line[line.find(':') + 2:]) else: instructions = [int(val) for val in line[line.find(':') + 2:].split(',') if len(val) == 1] instructions = [(instructions[i], instructions[i + 1]) for i in range(0, len(instructions), 2)] print(""Result String:"", get_result_string(regs, instructions))",python:3.9.21-slim 2024,17,1,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","import re instr_map = { 0: lambda operand: adv(operand), 1: lambda operand: bxl(operand), 2: lambda operand: bst(operand), 3: lambda operand: jnz(operand), 4: lambda operand: bxc(operand), 5: lambda operand: out(operand), 6: lambda operand: bdv(operand), 7: lambda operand: cdv(operand) } def combo(operand): global reg_a, reg_b, reg_c if 0 <= operand <= 3: return operand elif operand == 4: return reg_a elif operand == 5: return reg_b elif operand == 6: return reg_c def adv(operand): global reg_a reg_a = reg_a // (2 ** combo(operand)) def bxl(operand): global reg_b reg_b = reg_b ^ operand def bst(operand): global reg_b reg_b = combo(operand) % 8 def bxc(operand): global reg_b, reg_c reg_b = reg_b ^ reg_c def out(operand): print(f'{combo(operand) % 8},', end='') def bdv(operand): global reg_a, reg_b reg_b = reg_a // (2 ** combo(operand)) def cdv(operand): global reg_a, reg_c reg_c = reg_a // (2 ** combo(operand)) def jnz(operand): global ip, reg_a if reg_a != 0: ip = operand ip -= 2 def main(): global reg_a, reg_b, reg_c, ip with open(""17_input.txt"", ""r"") as f: reg_a = int(re.search(r""(\d+)"", f.readline())[0]) reg_b = int(re.search(r""(\d+)"", f.readline())[0]) reg_c = int(re.search(r""(\d+)"", f.readline())[0]) f.readline() program = [int(opcode) for opcode in re.findall(r""(\d+)"", f.readline())] print(f'{reg_a=}, {reg_b=}, {reg_c=}, {program=}') while 0 <= ip < len(program): instr_map[program[ip]](program[ip+1]) ip += 2 reg_a: int = 0 reg_b: int = 0 reg_c: int = 0 ip: int = 0 if __name__ == '__main__': main()",python:3.9.21-slim 2024,17,2,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"def run(regs, instructions): n = len(instructions) i = 0 output = [] def get_combo(operand): if 0 <= operand < 4: return operand elif operand == 4: return regs['a'] elif operand == 5: return regs['b'] elif operand == 6: return regs['c'] return 0 while i < n: curr = instructions[i] operand = instructions[i + 1] if curr == 0: regs['a'] //= 2**get_combo(operand) elif curr == 1: regs['b'] ^= operand elif curr == 2: regs['b'] = get_combo(operand) % 8 elif curr == 3: if regs['a']: i = operand continue elif curr == 4: regs['b'] ^= regs['c'] elif curr == 5: output.append(get_combo(operand) % 8) elif curr == 6: regs['b'] = regs['a'] // 2**get_combo(operand) elif curr == 7: regs['c'] = regs['a'] // 2**get_combo(operand) i += 2 return list(output) def get_lowest_a(regs, instructions): regs['a'] = 0 j = 1 iFloor = 0 while j <= len(instructions) and j >= 0: regs['a'] <<= 3 for i in range(iFloor, 8): regsCopy = regs.copy() regsCopy['a'] += i if instructions[-j:] == run(regsCopy, instructions): break else: j -= 1 regs['a'] >>= 3 iFloor = regs['a'] % 8 + 1 regs['a'] >>= 3 continue j += 1 regs['a'] += i iFloor = 0 return regs['a'] if __name__ == ""__main__"": regs = {} instructions = [] # Open file 'day17-2.txt' in read mode with open('day17-2.txt', 'r') as f: for line in f: line = line.strip() if regs.get('a') is None: regs['a'] = 0 elif regs.get('b') is None: regs['b'] = int(line[line.find(':') + 2:]) elif regs.get('c') is None: regs['c'] = int(line[line.find(':') + 2:]) else: instructions = [int(val) for val in line[line.find(':') + 2:].split(',') if len(val) == 1] print(""Lowest value of Register A:"", get_lowest_a(regs, instructions))",python:3.9.21-slim 2024,17,2,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"from part1 import parse_input def run(program, regs): """""" Executes a given program with specified registers. Args: program (list of int): A list of integers representing the program's opcodes and operands. regs (list of int): A list of initial values for the registers. Yields: int: The result of the operation specified by opcode 5, modulo 8. The program supports the following opcodes: 0: Divide the value in reg_a by 2 raised to the power of the value in the register specified by operand. 1: XOR the value in reg_b with the operand. 2: Set reg_b to the value in the register specified by operand, modulo 8. 3: If the value in reg_a is non-zero, set the instruction pointer to operand - 2. 4: XOR the value in reg_b with the value in reg_c. 5: Yield the value in the register specified by operand, modulo 8. 6: Set reg_b to the value in reg_a divided by 2 raised to the power of the value in the register specified by operand. 7: Set reg_c to the value in reg_a divided by 2 raised to the power of the value in the register specified by operand. """""" reg_a, reg_b, reg_c = range(4, 7) ip = 0 combo = [0, 1, 2, 3, *regs] while ip < len(program): opcode, operand = program[ip:ip + 2] if opcode == 0: combo[reg_a] //= 2 ** combo[operand] elif opcode == 1: combo[reg_b] ^= operand elif opcode == 2: combo[reg_b] = combo[operand] % 8 elif opcode == 3: if combo[reg_a]: ip = operand - 2 elif opcode == 4: combo[reg_b] ^= combo[reg_c] elif opcode == 5: yield combo[operand] % 8 elif opcode == 6: combo[reg_b] = combo[reg_a] // (2 ** combo[operand]) elif opcode == 7: combo[reg_c] = combo[reg_a] // (2 ** combo[operand]) ip += 2 def expect(program, target_output, prev_a=0): """""" Tries to find an integer 'a' such that when the 'program' is run with inputs derived from 'a', it produces the 'target_output' sequence. Args: program (iterable): The program to be run, which yields outputs based on inputs. target_output (list): The desired sequence of outputs that the program should produce. prev_a (int, optional): The previous value of 'a' used in the recursive calls. Defaults to 0. Returns: int or None: The integer 'a' that produces the 'target_output' when the program is run, or None if no such 'a' can be found. """""" def helper(program, target_output, prev_a): if not target_output: return prev_a for a in range(1 << 10): if a >> 3 == prev_a & 127 and next(run(program, (a, 0, 0))) == target_output[-1]: result = helper(program, target_output[:-1], (prev_a << 3) | (a % 8)) if result is not None: return result return None return helper(program, target_output, prev_a) if __name__ == ""__main__"": file_path = 'input.txt' registers, program = parse_input(file_path) # Example target output target_output = program.copy() initial_value = expect(program, target_output) if initial_value is not None: print(f""The initial value for register A that produces the target output is: {initial_value}"") else: print(""No initial value found that produces the target output within the given attempts."")",python:3.9.21-slim 2024,17,2,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() program = [int(x) for x in input_text[4].removeprefix(""Program: "").split("","")] a = 0 position = 0 offsets = [0] while position < len(program): if program[-1 - position] == ((a % 8) ^ 5 ^ 6 ^ (a // (2 ** ((a % 8) ^ 5)))) % 8: a *= 8 position += 1 offsets.append(0) elif offsets[-1] < 7: a += 1 offsets[-1] += 1 else: while offsets[-1] >= 7 and position > 0: a //= 8 offsets.pop(-1) position -= 1 a += 1 offsets[-1] += 1 print(a // 8)",python:3.9.21-slim 2024,17,2,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"import re with open(""17.txt"") as i: input = [x.strip() for x in i.readlines()] test_data = """"""Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0"""""".split(""\n"") # input = test_data a, b, c = 0, 0, 0 program = None for l in input: if l.startswith(""Register ""): r, v = re.match(r""Register (A|B|C): (\d+)"", l).groups() if r == ""A"": a = int(v) elif r == ""B"": b = int(v) elif r == ""C"": c = int(v) elif l.startswith(""Program: ""): program = [int(x) for x in l[9:].split("","")] def run_program(program: list[int], aa: int, bb: int, cc: int) -> list[int]: output = [] a, b, c = aa, bb, cc ip = 0 while ip < len(program): i = program[ip] op = program[ip+1] cop = None if op == 4: cop = a elif op == 5: cop = b elif op == 6: cop = c else: cop = op if i == 0: # adv a = a // (2**cop) elif i == 1: # bxl b = b ^ op elif i == 2: #bst b = cop % 8 elif i == 3: # jnz if a != 0: ip = op continue elif i == 4: # bxc b = b ^ c elif i == 5: # out output.append(cop%8) elif i == 6: # bdv b = a // (2**cop) elif i == 7: # cdv c = a // (2**cop) ip += 2 return output current = len(program) solutions = [0] while current>0: next_solutions = [] for aa in solutions: for i in range(8): r = run_program(program, (aa<<3) | i, b, c) if r[0] == program[current-1]: next_solutions.append((aa << 3) | i) current = current - 1 solutions = next_solutions part2 = min(solutions) print(part2)",python:3.9.21-slim 2024,17,2,"--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. ""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 7,5,4,3,4,5,3,4,6. --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"# day 17 import os def reader(): return open(f""17.txt"", 'r').read().splitlines() def simulate(program, A): l = [0, 1, 2, 3, A, 0, 0, -1] out = [] i = 0 while i < len(program): op = program[i] operand = program[i + 1] if op == 0: l[4] = int(l[4] / (2 ** l[operand])) elif op == 1: l[5] = l[5] ^ operand elif op == 2: l[5] = l[operand] % 8 elif op == 3: if l[4] != 0: i = operand continue elif op == 4: l[5] = l[5] ^ l[6] elif op == 5: out.append(l[operand] % 8) elif op == 6: l[5] = int(l[4] / (2 ** l[operand])) elif op == 7: l[6] = int(l[4] / (2 ** l[operand])) i += 2 return out def part2(): f = reader() program = list(map(int, f[4][(f[4].find(': ') + 2):].split(','))) def backtrack(A=0, j=-1): if -j > len(program): return A m = float('inf') for i in range(8): t = (A << 3) | i if simulate(program, t)[j:] == program[j:]: m = min(m, backtrack(t, j - 1)) return m print(backtrack()) part2()",python:3.9.21-slim 2024,18,1,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heapify, heappop, heappush with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() grid_size = 70 num_fallen = 1024 bytes = set() for byte in input_text[:num_fallen]: byte_x, byte_y = byte.split("","") bytes.add((int(byte_x), int(byte_y))) movements = ((-1, 0), (1, 0), (0, 1), (0, -1)) explored = set() discovered = [(0, 0, 0)] heapify(discovered) while True: distance, byte_x, byte_y = heappop(discovered) if (byte_x, byte_y) not in explored: explored.add((byte_x, byte_y)) if byte_x == byte_y == grid_size: print(distance) break for movement in movements: new_position = (byte_x + movement[0], byte_y + movement[1]) if ( new_position not in bytes and new_position not in explored and all(0 <= coord <= grid_size for coord in new_position) ): heappush(discovered, (distance + 1, *new_position))",python:3.9.21-slim 2024,18,1,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from collections import deque from typing import List, Tuple def parse_input(file_path: str) -> List[Tuple[int, int]]: """""" Parses the input file and returns a list of tuples containing integer pairs. Args: file_path (str): The path to the input file. Returns: List[Tuple[int, int]]: A list of tuples, where each tuple contains two integers parsed from a line in the input file. Each line in the file should contain two integers separated by a comma. """""" with open(file_path, 'r') as file: return [tuple(map(int, line.strip().split(','))) for line in file] def initialize_grid(size: int) -> List[List[str]]: """""" Initializes a square grid of the given size with all cells set to '.'. Args: size (int): The size of the grid (number of rows and columns). Returns: List[List[str]]: A 2D list representing the initialized grid. """""" return [['.' for _ in range(size)] for _ in range(size)] def simulate_falling_bytes(grid: List[List[str]], byte_positions: List[Tuple[int, int]], num_bytes: int): """""" Simulates the falling of bytes in a grid. Args: grid (List[List[str]]): A 2D list representing the grid where bytes will fall. byte_positions (List[Tuple[int, int]]): A list of tuples representing the (x, y) positions of bytes. num_bytes (int): The number of bytes to simulate falling. Returns: None """""" for x, y in byte_positions[:num_bytes]: grid[y][x] = '#' def find_shortest_path(grid: List[List[str]]) -> int: """""" Finds the shortest path in a grid from the top-left corner to the bottom-right corner. The grid is represented as a list of lists of strings, where '.' represents an open cell and any other character represents an obstacle. Args: grid (List[List[str]]): The grid to search, where each element is a string representing a cell. Returns: int: The number of steps in the shortest path from the top-left to the bottom-right corner. Returns -1 if no such path exists. """""" size = len(grid) directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] queue = deque([(0, 0, 0)]) # (x, y, steps) visited = set([(0, 0)]) while queue: x, y, steps = queue.popleft() if (x, y) == (size - 1, size - 1): return steps for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < size and 0 <= ny < size and grid[ny][nx] == '.' and (nx, ny) not in visited: visited.add((nx, ny)) queue.append((nx, ny, steps + 1)) return -1 # No path found if __name__ == ""__main__"": file_path = 'input.txt' byte_positions = parse_input(file_path) grid_size = 71 # For the actual problem, use 71; for the example, use 7 grid = initialize_grid(grid_size) simulate_falling_bytes(grid, byte_positions, 1024) steps = find_shortest_path(grid) print(f""Minimum number of steps needed to reach the exit: {steps}"")",python:3.9.21-slim 2024,18,1,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heappop, heappush def in_bounds(i, j, n): return 0 <= i < n and 0 <= j < n def navigate(maze, n): start = (0, 0) end = (n - 1, n - 1) heap = [(0, start[0], start[1])] visited = set() while heap: score, i, j = heappop(heap) if (i, j) == end: break if (i, j) in visited: continue visited.add((i, j)) if in_bounds(i, j+1, n) and maze[i][j+1] not in visited and maze[i][j+1] == '.': heappush(heap, (score + 1, i, j+1)) if in_bounds(i+1, j, n) and maze[i+1][j] not in visited and maze[i+1][j] == '.': heappush(heap, (score + 1, i+1, j)) if in_bounds(i, j-1, n) and maze[i][j-1] not in visited and maze[i][j-1] == '.': heappush(heap, (score + 1, i, j-1)) if in_bounds(i-1, j, n) and maze[i-1][j] not in visited and maze[i-1][j] == '.': heappush(heap, (score + 1, i-1, j)) return score def init_maze(bytes, n, numBytes): maze = [['.' for _ in range(n)] for _ in range(n)] for byte in bytes[:numBytes]: maze[byte[1]][byte[0]] = '#' return maze def get_min_steps(bytes): n = 71 numBytes = 1024 maze = init_maze(bytes, n, numBytes) return navigate(maze, n) if __name__ == ""__main__"": # Open file 'day18-1.txt' in read mode with open('day18-1.txt', 'r') as f: bytes = [] for line in f: line = line.strip() x, y = line.split(',') bytes.append((int(x), int(y))) print(""Minimum steps:"", get_min_steps(bytes))",python:3.9.21-slim 2024,18,1,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"def bfs(byte_locs, x_len, y_len): start = (0, 0) end = (x_len - 1, y_len - 1) visited = set() frontier = [[start]] while len(frontier) > 0: path = frontier.pop(0) cur = path[-1] if cur == end: return path visited.add(cur) neighbors = [tuple(map(sum, zip(cur, direction))) for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]] neighbors = [pos for pos in neighbors if pos[0] in range(x_len) and pos[1] in range(y_len) and pos not in byte_locs] for neighbor in neighbors: if neighbor not in visited: frontier.append(path + [neighbor]) visited.add(neighbor) print(""no path found"") return None with open('input.txt') as f: lines = f.read().splitlines() byte_locs = [tuple(map(int, line.split("",""))) for line in lines] x_len = 71 y_len = 71 print(len(bfs(set(byte_locs[0:1024]), x_len, y_len)) - 1)",python:3.9.21-slim 2024,18,1,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"from heapq import heappush, heappop with open(""./day_18.in"") as fin: lines = fin.read().strip().split(""\n"") coords = set([tuple(map(int, line.split("",""))) for line in lines][:1024]) dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] N = 70 # Heuristic for A* def h(i, j): return abs(N - i) + abs(N - j) def in_grid(i, j): return 0 <= i <= N and 0 <= j <= N and (i, j) not in coords q = [(h(0, 0), 0, 0)] cost = {} while len(q) > 0: c, i, j = heappop(q) if (i, j) in cost: continue cost[(i, j)] = c - h(i, j) if (i, j) == (N, N): print(cost[(i, j)]) break for di, dj in dd: ii, jj = i + di, j + dj if in_grid(ii, jj): heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj))",python:3.9.21-slim 2024,18,2,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from heapq import heapify, heappop, heappush with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() grid_size = 70 bytes_list = [] for byte in input_text: byte_x, byte_y = byte.split("","") bytes_list.append((int(byte_x), int(byte_y))) movements = ((-1, 0), (1, 0), (0, 1), (0, -1)) bytes_needed_lower = 0 bytes_needed_upper = len(bytes_list) - 1 while bytes_needed_lower < bytes_needed_upper: mid = (bytes_needed_lower + bytes_needed_upper) // 2 bytes = set(bytes_list[:mid]) explored = set() discovered = [(0, 0, 0)] heapify(discovered) while discovered: distance, byte_x, byte_y = heappop(discovered) if (byte_x, byte_y) not in explored: explored.add((byte_x, byte_y)) if byte_x == byte_y == grid_size: break for movement in movements: new_position = (byte_x + movement[0], byte_y + movement[1]) if ( new_position not in bytes and new_position not in explored and all(0 <= coord <= grid_size for coord in new_position) ): heappush(discovered, (distance + 1, *new_position)) else: bytes_needed_upper = mid continue bytes_needed_lower = mid + 1 print("","".join([str(x) for x in bytes_list[bytes_needed_lower - 1]]))",python:3.9.21-slim 2024,18,2,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","def bfs(byte_locs, x_len, y_len): start = (0, 0) end = (x_len - 1, y_len - 1) visited = set() frontier = [[start]] while len(frontier) > 0: path = frontier.pop(0) cur = path[-1] if cur == end: return path visited.add(cur) neighbors = [tuple(map(sum, zip(cur, direction))) for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]] neighbors = [pos for pos in neighbors if pos[0] in range(x_len) and pos[1] in range(y_len) and pos not in byte_locs] for neighbor in neighbors: if neighbor not in visited: frontier.append(path + [neighbor]) visited.add(neighbor) return None with open('input.txt') as f: lines = f.read().splitlines() byte_locs = [tuple(map(int, line.split("",""))) for line in lines] x_len = 71 y_len = 71 lower = 0 upper = len(byte_locs) - 1 while lower <= upper: mid = (lower + upper) // 2 test = bfs(set(byte_locs[0:mid]), x_len, y_len) if test is None: upper = mid - 1 print(""not reachable at"", byte_locs[mid-1]) else: print(""reachable at"", byte_locs[mid-1]) lower = mid + 1 print(byte_locs[mid])",python:3.9.21-slim 2024,18,2,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from heapq import heappush, heappop with open(""./day_18.in"") as fin: lines = fin.read().strip().split(""\n"") coords = [tuple(map(int, line.split("",""))) for line in lines] dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] N = 70 # Heuristic for A* def h(i, j): return abs(N - i) + abs(N - j) def doable(idx): # Can we get to the index with first `idx` coords blocked? def in_grid(i, j): return 0 <= i <= N and 0 <= j <= N and (i, j) not in coords[:idx] q = [(h(0, 0), 0, 0)] cost = {} while len(q) > 0: c, i, j = heappop(q) if (i, j) in cost: continue cost[(i, j)] = c - h(i, j) if (i, j) == (N, N): return True for di, dj in dd: ii, jj = i + di, j + dj if in_grid(ii, jj): heappush(q, (cost[(i, j)] + 1 + h(ii, jj), ii, jj)) return False # Binary search for first coord that is not doable lo = 0 hi = len(coords) - 1 while hi > lo: mid = (lo + hi) // 2 if doable(mid): lo = mid + 1 else: hi = mid print("","".join(map(str, coords[lo-1])))",python:3.9.21-slim 2024,18,2,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","from collections import deque l = open(""18.txt"").read().splitlines() l = [list(map(int, x.split("",""))) for x in l] max_x = max(coord[0] for coord in l) max_y = max(coord[1] for coord in l) def P2(): for find in range(1024,len(l)): grid = [[""."" for _ in range(max_y + 1)] for _ in range(max_x + 1)] for i in range(find): x,y = l[i] grid[x][y] = ""#"" def bfs(grid, start, end): rows, cols = len(grid), len(grid[0]) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] queue = deque([(start, 0)]) visited = set() while queue: (x, y), dist = queue.popleft() if (x, y) == end: return dist if (x, y) in visited or grid[x][y] == ""#"": continue visited.add((x, y)) for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < rows and 0 <= ny < cols and (nx, ny) not in visited: queue.append(((nx, ny), dist + 1)) return -1 if bfs(grid, (0,0), (max_x, max_y)) == -1: return l[find-1] print(P2())",python:3.9.21-slim 2024,18,2,"--- Day 18: RAM Run --- You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: 5,4 4,2 4,5 3,0 2,1 6,3 2,4 1,5 0,6 3,3 2,6 5,1 1,2 5,5 2,5 6,5 1,4 0,4 6,4 1,1 6,1 1,0 0,5 1,6 2,0 Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: ...#... ..#..#. ....#.. ...#..# ..#..#. .#..#.. #.#.... You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: OO.#OOO .O#OO#O .OOO#OO ...#OO# ..#OO#. .#.O#.. #.#OOOO Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? Your puzzle answer was 506. --- Part Two --- The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. In the above example, after the byte at 1,1 falls, there is still a path to the exit: O..#OOO O##OO#O O#OO#OO OOO#OO# ###OO## .##O### #.#OOOO However, after adding the very next byte (at 6,1), there is no longer a path to the exit: ...#... .##..## .#..#.. ...#..# ###..## .##.### #.#.... So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","#!/usr/bin/env python3 import re from collections import defaultdict, deque myfile = open(""18.in"", ""r"") lines = myfile.read().strip().splitlines() myfile.close() blocks = [tuple(map(int, re.findall(r""\d+"", line))) for line in lines] part_one = 0 part_two = 0 height = width = 70 def search(block_count): grid = defaultdict(str) for x in range(width + 1): for y in range(height + 1): grid[(x, y)] = ""."" grid[(width, height)] = ""$"" for x, y in blocks[: block_count + 1]: grid[(x, y)] = """" visited = set() scores = defaultdict(lambda: float(""inf"")) scores[(0, 0)] = 0 q = deque([(0, 0)]) while q: pos = q.popleft() visited.add(pos) if grid[pos] == ""$"": return scores[pos] next_score = scores[pos] + 1 for dir in [(1, 0), (0, -1), (-1, 0), (0, 1)]: next_pos = (pos[0] + dir[0], pos[1] + dir[1]) if next_pos not in visited and next_score < scores[next_pos]: if grid[next_pos] != """": scores[next_pos] = next_score q.append(next_pos) return -1 unblocked, blocked = 1024, len(blocks) while blocked - unblocked > 1: mid = (unblocked + blocked) // 2 result = search(mid) if result == -1: blocked = mid else: unblocked = mid part_two = "","".join(map(str, blocks[blocked])) print(""Part Two:"", part_two)",python:3.9.21-slim 2024,19,1,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from pprint import pprint WHITE = ""w"" BLUE = ""u"" BLACK = ""b"" RED = ""r"" GREEN = ""g"" INPUT_FILE = ""test.txt"" read_file = open(INPUT_FILE, ""r"") lines = read_file.readlines() available_towels = lines[0].strip().split("", "") designs = [] for line in lines[2:]: designs.append(line.strip()) def find_first_pattern(design, start_index=0): for i in range(len(design), 0, -1): if design[start_index:i] in available_towels: return (i, design[start_index:i]) return (None, None) def find_last_pattern(design, end_index): for i in range(len(design)): if design[i:end_index] in available_towels: return (i, design[i:end_index]) return (None, None) def find_largest_from_start(design, start=0): largest_pattern_match = None end = 0 for i in range(1 + start, len(design)): sub_string = design[start:i] print(sub_string) if sub_string in available_towels: largest_pattern_match = sub_string end = i return (largest_pattern_match, end) results = [] impossible_designs = [] def can_build_word(target, patterns): def can_build(remaining, memo=None): if memo is None: memo = {} # Base cases if not remaining: # Successfully used all letters return True if remaining in memo: # Already tried this combo return memo[remaining] # Try each pattern at the start of our remaining string # We can reuse patterns, so no need to track what we've used for pattern in patterns: if remaining.startswith(pattern): new_remaining = remaining[len(pattern) :] if can_build(new_remaining, memo): memo[remaining] = True print(memo) return True memo[remaining] = False return False return can_build(target) can_build_count = 0 for design in designs: if can_build_word(design, available_towels): can_build_count += 1 print(can_build_count) quit() for design in designs: patterns = {} result = 0 pattern_found = False while True: (result, pattern) = find_first_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if not result: pattern_found = False break if design[:result] == design: pattern_found = True break if pattern_found: results.append((design, patterns)) else: patterns = {} result = len(design) pattern_found = False while True: (result, pattern) = find_last_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if result == None: pattern_found = False break if result == 0: pattern_found = True break if pattern_found: results.append((design, patterns)) else: impossible_designs.append(design)",python:3.9.21-slim 2024,19,1,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from functools import cache with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() towels_trie = {} for towel in input_text[0].split("", ""): inner_dict = towels_trie for letter in list(towel): if letter not in inner_dict: inner_dict[letter] = {} inner_dict = inner_dict[letter] inner_dict[None] = None @cache def pattern_possible(pattern): if not pattern: return True patterns_needed = [] trie = towels_trie for i, letter in enumerate(pattern): if letter in trie: trie = trie[letter] if None in trie: patterns_needed.append(pattern[i + 1 :]) else: break return any(pattern_possible(sub_pattern) for sub_pattern in patterns_needed) print(sum(pattern_possible(pattern) for pattern in input_text[2:]))",python:3.9.21-slim 2024,19,1,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"def is_pattern_possible(pattern, towels, visited): if pattern == """": return True visited.add(pattern) return any([pattern.startswith(t) and pattern[len(t):] not in visited and is_pattern_possible(pattern[len(t):], towels, visited) for t in towels]) with open('input.txt') as f: lines = f.read().splitlines() towels = [s.strip() for s in lines[0].split("","")] patterns = lines[2:] print(sum([is_pattern_possible(p, towels, set()) for p in patterns]))",python:3.9.21-slim 2024,19,1,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"from pprint import pprint WHITE = ""w"" BLUE = ""u"" BLACK = ""b"" RED = ""r"" GREEN = ""g"" INPUT_FILE = ""test.txt"" read_file = open(INPUT_FILE, ""r"") lines = read_file.readlines() available_towels = lines[0].strip().split("", "") designs = [] for line in lines[2:]: designs.append(line.strip()) def find_first_pattern(design, start_index=0): for i in range(len(design), 0, -1): if design[start_index:i] in available_towels: return (i, design[start_index:i]) return (None, None) def find_last_pattern(design, end_index): for i in range(len(design)): if design[i:end_index] in available_towels: return (i, design[i:end_index]) return (None, None) def find_largest_from_start(design, start=0): largest_pattern_match = None end = 0 for i in range(1 + start, len(design)): sub_string = design[start:i] print(sub_string) if sub_string in available_towels: largest_pattern_match = sub_string end = i return (largest_pattern_match, end) results = [] impossible_designs = [] def can_build_pattern(target, patterns): def can_build(remaining, memo=None): if memo is None: memo = {} # Base cases if not remaining: # Successfully used all letters return True if remaining in memo: # Already tried this combo return memo[remaining] # Try each pattern at the start of our remaining string # We can reuse patterns, so no need to track what we've used for pattern in patterns: if remaining.startswith(pattern): new_remaining = remaining[len(pattern) :] if can_build(new_remaining, memo): memo[remaining] = True print(memo) return True memo[remaining] = False return False return can_build(target) can_build_count = 0 for design in designs: if can_build_pattern(design, available_towels): can_build_count += 1 print(can_build_count) quit() for design in designs: patterns = {} result = 0 pattern_found = False while True: (result, pattern) = find_first_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if not result: pattern_found = False break if design[:result] == design: pattern_found = True break if pattern_found: results.append((design, patterns)) else: patterns = {} result = len(design) pattern_found = False while True: (result, pattern) = find_last_pattern(design, result) patterns[pattern] = patterns.get(pattern, 0) + 1 if result == None: pattern_found = False break if result == 0: pattern_found = True break if pattern_found: results.append((design, patterns)) else: impossible_designs.append(design)",python:3.9.21-slim 2024,19,1,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"with open(""./day_19.in"") as fin: lines = fin.read().strip().split(""\n"") units = lines[0].split("", "") designs = lines[2:] def possible(design): n = len(design) dp = [False] * len(design) for i in range(n): if design[:i+1] in units: dp[i] = True continue for u in units: if design[i-len(u)+1:i+1] == u and dp[i - len(u)]: # print("" "", i, u, design[-len(u):], dp[i - len(u)]) dp[i] = True break # print(design, dp) return dp[-1] ans = 0 for d in designs: if possible(d): print(d) ans += 1 print(ans)",python:3.9.21-slim 2024,19,2,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"def check_count(towels, pattern, cache): if pattern == """": return 1 if (block := cache.get(pattern, None)) is not None: return block result = 0 for towel in towels: if towel == pattern[:len(towel)]: result += check_count(towels, pattern[len(towel):], cache) cache[pattern] = result return result def get_num_achievable_patterns(towels, patterns): return sum([check_count(towels, pattern, {}) for pattern in patterns]) if __name__ == ""__main__"": towels = [] patterns = [] # Open file 'day19-2.txt' in read mode with open('day19-2.txt', 'r') as f: vals = [] for line in f: line = line.strip() if len(line) == 0: continue if len(towels) == 0: towels = line.split(', ') else: patterns.append(line) print(""Number of ways to acheive patterns:"", get_num_achievable_patterns(towels, patterns))",python:3.9.21-slim 2024,19,2,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"def num_possible_patterns(pattern, towels, memo): if pattern == """": return 1 if pattern in memo: return memo[pattern] res = sum([num_possible_patterns(pattern[len(t):], towels, memo) if pattern.startswith(t) else 0 for t in towels]) memo[pattern] = res return res with open('input.txt') as f: lines = f.read().splitlines() towels = [s.strip() for s in lines[0].split("","")] patterns = lines[2:] print(sum([num_possible_patterns(p, towels, dict()) for p in patterns]))",python:3.9.21-slim 2024,19,2,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from functools import cache with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() towels_trie = {} for towel in input_text[0].split("", ""): inner_dict = towels_trie for letter in list(towel): if letter not in inner_dict: inner_dict[letter] = {} inner_dict = inner_dict[letter] inner_dict[None] = None @cache def pattern_possible(pattern): if not pattern: return 1 patterns_needed = [] trie = towels_trie for i, letter in enumerate(pattern): if letter in trie: trie = trie[letter] if None in trie: patterns_needed.append(pattern[i + 1 :]) else: break return sum(pattern_possible(sub_pattern) for sub_pattern in patterns_needed) print(sum(pattern_possible(pattern) for pattern in input_text[2:]))",python:3.9.21-slim 2024,19,2,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from typing import List, Tuple from collections import defaultdict from part1 import parse_input def count_ways_to_construct_design(design: str, towel_patterns: List[str]) -> int: """""" Counts the number of ways to construct a given design using a list of towel patterns. Args: design (str): The design string that needs to be constructed. towel_patterns (List[str]): A list of towel patterns that can be used to construct the design. Returns: int: The number of ways to construct the design using the given towel patterns. """""" n = len(design) dp = defaultdict(int) dp[0] = 1 # Base case: there's one way to construct an empty design for i in range(1, n + 1): for pattern in towel_patterns: if i >= len(pattern) and design[i - len(pattern):i] == pattern: dp[i] += dp[i - len(pattern)] return dp[n] def total_ways_to_construct_designs(towel_patterns: List[str], desired_designs: List[str]) -> int: """""" Calculate the total number of ways to construct each design in the desired designs list using the given towel patterns. Args: towel_patterns (List[str]): A list of available towel patterns. desired_designs (List[str]): A list of desired designs to be constructed. Returns: int: The total number of ways to construct all the desired designs using the towel patterns. """""" return sum(count_ways_to_construct_design(design, towel_patterns) for design in desired_designs) if __name__ == ""__main__"": file_path = 'input.txt' towel_patterns, desired_designs = parse_input(file_path) result = total_ways_to_construct_designs(towel_patterns, desired_designs) print(result)",python:3.9.21-slim 2024,19,2,"--- Day 19: Linen Layout --- Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. Could this finally be your chance to visit the onsen next door? Only one way to find out. After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: r, wr, b, g, bwu, rb, gb, br brwrr bggr gbbr rrbgbr ubwu bwurrg brgr bbrgwb The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: brwrr can be made with a br towel, then a wr towel, and then finally an r towel. bggr can be made with a b towel, two g towels, and then an r towel. gbbr can be made with a gb towel and then a br towel. rrbgbr can be made with r, rb, g, and br. ubwu is impossible. bwurrg can be made with bwu, r, r, and g. brgr can be made with br, g, and r. bbrgwb is impossible. In this example, 6 of the eight designs are possible with the available towel patterns. To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? Your puzzle answer was 267. --- Part Two --- The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. Here are all of the different ways the above example's designs can be made: brwrr can be made in two different ways: b, r, wr, r or br, wr, r. bggr can only be made with b, g, g, and r. gbbr can be made 4 different ways: g, b, b, r g, b, br gb, b, r gb, br rrbgbr can be made 6 different ways: r, r, b, g, b, r r, r, b, g, br r, r, b, gb, r r, rb, g, b, r r, rb, g, br r, rb, gb, r bwurrg can only be made with bwu, r, r, and g. brgr can be made in two different ways: b, r, g, r or br, g, r. ubwu and bbrgwb are still impossible. Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"from collections import defaultdict def nb_possible_arrangements(design: str, towels: list[str]) -> int: cache: defaultdict[str, int] = defaultdict(lambda: 0) cache[""""] = 1 for i in range(1, len(design) + 1): design_i = design[-i:] cache[design_i] = 0 for towel in towels: if design_i.startswith(towel): sub_design = design_i[len(towel) :] cache[design_i] += cache[sub_design] return cache[design] def main() -> None: towels: list[str] = [] designs: list[str] = [] with open(""input.txt"") as data: towels = data.readline().strip().split("", "") assert data.readline() == ""\n"" for line in data: designs.append(line.strip()) count = 0 for i, design in enumerate(designs): nb = nb_possible_arrangements(design, towels) count += nb print(count) if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,21,1,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from itertools import permutations keypadSequences = open('input.txt').read().splitlines() keypad = { '7': (0, 0), '8': (0, 1), '9': (0, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '1': (2, 0), '2': (2, 1), '3': (2, 2), '#': (3, 0), '0': (3, 1), 'A': (3, 2) } keypadBadPosition = (3,0) startKeypad = (3, 2) directionalpad = { '#': (0, 0), '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2) } directionalpadBadPosition = (0,0) startdirectionalpad = (0, 2) def getNumericPart(code): return ''.join([elem for elem in code if elem.isdigit()]) def getdirections(drow, dcol): res = [] if drow > 0: res.append('v'*drow) elif drow < 0: res.append('^'*abs(drow)) if dcol > 0: res.append('>'*dcol) elif dcol < 0: res.append('<'*abs(dcol)) return ''.join(res) def getPossiblePermutations(pos, directions, position): perms = set(permutations(directions)) validPerms = [] for perm in perms: if validatepath(pos, perm, position): validPerms.append(''.join(perm)) return validPerms def validatepath(pos, directions, position): _pos = pos for direction in directions: if direction == 'v': _pos = (_pos[0] + 1, _pos[1]) elif direction == '^': _pos = (_pos[0] - 1, _pos[1]) elif direction == '>': _pos = (_pos[0], _pos[1] + 1) elif direction == '<': _pos = (_pos[0], _pos[1] - 1) if _pos == position: return False return True def getDirectionToWriteCode(input): pos = startKeypad result = [] for elem in input: nextPos = keypad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, keypadBadPosition) if len(result) == 0: for path in validPaths: result.append(path + 'A') elif len(result) >= 1: temp = [] for res in result: for path in validPaths: temp.append(res + path + 'A') result = temp pos = nextPos return result def getDirectionToWriteDirection(input): pos = startdirectionalpad result = [] for elem in input: nextPos = directionalpad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition) if len(result) == 0: for path in validPaths: result.append(path + 'A') elif len(result) >= 1: temp = [] for res in result: for path in validPaths: temp.append(res + path + 'A') result = temp pos = nextPos min_length = min(len(r) for r in result) return [r for r in result if len(r) == min_length] def getDirectionToWriteDirectionSample(input): pos = startdirectionalpad result = [] for elem in input: nextPos = directionalpad[elem] drow = nextPos[0] - pos[0] dcol = nextPos[1] - pos[1] directions = getdirections(drow, dcol) validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition)[0] result.append(validPaths) result.append('A') pos = nextPos return ''.join(result) def calculateComplexity(code): sol1 = getDirectionToWriteCode(code) sol2 = [elem for sol in sol1 for elem in getDirectionToWriteDirection(sol)] sol3 = [getDirectionToWriteDirectionSample(elem) for elem in sol2] print(sol3[0]) print(sol2[0]) print(sol1[0]) print(code) min_length = min(len(r) for r in sol3) num = getNumericPart(code) print(f""Code: Numeric: {num}, minimum length: {min_length}"") return min_length * int(num) total = 0 for code in keypadSequences: score = calculateComplexity(code) total += score print() print(total) # >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A # <A>^AvAA<^A>A<>^AvA^A^A<^A>AAvA^A<A>^AAAvA<^A>A # code = '029A' # sol1 = getDirectionToWriteCode(code) # sol2 = getDirectionToWriteDirection(sol1) # sol3 = getDirectionToWriteDirection(sol2) # print(sol3) # print(sol2) # print(sol1) # print(code) # print(calculateComplexity(""029A""))",python:3.9.21-slim 2024,21,1,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"NUMS = { '0': (3, 1), '1': (2, 0), '2': (2, 1), '3': (2, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '7': (0, 0), '8': (0, 1), '9': (0, 2), 'A': (3, 2), '': (3, 0) } ARROWS = { '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2), '': (0, 0) } DIR_TO_ARROW_MAP = { (-1, 0): '^', (1, 0): 'v', (0, -1): '<', (0, 1): '>' } def get_shortest(keys, sequence): path = [] for i in range(len(sequence) - 1): cur, target = keys[sequence[i]], keys[sequence[i + 1]] next_path = [] dirs = [] for y in range(cur[1] - 1, target[1] - 1, -1): next_path.append((cur[0], y)) dirs.append((0, -1)) for x in range(cur[0] + 1, target[0] + 1): next_path.append((x, cur[1])) dirs.append((1, 0)) for x in range(cur[0] - 1, target[0] - 1, -1): next_path.append((x, cur[1])) dirs.append((-1, 0)) for y in range(cur[1] + 1, target[1] + 1): next_path.append((cur[0], y)) dirs.append((0, 1)) if keys[''] in next_path: dirs = list(reversed(dirs)) path += [DIR_TO_ARROW_MAP[d] for d in dirs] + ['A'] return """".join(path) with open('input.txt') as f: lines = f.read().splitlines() total_complexity = 0 for line in lines: l1 = get_shortest(NUMS, 'A' + line) l2 = get_shortest(ARROWS, 'A' + l1) l3 = get_shortest(ARROWS, 'A' + l2) total_complexity += int(line[0:-1]) * len(l3) print(total_complexity)",python:3.9.21-slim 2024,21,1,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from abc import ABC import argparse from functools import cache from itertools import product from typing import Optional g_verbose = False CHR_A = ord('A') UP = ord('^') DOWN = ord('v') LEFT = ord('<') RIGHT = ord('>') CHR_0 = ord('0') CHR_1 = ord('1') CHR_2 = ord('2') CHR_3 = ord('3') CHR_4 = ord('4') CHR_5 = ord('5') CHR_6 = ord('6') CHR_7 = ord('7') CHR_8 = ord('8') CHR_9 = ord('9') def get_dir_h(dx: int) -> int: return LEFT if dx < 0 else RIGHT def get_dir_v(dy: int) -> int: return UP if dy < 0 else DOWN class RobotPad(ABC): id: int = 0 dir_cache: dict[tuple[int, int], list[list[int]]] pos_cache: dict[tuple[int, int], int] child: Optional['RobotPad'] = None @cache def cost_press_once(self, snapshot: tuple[int, ...]): my_id = self.id if not self.child: assert len(snapshot) == 1 return 1, snapshot g_verbose and print(f'{"" "" * my_id}bot #{my_id} request parent press') cost_moving, new_snapshot = self.child.cost_moving(CHR_A, snapshot[1:]) cost_press, new_snapshot = self.child.cost_press_once(new_snapshot) return cost_moving + cost_press, (snapshot[0], *new_snapshot) @cache def cost_moving(self, target_button: int, snapshot: tuple[int, ...]): my_id = self.id current_button = snapshot[0] g_verbose and print(f'{"" "" * my_id}bot #{my_id} plan {chr(current_button)} -> {chr(target_button)}') if current_button == target_button: g_verbose and print(f'{"" "" * my_id}bot #{my_id} not moving, already at {chr(target_button)}') return 0, snapshot # Last layer distance = self.pos_cache[current_button, target_button] if not self.child: g_verbose and print(f'{"" "" * my_id}bot #{my_id} move to {chr(target_button)}, cost={distance}') assert len(snapshot) == 1 return distance, (target_button,) # Move parent node to the direction I want tracking = [] for possible_routes in self.dir_cache[current_button, target_button]: route_cost = 0 route_snapshot = snapshot[1:] for next_direction in possible_routes: cost_moving, route_snapshot = self.child.cost_moving(next_direction, route_snapshot) cost_press, route_snapshot = self.child.cost_press_once(route_snapshot) route_cost += cost_moving + cost_press tracking.append((route_cost, (target_button, *route_snapshot))) best_cost, best_snapshot = min(tracking, key=lambda x: x[0]) g_verbose and print(f'{"" "" * my_id}bot #{my_id} move to {chr(target_button)}, cost={best_cost}') return best_cost, best_snapshot def move(self, dst: int, snapshot: tuple[int, ...]): return self.cost_moving(dst, snapshot) class NumPad(RobotPad): def __init__(self, bot_id: int): self.id = bot_id self.board = [ [0x37, 0x38, 0x39], [0x34, 0x35, 0x36], [0x31, 0x32, 0x33], [0x00, 0x30, 0x41] ] self.pos_cache = {} self.board_lookup = {value: (x, y) for y, row in enumerate(self.board) for x, value in enumerate(row) if value} dir_cache: dict[tuple[int, int], list[list[int]]] = {} for ((a, (x1, y1)), (b, (x2, y2))) in product(self.board_lookup.items(), repeat=2): if a == b: continue # Find the direction of move from a to b dx = x2 - x1 dy = y2 - y1 x_count = abs(dx) y_count = abs(dy) # Only move in one direction if dx == 0 or dy == 0: dir_cache[a, b] = [[get_dir_h(dx) if dx else get_dir_v(dy)] * (x_count + y_count)] elif a in (CHR_0, CHR_A) and b in (CHR_1, CHR_4, CHR_7): # Can only move up and then left dir_cache[a, b] = [[UP] * y_count + [LEFT] * x_count] elif a in (CHR_1, CHR_4, CHR_7) and b in (CHR_0, CHR_A): # Can only move right and then down dir_cache[a, b] = [[RIGHT] * x_count + [DOWN] * y_count] else: # Can move both horizontally and vertically, any order dir_h = get_dir_h(dx) dir_v = get_dir_v(dy) dir_cache[a, b] = [[dir_h] * x_count + [dir_v] * y_count, [dir_v] * y_count + [dir_h] * x_count] self.pos_cache[a, b] = abs(dx) + abs(dy) self.dir_cache = dir_cache class DirectionPad(RobotPad): def __init__(self, bot_id: int): self.id = bot_id self.board = [ [0x00, UP, CHR_A], [LEFT, DOWN, RIGHT], ] self.board_lookup = {value: (x, y) for y, row in enumerate(self.board) for x, value in enumerate(row) if value} self.pos_cache = {} dir_cache: dict[tuple[int, int], list[list[int]]] = {} for ((a, (x1, y1)), (b, (x2, y2))) in product(self.board_lookup.items(), repeat=2): # Find the direction of move from a to b dx = x2 - x1 dy = y2 - y1 self.pos_cache[a, b] = abs(dx) + abs(dy) x_count = abs(dx) y_count = abs(dy) # Only move in one direction if dx == 0 or dy == 0: dir_cache[a, b] = [[get_dir_h(dx) if dx else get_dir_v(dy)] * (x_count + y_count)] elif a == LEFT and b in (UP, CHR_A): # Can only move right and then UP dir_cache[a, b] = [[RIGHT] * x_count + [UP] * y_count] elif a in (UP, CHR_A) and b == LEFT: # Can only move down and then left dir_cache[a, b] = [[DOWN] * y_count + [LEFT] * x_count] else: # Can move both horizontally and vertically, any order dir_h = get_dir_h(dx) dir_v = get_dir_v(dy) dir_cache[a, b] = [[dir_h] * x_count + [dir_v] * y_count, [dir_v] * y_count + [dir_h] * x_count] self.dir_cache = dir_cache def solve_ex(codes: list[str], count: int) -> int: root = NumPad(0) node = root for i in range(count): bot = DirectionPad(i + 1) node.child = bot node = bot snapshot_init = tuple([CHR_A] * (count + 1)) result = 0 for code in codes: snapshot = snapshot_init total_cost = 0 for current_chr in map(ord, code): prev_char = snapshot[0] cost, snapshot = root.cost_moving(current_chr, snapshot) cost_press, snapshot = root.cost_press_once(snapshot) g_verbose and print( f""** move {chr(prev_char)} -> {chr(current_chr)} cost={cost + cost_press} pos={''.join(map(chr, snapshot))}"") total_cost += cost + cost_press numeric_part = int(code[:-1]) print(f""{code} -> {total_cost} * {numeric_part}"") result += total_cost * numeric_part return result def solve(input_path: str, /, **_kwargs): with open(input_path, ""r"", encoding='utf-8') as file: input_text = file.read().strip().replace('\r', '').splitlines() p1 = solve_ex(input_text, 2) print(f'p1: {p1}') def main(): global g_verbose parser = argparse.ArgumentParser() parser.add_argument(""input"", nargs=""?"", default=""sample.txt"") parser.add_argument(""-v"", ""--verbose"", action=""store_true"") parser.add_argument(""--threshold"", type=int, default=50, help=""Threshold (p2)"") args = parser.parse_args() g_verbose = args.verbose solve(args.input) if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,21,1,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"import functools from typing import List, Tuple, Optional # Define the number pad and the direction pad number_pad = [ ""789"", ""456"", ""123"", "" 0A"" ] direction_pad = [ "" ^A"", """" ] def parse_input(file_path: str) -> List[Tuple[str, int]]: """""" Parses the input file and returns a list of tuples. Each tuple contains a string (the stripped line) and an integer (the first three characters of the line). Args: file_path (str): The path to the input file. Returns: List[Tuple[str, int]]: A list of tuples where each tuple contains a string and an integer. """""" with open(file_path) as file: return [(line.strip(), int(line[:3])) for line in file] def find_position(pad: List[str], char: str) -> Optional[Tuple[int, int]]: """""" Find the position of a character in a 2D list (pad). Args: pad (List[str]): A 2D list representing the pad where each element is a string. char (str): The character to find in the pad. Returns: Optional[Tuple[int, int]]: A tuple containing the x and y coordinates of the character if found, otherwise None. """""" for y, row in enumerate(pad): for x, cell in enumerate(row): if cell == char: return x, y return None def generate_path(pad: List[str], from_char: str, to_char: str) -> str: """""" Generate the shortest path from `from_char` to `to_char` in the given pad. The path is represented as a string of direction changes: - '<' for left - '>' for right - '^' for up - 'v' for down - 'A' for arrival at the target position Args: pad (List[str]): A 2D list representing the pad where each element is a character. from_char (str): The character representing the starting position. to_char (str): The character representing the target position. Returns: str: The shortest path from `from_char` to `to_char` based on the number of direction changes. """""" from_x, from_y = find_position(pad, from_char) to_x, to_y = find_position(pad, to_char) def move(x: int, y: int, path: str): # If the current position is the target position, yield the path with 'A' appended if (x, y) == (to_x, to_y): yield path + 'A' # Move left if possible and the target is to the left if to_x < x and pad[y][x - 1] != ' ': yield from move(x - 1, y, path + '<') # Move up if possible and the target is above if to_y < y and pad[y - 1][x] != ' ': yield from move(x, y - 1, path + '^') # Move down if possible and the target is below if to_y > y and pad[y + 1][x] != ' ': yield from move(x, y + 1, path + 'v') # Move right if possible and the target is to the right if to_x > x and pad[y][x + 1] != ' ': yield from move(x + 1, y, path + '>') # Return the shortest path based on the number of direction changes return min(move(from_x, from_y, """"), key=lambda p: sum(a != b for a, b in zip(p, p[1:]))) @functools.lru_cache(None) def solve(sequence: str, level: int, max_level: int = 2) -> int: """""" Solve the problem recursively. Args: sequence (str): The input sequence to process. level (int): The current recursion level. max_level (int, optional): The maximum recursion depth. Defaults to 2. Returns: int: The result of the recursive computation. """""" if level > max_level: return len(sequence) pad = direction_pad if level else number_pad return sum(solve(generate_path(pad, from_char, to_char), level + 1, max_level) for from_char, to_char in zip('A' + sequence, sequence)) if __name__ == ""__main__"": input_data = parse_input('input.txt') result = sum(solve(sequence, 0) * multiplier for sequence, multiplier in input_data) print(result)",python:3.9.21-slim 2024,21,1,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"from functools import cache with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() @cache def num_keypad_paths(start, end): output = [] x_diff = abs(end[0] - start[0]) y_diff = abs(end[1] - start[1]) horiz_char = "">"" if end[0] > start[0] else ""<"" vert_char = ""v"" if end[1] > start[1] else ""^"" for path in { tuple([horiz_char] * x_diff + [vert_char] * y_diff), tuple([vert_char] * y_diff + [horiz_char] * x_diff), }: if not ( (start == (0, 0) and path[:3] == (""v"", ""v"", ""v"")) or (start == (0, 1) and path[:2] == (""v"", ""v"")) or (start == (0, 2) and path[:1] == (""v"",)) or (start == (1, 3) and path[:1] == (""<"",)) or (start == (2, 3) and path[:2] == (""<"", ""<"")) ): output.append(list(path) + [""A""]) return output @cache def dir_keypad_paths(start, end): output = [] x_diff = abs(end[0] - start[0]) y_diff = abs(end[1] - start[1]) horiz_char = "">"" if end[0] > start[0] else ""<"" vert_char = ""v"" if end[1] > start[1] else ""^"" for path in { tuple([horiz_char] * x_diff + [vert_char] * y_diff), tuple([vert_char] * y_diff + [horiz_char] * x_diff), }: if not ( (start == (1, 0) and path[:1] == (""<"",)) or (start == (2, 0) and path[:2] == (""<"", ""<"")) or (start == (0, 1) and path[:1] == (""^"",)) ): output.append(list(path) + [""A""]) return output num_keypad = { ""7"": (0, 0), ""8"": (1, 0), ""9"": (2, 0), ""4"": (0, 1), ""5"": (1, 1), ""6"": (2, 1), ""1"": (0, 2), ""2"": (1, 2), ""3"": (2, 2), ""0"": (1, 3), ""A"": (2, 3), } directional_keypad = {""^"": (1, 0), ""A"": (2, 0), ""<"": (0, 1), ""v"": (1, 1), "">"": (2, 1)} total = 0 for code in input_text: current_pos = (2, 3) solutions = [[]] for character in code: new_pos = num_keypad[character] solutions = [ solution + path for solution in solutions for path in num_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_2_outer = [] for solution in solutions: current_pos = (2, 0) solutions_2 = [[]] for character in solution: new_pos = directional_keypad[character] solutions_2 = [ partial_solution + path for partial_solution in solutions_2 for path in dir_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_2_outer += solutions_2 solutions_3_outer = [] for solution in solutions_2_outer: current_pos = (2, 0) solutions_3 = [[]] for character in solution: new_pos = directional_keypad[character] solutions_3 = [ partial_solution + path for partial_solution in solutions_3 for path in dir_keypad_paths(current_pos, new_pos) ] current_pos = new_pos solutions_3_outer += solutions_3 total += min(len(x) for x in solutions_3_outer) * int(code[:3]) print(total)",python:3.9.21-slim 2024,21,2,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"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:3.9.21-slim 2024,21,2,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"from collections import defaultdict, Counter NUMS = { '0': (3, 1), '1': (2, 0), '2': (2, 1), '3': (2, 2), '4': (1, 0), '5': (1, 1), '6': (1, 2), '7': (0, 0), '8': (0, 1), '9': (0, 2), 'A': (3, 2), '': (3, 0) } ARROWS = { '^': (0, 1), 'A': (0, 2), '<': (1, 0), 'v': (1, 1), '>': (1, 2), '': (0, 0) } DIR_TO_ARROW_MAP = { (-1, 0): '^', (1, 0): 'v', (0, -1): '<', (0, 1): '>' } memo = dict() def get_shortest(keys, sequence): path = [] for i in range(len(sequence) - 1): cur, target = keys[sequence[i]], keys[sequence[i + 1]] next_path = [] dirs = [] for y in range(cur[1] - 1, target[1] - 1, -1): next_path.append((cur[0], y)) dirs.append((0, -1)) for x in range(cur[0] + 1, target[0] + 1): next_path.append((x, cur[1])) dirs.append((1, 0)) for x in range(cur[0] - 1, target[0] - 1, -1): next_path.append((x, cur[1])) dirs.append((-1, 0)) for y in range(cur[1] + 1, target[1] + 1): next_path.append((cur[0], y)) dirs.append((0, 1)) if keys[''] in next_path: dirs = list(reversed(dirs)) to_append = [DIR_TO_ARROW_MAP[d] for d in dirs] + ['A'] path += to_append return """".join(path).split(""A"")[0:-1] def count_parts(path): return Counter([s +""A"" for s in path]) with open('input.txt') as f: lines = f.read().splitlines() total_complexity = 0 for line in lines: counts = count_parts(get_shortest(NUMS, 'A' + line)) for i in range(25): next_counts = defaultdict(int) for seq, count in counts.items(): for k, v in count_parts(get_shortest(ARROWS, 'A' + seq)).items(): next_counts[k] += count * v counts = next_counts length = sum([len(k) * v for k, v in counts.items()]) total_complexity += int(line[0:-1]) * length print(total_complexity)",python:3.9.21-slim 2024,21,2,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"import functools with open(""21.txt"") as i: input = [x.strip() for x in i.readlines()] test_data = """"""029A 980A 179A 456A 379A"""""".split(""\n"") # input = test_data # +---+---+---+ # | 7 | 8 | 9 | # +---+---+---+ # | 4 | 5 | 6 | # +---+---+---+ # | 1 | 2 | 3 | # +---+---+---+ # | 0 | A | # +---+---+ numeric_keys = { ""7"": (0, 0), ""8"": (1, 0), ""9"": (2, 0), ""4"": (0, 1), ""5"": (1, 1), ""6"": (2, 1), ""1"": (0, 2), ""2"": (1, 2), ""3"": (2, 2), ""0"": (1, 3), ""A"": (2, 3), } # +---+---+ # | ^ | A | #+---+---+---+ #| < | v | > | #+---+---+---+ directional_keys = { ""^"": (1, 0), ""A"": (2, 0), ""<"": (0, 1), ""v"": (1, 1), "">"": (2,1) } allowed_num_pos = [v for v in numeric_keys.values()] allowed_dir_pos = [v for v in directional_keys.values()] pos = (2,3) x, y = pos def find_keystrokes(src, target, directional): if src == target: return [""A""] if not directional and not src in allowed_num_pos: return [] if directional and not src in allowed_dir_pos: return [] x1, y1 = src x2, y2 = target res = [] if x1""+s for s in find_keystrokes((x1+1, y1), target, directional)]) elif x1>x2: res.extend([""<""+s for s in find_keystrokes((x1-1, y1), target, directional)]) if y1y2: res.extend([""^""+s for s in find_keystrokes((x1, y1-1), target, directional)]) return res @functools.cache def find_shortest_to_click(a, b, depth=2): # Assume we start at A always? opts = find_keystrokes(directional_keys[a], directional_keys[b], True) if depth == 1: return min([len(x) for x in opts]) tmps = [] for o in opts: tmp = [] tmp.append(find_shortest_to_click(""A"", o[0], depth-1)) for i in range(1, len(o)): tmp.append(find_shortest_to_click(o[i-1], o[i], depth-1)) tmps.append(sum(tmp)) return min(tmps) def find_shortest(code, levels): pos = numeric_keys[""A""] shortest = 0 for key in code: possible_key_sequences = find_keystrokes(pos, numeric_keys[key], False) tmps = [] for sequence in possible_key_sequences: tmp = [] tmp.append(find_shortest_to_click(""A"", sequence[0], levels)) for i in range(1, len(sequence)): tmp.append(find_shortest_to_click(sequence[i-1], sequence[i], levels)) tmps.append(sum(tmp)) pos = numeric_keys[key] shortest += min(tmps) return shortest def find_total_complexity(codes, levels): complexities = [] for code in input: s = find_shortest(code, levels) complexities.append(s*int(code[:-1])) return sum(complexities) print(find_total_complexity(input, 25))",python:3.9.21-slim 2024,21,2,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"#!/usr/bin/env python3 import re from collections import deque from itertools import product myfile = open(""21.in"", ""r"") lines = myfile.read().strip().splitlines() myfile.close() part_two = 0 # fmt: off num_pad = { (0, 0): ""7"", (1, 0): ""8"", (2, 0): ""9"", (0, 1): ""4"", (1, 1): ""5"", (2, 1): ""6"", (0, 2): ""1"", (1, 2): ""2"", (2, 2): ""3"", (1, 3): ""0"", (2, 3): ""A"", } num_pad_t = {v: k for k, v in num_pad.items()} dir_pad = { (1, 0): ""^"", (2, 0): ""A"", (0, 1): ""<"", (1, 1): ""v"", (2, 1): "">"", } dir_pad_t = {v: k for k, v in dir_pad.items()} # fmt: on button_dirs = {""<"": (-1, 0), "">"": (1, 0), ""^"": (0, -1), ""v"": (0, 1)} def dfs(start, end, use_dir_pad=True): key_pad = dir_pad if use_dir_pad else num_pad sequences = set() seen = set() q = deque([("""", start)]) while q: sequence, pos = q.popleft() seen.add(pos) if pos == end: sequences.add(sequence + ""A"") continue buttons = [""<"", ""^"", ""v"", "">""] for btn in buttons: d_x, d_y = button_dirs[btn] next_pos = (pos[0] + d_x, pos[1] + d_y) if next_pos not in seen and next_pos in key_pad: q.append((sequence + btn, next_pos)) min_len = min(len(x) for x in sequences) return {x for x in sequences if len(x) == min_len} def get_sequences(sequence, use_dir_pad=True): key_pad_t = dir_pad_t if use_dir_pad else num_pad_t sub_sequences = [] start = key_pad_t[""A""] for c in sequence: end = key_pad_t[c] sub_sequences.append(dfs(start, end, use_dir_pad)) start = end sequences = {"""".join(x) for x in product(*sub_sequences)} min_len = min(len(x) for x in sequences) return {x for x in sequences if len(x) == min_len} memo = {} def solve(sequence, robots, is_code=False): if robots == 0: return len(sequence) if (sequence, robots) not in memo: total = 0 sub_sequences = list(re.findall(r"".*?A"", sequence)) for sub_seq in sub_sequences: total += min( solve(s, robots - 1) for s in get_sequences(sub_seq, not is_code) ) memo[(sequence, robots)] = total return memo[(sequence, robots)] for code in lines: numeric_code = int(code[:-1]) part_two += solve(code, 26, is_code=True) * numeric_code print(""Part Two:"", part_two)",python:3.9.21-slim 2024,21,2,"--- Day 21: Keypad Conundrum --- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: +---+---+---+ | 7 | 8 | 9 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 0 | A | +---+---+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: +---+---+ | ^ | A | +---+---+---+ | < | v | > | +---+---+---+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: < to move the arm from A (its initial position) to 0. A to push the 0 button. ^A to move the arm to the 2 button and push it. >^^A to move the arm to the 9 button and push it. vvvA to move the arm to the A button and push it. In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A v<>^AAvA<^AA>A^A ^^AvvvA 029A In summary, there are the following keypads: One directional keypad that you are using. Two directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. To unlock the door, five codes will need to be typed on its numeric keypad. For example: 029A 980A 179A 456A 379A For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: 029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A 980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA 179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A 456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A 379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. The complexity of a single code (like 029A) is equal to the result of multiplying these two values: The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? Your puzzle answer was 157908. --- Part Two --- Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. This time, many more robots are involved. In summary, there are the following keypads: One directional keypad that you are using. 25 directional keypads that robots are using. One numeric keypad (on a door) that a robot is using. The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. The door codes are the same this time around; only the number of robots and directional keypads has changed. Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"#day 21 import os from itertools import pairwise from functools import cache def reader(): return open(f""input.txt"", 'r').read().splitlines() def getPT(G, chars): P = {c: (i, j) for i, r in enumerate(G) for j, c in enumerate(r)} T = {c1: {c2: set() for c2 in chars} for c1 in chars} for c1 in T: for c2 in T[c1]: (x1, y1), (x2, y2) = P[c1], P[c2] v, vc = 'v' if x1 < x2 else '^', abs(x2 - x1) h, hc = '>' if y1 < y2 else '<', abs(y2 - y1) if G[x1][y2] in chars: T[c1][c2].add(h * hc + v * vc) if G[x2][y1] in chars: T[c1][c2].add(v * vc + h * hc) return P, T def part2(): f = reader() G0 = [ ['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['#', '0', 'A'], ] GC = [ ['#', '^', 'A'], ['<', 'v', '>'] ] _, G0T = getPT(G0, '0123456789A') _, GCT = getPT(GC, '<^>vA') def r(T, s, i=0, c='A'): return [[t1] + t2 for t1 in T[c][s[i]] for t2 in r(T, s, i + 1, s[i])] if i < len(s) else [[]] @cache def count(c1, c2, M): return min(sum(count(cc1, cc2, M - 1) for cc1, cc2 in pairwise('A' + t + 'A')) for t in GCT[c1][c2]) if M > 0 else 1 ans = 0 for s0 in f: l = min(sum(count(cc1, cc2, 25) for cc1, cc2 in pairwise('A' + t + 'A')) for t in map(lambda l: 'A'.join(l), r(G0T, s0))) ans += l * int(s0[:-1]) print(ans) part2()",python:3.9.21-slim 2024,23,1,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"from collections import defaultdict with open('input.txt') as f: lines = f.read().splitlines() connections = defaultdict(set) pairs = [tuple(line.split(""-"")) for line in lines] for pair in pairs: connections[pair[0]].add(pair[1]) connections[pair[1]].add(pair[0]) trios = set() for pair in pairs: intersection = connections[pair[0]].intersection(connections[pair[1]]) for val in intersection: trios.add(tuple(sorted((pair[0], pair[1], val)))) trios_with_t = [trio for trio in trios if any(v.startswith(""t"") for v in trio)] print(len(trios_with_t))",python:3.9.21-slim 2024,23,1,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"import argparse import re from collections import defaultdict from typing import Iterable class Network: completed_networks: defaultdict[int, set[tuple[str, ...]]] nodes: defaultdict[str, set[str]] def __init__(self, text: str): cache: defaultdict[str, set[str]] = defaultdict(set) for m in re.finditer(r'(..)-(..)', text): a = m.group(1) b = m.group(2) cache[a].add(b) cache[b].add(a) self.nodes = cache self.completed_networks = defaultdict(set) def get_names(self): return self.nodes.keys() def get_largest_networks(self): largest_network_length = max(*self.completed_networks.keys()) return list(self.completed_networks[largest_network_length]) def get_complete_network_with_n_nodes(self, n: int): return list(self.completed_networks[n]) def build_network_for(self, names: Iterable[str]): networks = self.completed_networks for name in names: name_pool = set(self.nodes[name]) depth = 1 work: set[tuple[str, ...]] = {(name,)} while work: next_work = set() for network in work: # Don't bother with already explored networks if network in networks[depth]: continue networks[depth].add(network) for next_name in name_pool.difference(network): if self.nodes[next_name].issuperset(network): next_work.add(tuple(sorted({*network, next_name}))) depth += 1 work = next_work def solve(input_path: str, /, **_kwargs): with open(input_path, ""r"", encoding='utf-8') as file: input_text = file.read().strip().replace('\r', '') network = Network(input_text) names_with_t = [name for name in network.get_names() if name.startswith('t')] network.build_network_for(names_with_t) p1 = len(network.get_complete_network_with_n_nodes(3)) print(f'p1 = {p1}') largest_networks = network.get_largest_networks() assert len(largest_networks) == 1, ""p2 solution should have a single, unique answer"" p2 = ','.join(largest_networks[0]) print(f'p2 = {p2}') def main(): parser = argparse.ArgumentParser() parser.add_argument(""input"", nargs=""?"", default=""sample.txt"") parser.add_argument(""-v"", ""--verbose"", action=""store_true"") args = parser.parse_args() solve(args.input, verbose=args.verbose) if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,23,1,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"from collections import defaultdict with open(""./day_23.in"") as fin: lines = fin.read().strip().split(""\n"") adj = defaultdict(list) for line in lines: a, b = line.split(""-"") adj[a].append(b) adj[b].append(a) triangles = set() for a in dict(adj): for i in adj[a]: for j in adj[a]: if j in adj[i]: triangles.add(tuple(sorted([a, i, j]))) ans = 0 for a, b, c in triangles: if ""t"" in [a[0], b[0], c[0]]: ans += 1 print(ans)",python:3.9.21-slim 2024,23,1,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"def readfile(): file_name = ""23.txt"" mapping = {} with open(file_name) as f: tuples = [tuple(line.strip().split(""-"")) for line in f.readlines()] # Add reverse order as well tuples += [(i[1], i[0]) for i in tuples] # Map all computers to which they are connected for key, val in tuples: if key in mapping: mapping[key].append(val) else: mapping[key] = [val] return mapping def make_mapping_part1(mapping, computer, depth, lan_party, lan_parties): # We have reached 3 computers so make sure that we have closed the loop if depth == 0: if lan_party[0] == lan_party[-1] and any( [i.startswith(""t"") for i in lan_party] ): lan_parties.add(tuple(sorted(lan_party[:3]))) return # Check all computers that are connected to the current one for val in mapping[computer]: lan_party.append(val) make_mapping_part1(mapping, val, depth - 1, lan_party, lan_parties) del lan_party[-1] def part1(mapping): lan_parties = set() # Find all lan parties with exactly 3 computers for computer in mapping: make_mapping_part1(mapping, computer, 3, [computer], lan_parties) print(len(lan_parties)) if __name__ == ""__main__"": test_file = False mapping = readfile() print(""Answer to part 1:"") part1(mapping)",python:3.9.21-slim 2024,23,1,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"#!/usr/bin/env python3 from collections import defaultdict from itertools import combinations myfile = open(""23.in"", ""r"") lines = myfile.read().strip().splitlines() myfile.close() conns = defaultdict(set) part_one = 0 for line in lines: a, b = line.split(""-"") conns[a].add(b) conns[b].add(a) trios = set() for comp, others in conns.items(): pairs = combinations(others, 2) for a, b in pairs: if b in conns[a]: trios.add(frozenset([comp, a, b])) for t in trios: if any(x.startswith(""t"") for x in t): part_one += 1 print(""Part One:"", part_one)",python:3.9.21-slim 2024,23,2,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? Your puzzle answer was 1194. --- Part Two --- There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: ka-co ta-co de-co ta-ka de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. What is the password to get into the LAN party?","bd,bu,dv,gl,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:3.9.21-slim 2024,23,2,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? Your puzzle answer was 1194. --- Part Two --- There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: ka-co ta-co de-co ta-ka de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. What is the password to get into the LAN party?","bd,bu,dv,gl,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:3.9.21-slim 2024,23,2,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? Your puzzle answer was 1194. --- Part Two --- There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: ka-co ta-co de-co ta-ka de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. What is the password to get into the LAN party?","bd,bu,dv,gl,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:3.9.21-slim 2024,23,2,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? Your puzzle answer was 1194. --- Part Two --- There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: ka-co ta-co de-co ta-ka de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. What is the password to get into the LAN party?","bd,bu,dv,gl,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:3.9.21-slim 2024,23,2,"--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? Your puzzle answer was 1194. --- Part Two --- There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: ka-co ta-co de-co ta-ka de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. What is the password to get into the LAN party?","bd,bu,dv,gl,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:3.9.21-slim 2024,24,1,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"import operator from pprint import pprint import re with open(""input24.txt"") as i: input = [x.strip() for x in i.readlines()] test_data_1 = """"""x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02"""""".split(""\n"") test_data_2 = """"""x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj"""""".split(""\n"") # input = test_data_1 # input = test_data_2 wires = {} i = 0 while input[i]!="""": n, v = input[i].split("": "") wires[n] = int(v) i += 1 operator_lookup = { ""AND"": operator.and_, ""OR"": operator.or_, ""XOR"": operator.xor } gates = {} for l in input[i+1:]: l, op, r, o = re.match(r""(.+) (AND|OR|XOR) (.+) -> (.+)"", l).groups() gates[o] = (l, operator_lookup[op], r) def get_bit(name: str) -> int: if name in wires.keys(): return wires[name] l, op, r = gates[name] res = op(get_bit(l), get_bit(r)) return res bit_count = max([int(x[1:]) for x in gates.keys() if x.startswith(""z"")])+1 res = 0 for i in range(bit_count-1,-1, -1): b = get_bit(f""z{i:02}"") res = (res<<1) | b print(res) def swap_gates(a, b): t = gates[a] gates[a] = gates[b] gates[b] = t def add(a: int, b: int) -> int: for i in range(bit_count): wires[f""x{i:02}""] = (a>>i)%2 wires[f""y{i:02}""] = (b>>i)%2 res = 0 try: for i in range(bit_count-1,-1, -1): c = get_bit(f""z{i:02}"") res = (res<<1) | c except RecursionError: raise ""Loop detected"" return res def find_gate(a, op, b): for k, v in gates.items(): aa, opp, bb = v if ((a==aa and b==bb) or (a==bb and b==aa)) and opp==op: return k return None def find_gate2(a, op): for k, v in gates.items(): if (v[0]==a or v[2]==a) and op==v[1]: return k print() # f[i] = x[i] xor y[i] # g[i] = x[i] and y[i] # z[i] = (x[i] xor y[i]) xor r[i-1] # z[i] = f[i] xor r[i-1] # r[i] = (x[i] and y[i]) or ((x[i] xor y[i]) and r[i-1]) # r[i] = g[i] or (f[i] and r[i-1]) remainders = [find_gate(""x00"", operator.and_, ""y00"")] f = [find_gate(f""x{i:02}"", operator.xor, f""y{i:02}"") for i in range(0, bit_count)] g = [find_gate(f""x{i:02}"", operator.and_, f""y{i:02}"") for i in range(0, bit_count)] swaps = [] for i in range(1, bit_count-1): e = find_gate2(f[i], operator.xor) if e is not None and e!=f""z{i:02}"": swaps.append((e, f""z{i:02}"")) elif e is None: print(f""No swap found for bit {i}..."") # e = find_gate2(remainders[i-1], operator.xor) # print(e) # print(remainders) # swaps.append() # x = find_gate2(f[i], operator.and_) # rr = find_gate2(g[i], operator.or_) # print(x, rr) remainders.append(find_gate2(g[i], operator.or_)) print("","".join(sorted([x for y in swaps for x in y])))",python:3.9.21-slim 2024,24,1,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() states = {} z_wires = [] XOR = [] OR = [] AND = [] for line in input_text: if "":"" in line: wire, value = line.split("": "") states[wire] = bool(int(value)) elif ""XOR"" in line: wires, output = line.split("" -> "") wire1, wire2 = wires.split("" XOR "") XOR.append((wire1, wire2, output)) if output[0] == ""z"": z_wires.append(output) elif ""OR"" in line: wires, output = line.split("" -> "") wire1, wire2 = wires.split("" OR "") OR.append((wire1, wire2, output)) if output[0] == ""z"": z_wires.append(output) elif ""AND"" in line: wires, output = line.split("" -> "") wire1, wire2 = wires.split("" AND "") AND.append((wire1, wire2, output)) if output[0] == ""z"": z_wires.append(output) while not all(z in states for z in z_wires): for op_list, op in ((XOR, ""__xor__""), (OR, ""__or__""), (AND, ""__and__"")): new_list = [] for wire1, wire2, output in op_list: if states.get(wire1) is not None and states.get(wire2) is not None: states[output] = getattr(states[wire1], op)(states[wire2]) else: new_list.append((wire1, wire2, output)) op_list = new_list place = 0 total = 0 while f""z{place:02d}"" in states: total += int(states[f""z{place:02d}""]) << place place += 1 print(total)",python:3.9.21-slim 2024,24,1,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"wires = {} gates = [] with open(""day24-data.txt"") as f: initial = True for line in f.readlines(): if line == ""\n"": initial = False continue if initial: wires[line.split()[0].strip(':')] = int(line.split()[1]) else: gate = line.strip('\n').split() gates.append([gate[0], gate[1], gate[2], gate[4], False]) for gate in gates: if gate[0] not in wires: wires[gate[0]] = -1 if gate[2] not in wires: wires[gate[2]] = -1 all_done = False while not all_done: print('*', end='') all_done = True for gate in gates: if wires[gate[0]] != -1 and wires[gate[2]] != -1 and gate[4] == False: if gate[1] == ""AND"": wires[gate[3]] = 1 if wires[gate[0]] + wires[gate[2]] == 2 else 0 elif gate[1] == ""OR"": wires[gate[3]] = 1 if wires[gate[0]] + wires[gate[2]] >= 1 else 0 else: wires[gate[3]] = 1 if wires[gate[0]] != wires[gate[2]] else 0 gate[4] = True print('.', end='') elif gate[4] == False: all_done = False print() #print(sorted(wires.items())) #print(gates) output = {} for key, val in wires.items(): if key[0] == 'z': output[key] = val sorted_output = dict(sorted(output.items())) power = 0 dec = 0 for key, val in sorted_output.items(): print(key, val) dec += val * (2**power) power += 1 print(dec)",python:3.9.21-slim 2024,24,1,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"#!/usr/bin/python3 class Wire: def __init__(self, name, wire_val): self.name = name self.wire_val = wire_val class Gate: def __init__(self, logic:str, input_1:str, input_2:str): self.logic = logic self.input_1 = input_1 self.input_2 = input_2 def get_output(self, wire_dict:dict) -> str: if self.logic == ""AND"": return (""1"" if wire_dict[self.input_1].wire_val == ""1"" and wire_dict[self.input_2].wire_val == ""1"" else ""0"") elif self.logic == ""OR"": return (""1"" if wire_dict[self.input_1].wire_val == ""1"" or wire_dict[self.input_2].wire_val == ""1"" else ""0"") elif self.logic == ""XOR"": return (""1"" if wire_dict[self.input_1].wire_val != wire_dict[self.input_2].wire_val else ""0"") with open(""input.txt"") as file: wires = {} gates = {} for line in file: line = line.strip() if "":"" in line: wires[line.split("": "")[0]] = Wire(line.split("": "")[0], line.split("": "")[1]) elif ""->"" in line: gates[line.split()[4]] = Gate(line.split()[1], line.split()[0], line.split()[2]) while any(gate not in wires for gate in gates): for gate in gates: if (gates[gate].input_1 in wires.keys() and gates[gate].input_2 in wires.keys()): out_val = gates[gate].get_output(wires) wires[gate] = Wire(gate, out_val) z_wires = sorted([wires[wire].name for wire in wires if wires[wire].name.startswith(""z"")]) z_bits = """".join([wires[z].wire_val for z in z_wires[::-1]]) print('Decimal number output on the wires starting with ""z"":', int(z_bits, 2))",python:3.9.21-slim 2024,24,1,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"#!/usr/bin/env python3 from collections import deque myfile = open(""24.in"", ""r"") lines = myfile.read().strip().split(""\n\n"") myfile.close() in_vals, out_vals = lines[0].splitlines(), lines[1].splitlines() wires = {} for line in in_vals: wire, val = line.split("": "") wires[wire] = int(val) q = deque(out_vals) while q: curr = q.popleft() wires_in, out_wire = curr.split("" -> "") left, op, right = wires_in.split("" "") if left not in wires or right not in wires: q.append(curr) continue result = -1 if op == ""XOR"": result = wires[left] ^ wires[right] elif op == ""OR"": result = wires[left] | wires[right] elif op == ""AND"": result = wires[left] & wires[right] wires[out_wire] = result x_wires, y_wires, z_wires = [], [], [] for wire in wires.keys(): if ""x"" in wire: x_wires.append(wire) elif ""y"" in wire: y_wires.append(wire) elif ""z"" in wire: z_wires.append(wire) x_wires.sort(reverse=True) y_wires.sort(reverse=True) z_wires.sort(reverse=True) x_digits = [str(wires[w]) for w in x_wires] y_digits = [str(wires[w]) for w in y_wires] z_digits = [str(wires[w]) for w in z_wires] x_dec = int("""".join(x_digits), 2) y_dec = int("""".join(y_digits), 2) z_dec = int("""".join(z_digits), 2) part_one = z_dec print(""Part One:"", part_one) # part two analysis for manual solving print() print(""Part Two Analysis"") width = len(z_digits) expected = f""{x_dec + y_dec:0{width}b}""[::-1] actual = f""{z_dec:0{width}b}""[::-1] # z wires that must swap must_swap = [] for line in out_vals: wires_in, out_wire = line.split("" -> "") left, op, right = wires_in.split("" "") if out_wire.startswith(""z""): if out_wire != f""z{width - 1}"" and op != ""XOR"": must_swap.append(out_wire) elif out_wire == f""z{width - 1}"" and op != ""OR"": must_swap.append(out_wire) print(""Must swap:"") print("", "".join(must_swap)) # z wires where something is wrong wrong_z = [] for i, digit in enumerate(expected): if digit != actual[i]: wrong_z.append(f""z{i:02}"") print(""Investigate:"") print("", "".join(wrong_z))",python:3.9.21-slim 2024,24,2,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? Your puzzle answer was 52956035802096. --- Part Two --- After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): x00: 1 x01: 1 x02: 0 x03: 1 y00: 1 y01: 0 y02: 1 y03: 1 If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: z00: 0 z01: 0 z02: 0 z03: 1 z04: 1 Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: x00: 0 x01: 1 x02: 0 x03: 1 x04: 0 x05: 1 y00: 0 y01: 0 y02: 1 y03: 1 y04: 0 y05: 1 x00 AND y00 -> z05 x01 AND y01 -> z02 x02 AND y02 -> z01 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z00 However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: x00 AND y00 -> z00 x01 AND y01 -> z01 x02 AND y02 -> z02 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z05 In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,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:3.9.21-slim 2024,24,2,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? Your puzzle answer was 52956035802096. --- Part Two --- After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): x00: 1 x01: 1 x02: 0 x03: 1 y00: 1 y01: 0 y02: 1 y03: 1 If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: z00: 0 z01: 0 z02: 0 z03: 1 z04: 1 Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: x00: 0 x01: 1 x02: 0 x03: 1 x04: 0 x05: 1 y00: 0 y01: 0 y02: 1 y03: 1 y04: 0 y05: 1 x00 AND y00 -> z05 x01 AND y01 -> z02 x02 AND y02 -> z01 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z00 However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: x00 AND y00 -> z00 x01 AND y01 -> z01 x02 AND y02 -> z02 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z05 In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,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:3.9.21-slim 2024,24,2,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? Your puzzle answer was 52956035802096. --- Part Two --- After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): x00: 1 x01: 1 x02: 0 x03: 1 y00: 1 y01: 0 y02: 1 y03: 1 If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: z00: 0 z01: 0 z02: 0 z03: 1 z04: 1 Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: x00: 0 x01: 1 x02: 0 x03: 1 x04: 0 x05: 1 y00: 0 y01: 0 y02: 1 y03: 1 y04: 0 y05: 1 x00 AND y00 -> z05 x01 AND y01 -> z02 x02 AND y02 -> z01 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z00 However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: x00 AND y00 -> z00 x01 AND y01 -> z01 x02 AND y02 -> z02 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z05 In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,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:3.9.21-slim 2024,24,2,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? Your puzzle answer was 52956035802096. --- Part Two --- After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): x00: 1 x01: 1 x02: 0 x03: 1 y00: 1 y01: 0 y02: 1 y03: 1 If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: z00: 0 z01: 0 z02: 0 z03: 1 z04: 1 Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: x00: 0 x01: 1 x02: 0 x03: 1 x04: 0 x05: 1 y00: 0 y01: 0 y02: 1 y03: 1 y04: 0 y05: 1 x00 AND y00 -> z05 x01 AND y01 -> z02 x02 AND y02 -> z01 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z00 However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: x00 AND y00 -> z00 x01 AND y01 -> z01 x02 AND y02 -> z02 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z05 In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,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:3.9.21-slim 2024,24,2,"--- Day 24: Crossed Wires --- You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: x00: 1 x01: 1 x02: 1 y00: 0 y01: 1 y02: 0 x00 AND y00 -> z00 x01 XOR y01 -> z01 x02 OR y02 -> z02 Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. Here's a larger example: x00: 1 x01: 0 x02: 1 x03: 1 x04: 0 y00: 1 y01: 1 y02: 1 y03: 1 y04: 1 ntg XOR fgs -> mjb y02 OR x01 -> tnw kwq OR kpj -> z05 x00 OR x03 -> fst tgd XOR rvg -> z01 vdt OR tnw -> bfw bfw AND frj -> z10 ffh OR nrd -> bqk y00 AND y03 -> djm y03 OR y00 -> psh bqk OR frj -> z08 tnw OR fst -> frj gnj AND tgd -> z11 bfw XOR mjb -> z00 x03 OR x00 -> vdt gnj AND wpb -> z02 x04 AND y00 -> kjc djm OR pbm -> qhw nrd AND vdt -> hwm kjc AND fst -> rvg y04 OR y02 -> fgs y01 AND x02 -> pbm ntg OR kjc -> kwq psh XOR fgs -> tgd qhw XOR tgd -> z09 pbm OR djm -> kpj x03 XOR y03 -> ffh x00 XOR y04 -> ntg bfw OR bqk -> z06 nrd XOR fgs -> wpb frj XOR qhw -> z04 bqk OR frj -> z07 y03 OR x01 -> nrd hwm AND bqk -> z03 tgd XOR rvg -> z12 tnw OR pbm -> gnj After waiting for values on all wires starting with z, the wires in this system have the following values: bfw: 1 bqk: 1 djm: 1 ffh: 0 fgs: 1 frj: 1 fst: 1 gnj: 1 hwm: 1 kjc: 0 kpj: 1 kwq: 0 mjb: 1 nrd: 1 ntg: 0 pbm: 1 psh: 1 qhw: 1 rvg: 0 tgd: 0 tnw: 1 vdt: 1 wpb: 0 z00: 0 z01: 0 z02: 0 z03: 1 z04: 0 z05: 1 z06: 1 z07: 1 z08: 1 z09: 1 z10: 1 z11: 0 z12: 0 Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? Your puzzle answer was 52956035802096. --- Part Two --- After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): x00: 1 x01: 1 x02: 0 x03: 1 y00: 1 y01: 0 y02: 1 y03: 1 If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: z00: 0 z01: 0 z02: 0 z03: 1 z04: 1 Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: x00: 0 x01: 1 x02: 0 x03: 1 x04: 0 x05: 1 y00: 0 y01: 0 y02: 1 y03: 1 y04: 0 y05: 1 x00 AND y00 -> z05 x01 AND y01 -> z02 x02 AND y02 -> z01 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z00 However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: x00 AND y00 -> z00 x01 AND y01 -> z01 x02 AND y02 -> z02 x03 AND y03 -> z03 x04 AND y04 -> z04 x05 AND y05 -> z05 In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,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:3.9.21-slim 2024,25,1,"--- Day 25: Code Chronicle --- Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"#!/usr/bin/env python3 myfile = open(""25.in"", ""r"") lines = myfile.read().strip().split(""\n\n"") myfile.close() schematics = [line.split(""\n"") for line in lines] part_one = 0 keys = set() locks = set() for schematic in schematics: is_lock = schematic[0][0] == ""#"" width = len(schematic[0]) cols = [[row[i] for row in schematic] for i in range(width)] heights = tuple(c.count(""#"") - 1 for c in cols) if is_lock: locks.add(heights) else: keys.add(heights) for lock in locks: for key in keys: max_key = tuple(5 - h for h in lock) if all(h <= max_key[i] for i, h in enumerate(key)): part_one += 1 print(""Part One:"", part_one)",python:3.9.21-slim 2024,25,1,"--- Day 25: Code Chronicle --- Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"with open(""./day_25.in"") as fin: lines = fin.read().strip().split(""\n\n"") def parse(s): lock = s[0][0] == ""#"" if lock: vals = [] for j in range(5): for i in range(7): if s[i][j] == ""."": vals.append(i) break return vals, lock vals = [] for j in range(5): for i in range(6, -1, -1): if s[i][j] == ""."": vals.append(6 - i) break return vals, lock locks = [] keys = [] for s in lines: vals, lock = parse(s.split(""\n"")) if lock: locks.append(vals) else: keys.append(vals) ans = 0 for lock in locks: for key in keys: good = True for j in range(5): if lock[j] + key[j] > 7: good = False break ans += good print(ans)",python:3.9.21-slim 2024,25,1,"--- Day 25: Code Chronicle --- Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"import time def parse(lines) -> set[tuple[int, int]]: return { (x, y) for y, line in enumerate(lines) for x, char in enumerate(line) if char == ""#"" } def solve_part_1(text: str): blocks = text.split(""\n\n"") locks = [] keys = [] for b in blocks: lines = b.splitlines() schema = parse(lines[1:-1]) locks.append(schema) if lines[0] == ""#####"" else keys.append(schema) r = 0 for lock in locks: for key in keys: r += len(lock & key) == 0 return r def solve_part_2(text: str): return 0 if __name__ == ""__main__"": with open(""input.txt"", ""r"") as f: quiz_input = f.read() start = time.time() p_1_solution = int(solve_part_1(quiz_input)) middle = time.time() print(f""Part 1: {p_1_solution} (took {(middle - start) * 1000:.3f}ms)"") p_2_solution = int(solve_part_2(quiz_input)) end = time.time() print(f""Part 2: {p_2_solution} (took {(end - middle) * 1000:.3f}ms)"")",python:3.9.21-slim 2024,25,1,"--- Day 25: Code Chronicle --- Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"locks = [] keys = [] with open(""day25-data.txt"") as file: lines = file.readlines() for i in range(0, len(lines), 8): schematic = [line.strip('\n') for line in lines[i+1:i+6]] schematic_transposed = [[schematic[j][i] for j in range(len(schematic))] for i in range(len(schematic[0]))] pins = [a.count('#') for a in schematic_transposed] if (lines[i] == ""#####\n""): locks.append(pins) # lock elif lines[i] == "".....\n"": keys.append(pins) # key sum = 0 for lock in locks: for key in keys: test = [lock[i] + key[i] for i in range(0, len(lock))] if max(test) < 6: sum += 1 print(""Day 25 part 1, sum ="", sum)",python:3.9.21-slim 2024,25,1,"--- Day 25: Code Chronicle --- Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. ""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. ""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" ""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" He transmits you some example schematics: ##### .#### .#### .#### .#.#. .#... ..... ##### ##.## .#.## ...## ...#. ...#. ..... ..... #.... #.... #...# #.#.# #.### ##### ..... ..... #.#.. ###.. ###.# ###.# ##### ..... ..... ..... #.... #.#.. #.#.# ##### ""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" ""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" ""So, you could say the first lock has pin heights 0,5,3,4,3:"" ##### .#### .#### .#### .#.#. .#... ..... ""Or, that the first key has heights 5,0,2,1,3:"" ..... #.... #.... #...# #.#.# #.### ##### ""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" ""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. In this example, converting both locks to pin heights produces: 0,5,3,4,3 1,2,0,5,3 Converting all three keys to heights produces: 5,0,2,1,3 4,3,4,0,2 3,0,2,0,1 Then, you can try every key with every lock: Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"import itertools def get_lock(block): col_counts = [5] * 5 for line in block[1:6]: for i in range(5): if line[i] == ""."": col_counts[i] -= 1 return col_counts def get_key(block): col_counts = [0] * 5 for line in block[1:6]: for i in range(5): if line[i] == ""#"": col_counts[i] += 1 return col_counts with open('input.txt') as f: lines = f.read().splitlines() locks = [] keys = [] for i in range(0, len(lines), 8): block = lines[i:i+7] if block[0][0] == ""#"": locks.append(get_lock(block)) elif block[0][0] == ""."": keys.append(get_key(block)) ct_fit = sum([all([lock[i] + key[i] <= 5 for i in range(5)]) for lock, key in itertools.product(locks, keys)]) print(ct_fit)",python:3.9.21-slim 2024,22,1,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"data = open('input.txt').read().strip().split('\n') def generateNextNumber(num): res1 = num temp = (num * 64) res1 = (res1 ^ temp) % 16777216 res2 = res1 temp = (res1 // 32) res2 = (res2 ^ temp) % 16777216 res3 = res2 temp = (res2 * 2048) res3 = (res3 ^ temp) % 16777216 return res3 total = 0 for i in range(0, len(data)): num = int(data[i]) for i in range(2000): num = generateNextNumber(num) total += num print(total)",python:3.9.21-slim 2024,22,1,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"from typing import List def parse_input(file_path: str) -> List[int]: """""" Reads a file containing integers, one per line, and returns a list of these integers. Args: file_path (str): The path to the input file. Returns: List[int]: A list of integers read from the file. """""" with open(file_path) as f: return [int(line.strip()) for line in f] def next_secret_number(secret: int) -> int: """""" Calculate the next secret number based on the given secret number. The function performs a series of bitwise operations and modular arithmetic to generate a new secret number from the input secret number. Steps: 1. Multiply the secret by 64, mix with XOR, and prune with modulo 16777216. 2. Divide the result by 32, mix with XOR, and prune with modulo 16777216. 3. Multiply the result by 2048, mix with XOR, and prune with modulo 16777216. Args: secret (int): The input secret number. Returns: int: The next secret number. """""" # Step 1: Multiply by 64, mix, and prune secret = (secret ^ (secret * 64)) % 16777216 # Step 2: Divide by 32, mix, and prune secret = (secret ^ (secret // 32)) % 16777216 # Step 3: Multiply by 2048, mix, and prune secret = (secret ^ (secret * 2048)) % 16777216 return secret def generate_2000th_secret(initial_secret: int) -> int: """""" Generates the 2000th secret number starting from the given initial secret. Args: initial_secret (int): The initial secret number to start from. Returns: int: The 2000th secret number. """""" secret = initial_secret for _ in range(2000): secret = next_secret_number(secret) return secret if __name__ == ""__main__"": input_data = parse_input('input.txt') total = sum(generate_2000th_secret(secret) for secret in input_data) print(total)",python:3.9.21-slim 2024,22,1,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"def step(num): num = (num ^ (num * 64)) % 16777216 num = (num ^ (num // 32)) % 16777216 num = (num ^ (num * 2048)) % 16777216 return num def process_buyers(file_path): total = 0 with open(file_path) as file: for line in file: num = int(line) buyer = [num % 10] for _ in range(2000): num = step(num) buyer.append(num % 10) total += num return total def main(): total = process_buyers(""i.txt"") print(total) if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,22,1,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"from collections import defaultdict import numpy as np with open(""input.txt"") as f: ns = list(map(int, f.read().strip().split(""\n""))) def hsh(secret): for _ in range(2000): secret ^= secret << 6 & 0xFFFFFF secret ^= secret >> 5 & 0xFFFFFF secret ^= secret << 11 & 0xFFFFFF yield secret secrets = list(map(list, map(hsh, ns))) # Part 1 print(sum(s[-1] for s in secrets))",python:3.9.21-slim 2024,22,1,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"def step(num): num = (num ^ (num * 64)) % 16777216 num = (num ^ (num // 32)) % 16777216 num = (num ^ (num * 2048)) % 16777216 return num def process_buyers(file_path): total = 0 with open(file_path) as file: for line in file: num = int(line) buyer = [num % 10] for _ in range(2000): num = step(num) buyer.append(num % 10) total += num return total def main(): total = process_buyers(""22.txt"") print(total) if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,22,2,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"from collections import defaultdict import numpy as np with open(""input.txt"") as f: ns = list(map(int, f.read().strip().split(""\n""))) def hsh(secret): for _ in range(2000): secret ^= secret << 6 & 0xFFFFFF secret ^= secret >> 5 & 0xFFFFFF secret ^= secret << 11 & 0xFFFFFF yield secret # Part 2 result = defaultdict(int) for n in ns: ss = [s % 10 for s in hsh(n)] diffs = np.diff(ss) changes = set() for i in range(1996): if (change := tuple(diffs[i : i + 4])) not in changes: changes.add(change) result[change] += ss[i + 4] print(max(result.values()))",python:3.9.21-slim 2024,22,2,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"def step(num): num = (num ^ (num * 64)) % 16777216 num = (num ^ (num // 32)) % 16777216 num = (num ^ (num * 2048)) % 16777216 return num def process_buyers(file_path): buyers = [] with open(file_path) as file: for line in file: num = int(line) buyer = [num % 10] for _ in range(2000): num = step(num) buyer.append(num % 10) buyers.append(buyer) return buyers def calculate_sorok(buyers): sorok = {} for b in buyers: seen = set() for i in range(len(b) - 4): a1, a2, a3, a4, a5 = b[i:i+5] sor = (a2 - a1, a3 - a2, a4 - a3, a5 - a4) if sor in seen: continue seen.add(sor) if sor not in sorok: sorok[sor] = 0 sorok[sor] += a5 return sorok def main(): buyers = process_buyers(""22.txt"") sorok = calculate_sorok(buyers) print(max(sorok.values())) if __name__ == ""__main__"": main()",python:3.9.21-slim 2024,22,2,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"import time N = 2000 def next_secret(s): """"""3-step pseudorandom transformation for a 24-bit integer."""""" s = (s ^ ((s << 6) & 0xFFFFFF)) & 0xFFFFFF s = (s ^ (s >> 5)) & 0xFFFFFF s = (s ^ ((s << 11) & 0xFFFFFF)) & 0xFFFFFF return s def pack_diffs_into_key(d0, d1, d2, d3): """""" Each diff is offset by +9 to fit into [0..18] (5 bits each). Combine them into a single 20-bit integer. """""" return (d0 << 15) | (d1 << 10) | (d2 << 5) | d3 def solve_part_2(text: str): buyers = list(map(int, text.splitlines())) size = 1 << 20 # total possible 4-diff combinations seen = [0] * size results = [0] * size buyer_id = 1 secrets_arr = [0] * (N + 1) prices_arr = [0] * (N + 1) deltas_arr = [0] * (N + 1) for secret_number in buyers: # Fill arrays with generated secrets, prices, and deltas secrets_arr[0] = secret_number prices_arr[0] = secrets_arr[0] % 10 for i in range(1, N + 1): secrets_arr[i] = next_secret(secrets_arr[i - 1]) prices_arr[i] = secrets_arr[i] % 10 deltas_arr[i] = prices_arr[i] - prices_arr[i - 1] # From index 4 onward, we have a valid window of 4 consecutive deltas for i in range(4, N + 1): # We gather the 4 consecutive deltas leading to prices_arr[i]. d0 = deltas_arr[i - 3] + 9 d1 = deltas_arr[i - 2] + 9 d2 = deltas_arr[i - 1] + 9 d3 = deltas_arr[i] + 9 key = pack_diffs_into_key(d0, d1, d2, d3) # Only record the first time this buyer sees this pattern if seen[key] != buyer_id: seen[key] = buyer_id results[key] += prices_arr[i] buyer_id += 1 return max(results) if __name__ == ""__main__"": with open(""22.txt"", ""r"") as f: quiz_input = f.read() p_2_solution = int(solve_part_2(quiz_input)) print(f""Part 2: {p_2_solution}"")",python:3.9.21-slim 2024,22,2,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"import time, re, itertools as itt, collections as coll def load(file): with open(file) as f: return map(int, re.findall('\d+', f.read())) def mix_prune(s): s = (s ^ (s * 64)) % 16777216 s = (s ^ (s // 32)) % 16777216 return (s ^ (s * 2048)) % 16777216 def solve(p): part1 = part2 = 0 bananas = coll.defaultdict(int) for s in p: nums = [s := mix_prune(s) for _ in range(2000)] diffs = [b % 10 - a % 10 for a, b in itt.pairwise(nums)] first_seen_pat = set() for i in range(len(nums) - 4): pat = tuple(diffs[i:i + 4]) if pat in first_seen_pat: continue bananas[pat] += nums[i + 4] % 10 first_seen_pat.add(pat) part2 = max(bananas.values()) return part2 print(f'Solution: {solve(load(""22.txt""))}')",python:3.9.21-slim 2024,22,2,"--- Day 22: Monkey Market --- As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. Each step of the above process involves mixing and pruning: To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: 15887950 16495136 527345 704524 1553684 12683156 11100544 12249484 7753432 5908254 Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: 1 10 100 2024 This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: 1: 8685429 10: 4700978 100: 15273692 2024: 8667524 Adding up the 2000th new secret number for each buyer produces 37327623. For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? Your puzzle answer was 15335183969. --- Part Two --- Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: 3 (from 123) 0 (from 15887950) 6 (from 16495136) 5 (etc.) 4 4 6 4 4 2 This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: 123: 3 15887950: 0 (-3) 16495136: 6 (6) 527345: 5 (-1) 704524: 4 (-1) 1553684: 4 (0) 12683156: 6 (2) 11100544: 4 (-2) 12249484: 4 (0) 7753432: 2 (-2) Note that the first price has no associated change because there was no previous price to compare it with. In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. Suppose the initial secret number of each buyer is: 1 2 3 2024 There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"with open(""input.txt"", ""r"") as file: lines = file.readlines() def secretStep(secret): # Cleaned up secret = (secret * 64 ^ secret) % 16777216 secret = (secret // 32 ^ secret) % 16777216 secret = (secret * 2048 ^ secret) % 16777216 return secret # Custom implementation of max function def findMax(sequence_totals): max_key = None max_value = float('-inf') # Start with the smallest possible value for key, value in sequence_totals.items(): if value > max_value: max_value = value max_key = key return max_key def findMaxBananas(lines): sequence_totals = {} for line in lines: secret_number = int(line) price_list = [secret_number % 10] # Store last digit of secret numbers # Generate 2000 price steps for _ in range(2000): secret_number = secretStep(secret_number) price_list.append(secret_number % 10) tracked_sequences = set() # Examine all sequences of 4 consecutive price changes for index in range(len(price_list) - 4): p1, p2, p3, p4, p5 = price_list[index:index + 5] # Extract 5 consecutive prices price_change = (p2 - p1, p3 - p2, p4 - p3, p5 - p4) # Calculate changes if price_change in tracked_sequences: # Skip since we wont choose same again continue tracked_sequences.add(price_change) if price_change not in sequence_totals: sequence_totals[price_change] = 0 sequence_totals[price_change] += p5 # Add the price to the total # Find highest total # best_sequence = max(sequence_totals, key=sequence_totals.get) best_sequence = findMax(sequence_totals) max_bananas = sequence_totals[best_sequence] return best_sequence, max_bananas best_sequence, max_bananas = findMaxBananas(lines) print(max_bananas)",python:3.9.21-slim 2024,20,1,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"import time from enum import Enum import heapq file = open(""20.txt"", ""r"") start_time = time.time() class Direction(Enum): UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 class Position: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f""{self.__dict__}"" def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return hash(f""{self.x}_{self.y}"") @classmethod def list(cls): return list(map(lambda c: c.value, cls)) class TrackNode: def __init__(self, position, order): self.position = position self.order = order def __repr__(self): return f""{self.__dict__}"" def __eq__(self, other): return self.position == other.position and self.order == other.order def __hash__(self): return hash(f""{self.position}_{self.order}"") class Cheat: def __init__(self, s, e): self.s = s self.e = e def __repr__(self): return f""{self.__dict__}"" def __eq__(self, other): return self.s == other.s and self.e == other.e def __hash__(self): return hash(f""{self.s}_{self.e}"") space = 0 wall = 1 def import_matrix(matrix_string): matrix = [] start_position = None goal_position = None for line_index, line in enumerate(matrix_string.split(""\n"")): matrix.append([]) # print(line) for column_index, tile in enumerate(line): if tile == ""."": matrix[line_index].append(space) elif tile == ""#"": matrix[line_index].append(wall) elif tile == ""S"": matrix[line_index].append(space) start_position = Position(column_index, line_index) elif tile == ""E"": matrix[line_index].append(space) goal_position = Position(column_index, line_index) return (matrix, start_position, goal_position) map, start, goal = import_matrix(file.read()) def print_map(path = set()): for line_index, line in enumerate(map): string = [] for column_index, tile in enumerate(line): if Position(column_index, line_index) == start: string.append(""S"") elif Position(column_index, line_index) == goal: string.append(""E"") elif Position(column_index, line_index) in path: string.append(""O"") elif tile == wall: string.append(""#"") else: string.append(""."") print("""".join(string)) def get_valid_in_direction(current_position, direction): match direction: case Direction.UP: p = Position(current_position.x, current_position.y-1) case Direction.LEFT: p = Position(current_position.x-1, current_position.y) case Direction.RIGHT: p = Position(current_position.x+1, current_position.y) case Direction.DOWN: p = Position(current_position.x, current_position.y+1) if p.x < 0 or p.x >= len(map[0]) or p.y < 0 or p.y >= len(map): return None return (p, direction) def get_neighbors_and_cheats(current_position): directions = [Direction.LEFT, Direction.RIGHT, Direction.UP, Direction.DOWN] neighbors_in_map = [get_valid_in_direction(current_position, d) for d in directions] neighbors = [] walls_with_direction = [] for n in neighbors_in_map: if n is None: continue if map[n[0].y][n[0].x] == space: neighbors.append(n[0]) else: walls_with_direction.append(n) cheats = [] for wd in walls_with_direction: possible_cheat = get_valid_in_direction(wd[0], wd[1]) if possible_cheat is None: continue if map[possible_cheat[0].y][possible_cheat[0].x] == space: cheats.append(Cheat(wd[0], possible_cheat[0])) return (neighbors, cheats) print(""~~~~~~~~~~RESULT 1~~~~~~~~~~"") def create_track_1(): graph = {} cheats_dict = {} for line_index, line in enumerate(map): for column_index, tile in enumerate(line): if tile == wall: continue position = Position(column_index, line_index) (neighbors, cheats) = get_neighbors_and_cheats(position) graph[position] = neighbors cheats_dict[position] = cheats # track = {} # step: position track = {} # position: step cheats = {} # step: [Cheat] ignore = set() # tracks what steps to ignore in track building; should contain whole path current_position = start current_step = 0 while True: ignore.add(current_position) # track[current_step] = current_position track[current_position] = current_step if current_position == goal: break # ignore already traversed track (backward cheat is not a cheat) valid_cheats = [c for c in cheats_dict[current_position] if c.e not in ignore] cheats[current_step] = valid_cheats neighbors = graph[current_position] # assuming only one valid path forward (or none if end) for neighbor in neighbors: if neighbor not in ignore: # ignore already traversed track current_position = neighbor continue current_step += 1 return (track, cheats, current_step) (track, cheats, total_steps) = create_track_1() solution = 0 for step in cheats.keys(): for cheat in cheats[step]: length_up_to_cheat = step step_at_cheat_end = track[cheat.e] resulting_length = length_up_to_cheat + 2 + (total_steps - step_at_cheat_end) steps_saved = total_steps - resulting_length if steps_saved >= 100: solution += 1 print(solution)",python:3.9.21-slim 2024,20,1,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"grid = [[elem for elem in line.strip()] for line in open('input.txt')] def get_start(grid): for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 'S': return (i, j) def get_end(grid): for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 'E': return (i, j) start = get_start(grid) end = get_end(grid) def get_neighbors(grid, pos): i, j = pos neighbors = [] if i > 0 and grid[i-1][j] != '#': neighbors.append((i-1, j)) if i < len(grid) - 1 and grid[i+1][j] != '#': neighbors.append((i+1, j)) if j > 0 and grid[i][j-1] != '#': neighbors.append((i, j-1)) if j < len(grid[i]) - 1 and grid[i][j+1] != '#': neighbors.append((i, j+1)) return neighbors def get_race_track(grid, start, end): visited = [] queue = [start] while queue: pos = queue.pop(0) visited.append(pos) if pos == end: return visited neighbors = get_neighbors(grid, pos) for neighbor in neighbors: if neighbor not in visited: queue.append(neighbor) return [] def print_path(grid, path): grid_copy = [line.copy() for line in grid] for pos in path[:10]: i, j = pos grid_copy[i][j] = 'X' for line in grid_copy: print(''.join(line)) def print_cheat(grid, first, second): grid_copy = [line.copy() for line in grid] grid_copy[first[0]][first[1]] = '1' grid_copy[second[0]][second[1]] = '2' for line in grid_copy: print(''.join(line)) def get_cheats(path,grid): cheats = {} for i in range(len(path)): for j in range(i,len(path)): if (path[i][0] == path[j][0] and abs(path[i][1]-path[j][1]) == 2 and grid[path[i][0]][(path[i][1]+path[j][1])//2] == '#') or (path[i][1] == path[j][1] and abs(path[i][0]-path[j][0]) == 2 and grid[(path[i][0]+path[j][0])//2][path[i][1]] == '#'): savedTime = j - i - 2 if savedTime not in cheats: cheats[savedTime] = 1 else: cheats[savedTime] += 1 return cheats path = get_race_track(grid, start, end) cheats = get_cheats(path,grid) #rint(cheats) count = 0 for key in cheats: if key >= 100: count += cheats[key] print(count)",python:3.9.21-slim 2024,20,1,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from collections import defaultdict, deque from tqdm import tqdm import copy with open(""./day_20.in"") as fin: grid = [list(line) for line in fin.read().strip().split(""\n"")] N = len(grid) def in_grid(i, j): return 0 <= i < N and 0 <= j < N for i in range(N): for j in range(N): if grid[i][j] == ""S"": si, sj = i, j elif grid[i][j] == ""E"": ei, ej = i, j dd = [[1, 0], [0, 1], [-1, 0], [0, -1]] # Determine OG path path = [(si, sj)] while path[-1] != (ei, ej): i, j = path[-1] for di, dj in dd: ii, jj = i + di, j + dj if not in_grid(ii, jj): continue if len(path) > 1 and (ii, jj) == path[-2]: continue if grid[ii][jj] == ""#"": continue path.append((ii, jj)) break og = len(path) - 1 times = {} for t, coord in enumerate(path): times[coord] = og - t counts = defaultdict(int) saved = {} for t, coord in enumerate(tqdm(path, ncols=80)): i, j = coord for di1, dj1 in dd: for di2, dj2 in dd: ii, jj = i + di1 + di2, j + dj1 + dj2 if not in_grid(ii, jj) or grid[ii][jj] == ""#"": continue rem_t = times[(ii, jj)] saved[(i, j, ii, jj)] = og - (t + rem_t + 2) ans = 0 for v in saved.values(): if v >= 0: counts[v] += 1 if v >= 100: ans += 1 print(ans)",python:3.9.21-slim 2024,20,1,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from collections import Counter def find_shortcuts(map, p): y, x = p for direction in [(1, 0), (-1, 0), (0, 1), (0, -1)]: if in_direction(map, p, direction, 1) == '#': shortcut_to = in_direction(map, p, direction, 2) if shortcut_to == '#' or shortcut_to == '.': continue #print(f""Shortcut found from {p} to {shortcut_to}"") yield map[y][x] - shortcut_to - 2 def in_direction(map, f, d, count): y = f[0] x = f[1] for _ in range(count): y += d[0] x += d[1] if 0 > y or y >= len(map) or 0 > x or x >= len(map[0]): return '#' return map[y][x] def step(map, p, steps): y, x = p for r, c in [(y+1,x), (y-1,x), (y,x+1), (y,x-1)]: if map[r][c] == '.': map[r][c] = steps return (r, c) map = [] with open('input') as input: row = 0 for l in input: l = l.strip() map.append(list(l)) if 'S' in l: start = (row, l.find('S')) if 'E' in l: end = (row, l.find('E')) row += 1 print(f""Race from {start} to {end}"") p = start shortcuts = [] steps = 0 map[start[0]][start[1]] = 0 map[end[0]][end[1]] = '.' while p != end: steps += 1 #print(f""Step {steps} from {p}"") shortcuts.extend(find_shortcuts(map, p)) p = step(map, p, steps) # And also shortcuts straight to the end shortcuts.extend(find_shortcuts(map, p)) for l, count in sorted(Counter(shortcuts).items(), key=lambda x: x[0]): print(f""{l}: {count}"") print(sum(1 for s in shortcuts if s >= 100))",python:3.9.21-slim 2024,20,1,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"from dataclasses import dataclass from pathlib import Path TEST = False if TEST: text = Path(""20_test.txt"").read_text().strip() else: text = Path(""20.txt"").read_text().strip() grid = [list(l) for l in text.split(""\n"")] width = len(grid[0]) height = len(grid) def get_grid(p): x = p.x y = p.y if x < 0 or x > width: return None if y < 0 or x > height: return None return grid[y][x] @dataclass(frozen=True) class Position: x: int y: int def __add__(self, other): x = self.x + other.x y = self.y + other.y return Position(x=x, y=y) def manhattan_distance(self, other): d_x = self.x - other.x d_y = self.y - other.y return abs(d_x) + abs(d_y) def neighbours(position): directions = [ Position(1, 0), Position(-1, 0), Position(0, 1), Position(0, -1) ] for d in directions: new_position = position + d if get_grid(new_position) == '.': yield new_position # Find the 'S', and the path from the 'S' to the 'E' - we're told there's a unique path. for x in range(len(grid[0])): for y in range(len(grid)): p = Position(x=x, y=y) if get_grid(p) == 'S': start_position = p grid[y][x] = '.' elif get_grid(p) == 'E': end_position = p grid[y][x] = '.' path = {start_position: 0} last_position = start_position while last_position != end_position: next_ = [x for x in neighbours(last_position) if x not in path] assert len(next_) == 1 next_ = next_[0] path[next_] = len(path) last_position = next_ # Part 1: How many jumps of length 2 save at least 100 picoseconds? directions = [ Position(2, 0), Position(-2, 0), Position(0, 2), Position(0, -2) ] count = 0 for point in path: for d in directions: next_point = point + d if next_point in path: time_saved = path[next_point] - path[point] - 2 if time_saved >= 100: count += 1 print(count)",python:3.9.21-slim 2024,20,2,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"from collections import defaultdict with open(""input.txt"") as input_file: input_text = input_file.read().splitlines() start = (-1, -1) end = (-1, -1) walls = set() for row in range(len(input_text)): for col in range(len(input_text[0])): match input_text[row][col]: case ""S"": start = (row, col) case ""E"": end = (row, col) case ""#"": walls.add((row, col)) moves = ((1, 0), (-1, 0), (0, 1), (0, -1)) no_cheat_move_count = {start: 0} current_pos = start move_count = 0 while current_pos != end: for row_move, col_move in moves: new_pos = (current_pos[0] + row_move, current_pos[1] + col_move) if new_pos not in walls and new_pos not in no_cheat_move_count: move_count += 1 current_pos = new_pos no_cheat_move_count[current_pos] = move_count break cheat_moves = [] for delta_row in range(-20, 21): for delta_col in range(-(20 - abs(delta_row)), 21 - abs(delta_row)): cheat_moves.append((delta_row, delta_col)) cheats = defaultdict(int) for (initial_row, initial_col), step in no_cheat_move_count.items(): for row_move, col_move in cheat_moves: cheat_pos = (initial_row + row_move, initial_col + col_move) if no_cheat_move_count.get(cheat_pos, 0) > step + abs(row_move) + abs(col_move): cheats[ no_cheat_move_count[cheat_pos] - step - abs(row_move) - abs(col_move) ] += 1 print(sum(count for saving, count in cheats.items() if saving >= 100))",python:3.9.21-slim 2024,20,2,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"def readfile(test_file): file_name = ""test.txt"" if test_file else ""input.txt"" with open(file_name) as f: maze = [list(line.strip()) for line in f.readlines()] start = (-1, -1) end = (-1, -1) # Create the maze with 1 as blocks and 0 as free for r, row in enumerate(maze): for c, _ in enumerate(row): symbol = maze[r][c] if symbol == ""S"": # Keep track of start start = (r, c) maze[r][c] = 0 elif symbol == ""E"": # Keep track of end end = (r, c) maze[r][c] = 0 elif symbol == ""."": maze[r][c] = 0 else: maze[r][c] = 1 return maze, start, end def part2(maze, start, end): path, costs = cheapest_path(maze, start, end) cheats = [] # Find all possible cheats with max duration of 20 picoseconds by pairwise matching of path for i in range(0, len(path)): for j in range(i, len(path)): start = path[i] end = path[j] diff = abs(end[1] - start[1]) + abs(end[0] - start[0]) if 0 < diff <= 20: cheats.append((start, end, diff)) time_saved = {} # For each cheat keep track of how much time is saved for cheat in cheats: start = cheat[0] end = cheat[1] steps = cheat[2] diff = costs[end] - costs[start] - steps # Ignore cheats saving less than 100 picoseconds if diff < 100: continue elif diff in time_saved: time_saved[diff] += 1 else: time_saved[diff] = 1 print(sum(time_saved.values())) if __name__ == ""__main__"": test_file = False maze, start, end = readfile(test_file) print(""\nAnswer to part 2:"") part2(maze, start, end)",python:3.9.21-slim 2024,20,2,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"with open(""input20.txt"") as i: input = [x.strip() for x in i.readlines()] test_data = """"""############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ###############"""""".split(""\n"") # input = test_data map = """".join(input) w, h = len(input[0]), len(input) start, end = map.index(""S""), map.index(""E"") def print_map(): for r in range(h): print(map[r*w:(r+1)*w]) distances = [None]*w*h working_set = [end] current = 0 while len(working_set)>0: next = [] for i in working_set: if distances[i] is None: distances[i] = current next = [x for x in [i-1, i-w, i+1, i+w] if map[x]!=""#"" and distances[x] is None] working_set = next current += 1 original = distances[start] def get_cheats(cheat_length, limit): count = 0 for i in range(0, w*h): if distances[i] is None: continue for j in range(i+1, w*h): if distances[j] is None: continue x1, y1, x2, y2 = i%w, i//w, j%w, j//w if abs(x1-x2) + abs(y1-y2)<=cheat_length: k = 0 if distances[i] > distances[j]: k = distances[start]-distances[i] + distances[j] + abs(x1-x2) + abs(y1-y2) elif distances[i] < distances[j]: k = distances[start]-distances[j] + distances[i] + abs(x1-x2) + abs(y1-y2) if original-k>=limit: count += 1 return count print(get_cheats(20, 100))",python:3.9.21-slim 2024,20,2,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"from collections import defaultdict import heapq def parse_input(filename): grid = [] with open(filename, 'r') as file: for line in file: line = line.strip() grid.append([char for char in line]) return grid def solve1(grid, minsave): si, sj, ei, ej = 0,0,0,0 N, M = len(grid), len(grid[0]) def inside(i,j): return 0<=i= minsave and grid[ti][tj] == '#': savings[(i,j,ni,nj)] = cost[(ni,nj)] - cost[(i,j)] - 2 count += 1 print(f""Part One - {count}"") # 1518 def solve2(grid, minsave): si, sj, ei, ej = 0,0,0,0 N, M = len(grid), len(grid[0]) def inside(i,j): return 0<=i= minsave: savings[(i,j,ni,nj)] = cost[(ni,nj)] - cost[(i,j)] - step count += 1 print(f""Part Two - {count}"") # 1032257 # grid = parse_input('./inputs/day20toy.txt') # solve1(grid, 0) # solve2(grid, 50) grid = parse_input('./inputs/day20.txt') solve1(grid, 100) solve2(grid, 100)",python:3.9.21-slim 2024,20,2,"--- Day 20: Race Condition --- The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! They hand you a map of the racetrack (your puzzle input). For example: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...12....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...12..# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 38 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..E#...#...# ###.####1##.### #...###.2.#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### This cheat saves 64 picoseconds and takes the program directly to the end: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #######.#.#.### #######.#.#...# #######.#.###.# ###..21...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. In this example, the total number of cheats (grouped by the amount of time they save) are as follows: There are 14 cheats that save 2 picoseconds. There are 14 cheats that save 4 picoseconds. There are 2 cheats that save 6 picoseconds. There are 4 cheats that save 8 picoseconds. There are 2 cheats that save 10 picoseconds. There are 3 cheats that save 12 picoseconds. There is one cheat that saves 20 picoseconds. There is one cheat that saves 36 picoseconds. There is one cheat that saves 38 picoseconds. There is one cheat that saves 40 picoseconds. There is one cheat that saves 64 picoseconds. You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? Your puzzle answer was 1307. --- Part Two --- The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: ############### #...#...#.....# #.#.#.#.#.###.# #S#...#.#.#...# #1#####.#.#.### #2#####.#.#...# #3#####.#.###.# #456.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: ############### #...#...#.....# #.#.#.#.#.###.# #S12..#.#.#...# ###3###.#.#.### ###4###.#.#...# ###5###.#.###.# ###6.E#...#...# ###.#######.### #...###...#...# #.#####.#.###.# #.#...#.#.#...# #.#.#.#.#.#.### #...#...#...### ############### Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: There are 32 cheats that save 50 picoseconds. There are 31 cheats that save 52 picoseconds. There are 29 cheats that save 54 picoseconds. There are 39 cheats that save 56 picoseconds. There are 25 cheats that save 58 picoseconds. There are 23 cheats that save 60 picoseconds. There are 20 cheats that save 62 picoseconds. There are 19 cheats that save 64 picoseconds. There are 12 cheats that save 66 picoseconds. There are 14 cheats that save 68 picoseconds. There are 12 cheats that save 70 picoseconds. There are 22 cheats that save 72 picoseconds. There are 4 cheats that save 74 picoseconds. There are 3 cheats that save 76 picoseconds. Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"#!/usr/bin/env python3 from collections import defaultdict, deque myfile = open(""20.txt"", ""r"") lines = myfile.read().strip().splitlines() myfile.close() end = start = (-1, -1) grid = defaultdict(str) for y in range(len(lines)): for x in range(len(lines[y])): if lines[y][x] == ""S"": start = (x, y) elif lines[y][x] == ""E"": end = (x, y) grid[(x, y)] = lines[y][x] part_one = 0 part_two = 0 visited = set() scores = defaultdict(lambda: float(""inf"")) scores[start] = 0 q = deque([start]) while q: pos = q.popleft() visited.add(pos) for dir in [(1, 0), (0, -1), (-1, 0), (0, 1)]: next_pos = (pos[0] + dir[0], pos[1] + dir[1]) if next_pos not in visited and grid[next_pos] != ""#"" and grid[next_pos] != """": scores[next_pos] = scores[pos] + 1 q.append(next_pos) for a in visited: for i in range(-20, 21): for j in range(-20, 21): dist = abs(i) + abs(j) if dist > 20: continue b = (a[0] + i, a[1] + j) if b not in visited: continue savings = scores[b] - scores[a] - dist if savings < 100: continue if dist <= 2: part_one += 1 part_two += 1 print(""Part One:"", part_one) print(""Part Two:"", part_two)",python:3.9.21-slim 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);",node: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,"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 });",node: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,"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);",node: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? 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); });",node: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,"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);",node:14 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();",node:14 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; }",node:14 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);",node:14 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());",node:14 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);",node:14 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);",node:14 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);",node:14 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);",node:14 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 });",node:14 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}`);",node:14 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);",node:14 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}`);",node:14 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();",node:14 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();",node:14 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",node:14 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);",node:14 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}`);",node:14 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.`);",node:14 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);",node:14 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);",node:14 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);",node:14 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 });",node:14 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",node:14 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);",node:14 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}`);",node:14 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",node:14 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; }",node:14 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}`);",node:14 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}`);",node:14 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);",node:14 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}`);",node:14 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();",node:14 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);",node:14 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);",node:14 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');",node:14 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);",node:14 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();",node:14 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));",node:14 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');",node:14 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();",node:14 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));",node:14 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();",node:14 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();",node:14 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();",node:14 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);",node:14 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();",node:14 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);",node:14 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);",node:14 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();",node:14 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);",node:14 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();",node:14 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()); }",node:14 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();",node:14 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);",node:14 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();",node:14 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); }",node:14 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); }",node:14 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();",node:14 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);",node:14 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();",node:14 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; }",node:14 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); }",node:14 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); }",node:14 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);",node:14 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);",node:14 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); }",node:14 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);",node:14 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); }",node:14 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();",node:14 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();",node:14 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();",node:14 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();",node:14 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();",node:14 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();",node:14 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());",node:14 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();",node:14 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();",node:14 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();",node:14 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();",node:14 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();",node:14 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",node:14 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);",node:14 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);",node:14 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);",node:14 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);",node:14 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);",node:14 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}`);",node:14 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}`);",node:14 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();",node:14 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);",node:14 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}`);",node:14 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));",node:14 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();",node:14 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);",node:14 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);",node:14 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}`);",node:14 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);",node:14 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);",node:14 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);",node:14 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);",node:14 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; } }",node:14 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; } }",node:14 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; } }",node:14 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('')); } } }",node:14 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; }",node:14 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); });",node:14 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);",node:14 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); });",node:14 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);",node:14 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); });",node:14 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); });",node:14 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); });",node:14 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); });",node:14 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); });",node:14 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); });",node:14 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();",node:14 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);",node:14 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();",node:14 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); });",node:14 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 });",node:14 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); });",node:14 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);",node:14 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();",node:14 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; }",node:14 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`)",node:14 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);",node:14 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);",node:14 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);",node:14 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);",node:14 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 });",node:14 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);",node:14 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);",node:14 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); }",node:14 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); };",node:14 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);",node:14 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);",node:14 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')}`);",node:14 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);",node:14 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);",node:14 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');",node:14 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);",node:14 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);",node:14 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);",node:14 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));",node:14 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);",node:14 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}`);",node:14 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();",node:14 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}`);",node:14 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)}`);",node:14 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();",node:14 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();",node:14 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);",node:14 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));",node:14 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));",node:14 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));",node:14 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("","")); });",node:14 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("","")); });",node:14 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("",""); }",node:14 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);",node:14 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",node:14 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();",node:14 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();",node:14 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();",node:14 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'))); });",node:14 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",node:14 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);",node:14 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}`);",node:14 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",node:14 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]); } } } }",node:14 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]); } } }",node:14 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]);",node:14 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());",node:14 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; } }",node:14 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",node:14 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(','));",node:14 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",node:14 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); });",node:14 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); });",node:14 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);",node:14 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);",node:14 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) ); });",node:14 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); });",node:14 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)); });",node:14 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",node:14 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);",node:14 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);",node:14 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);",node:14 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",node:14 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');",node:14 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);",node:14 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);",node:14 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",node:14 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);",node:14 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); });",node:14 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)); });",node:14 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' };",node:14 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);",node:14 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",node:14 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); ",node:14 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; }",node:14 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' };",node:14 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",node:14 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));",node:14 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));",node:14 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' };",node:14 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();",node:14 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);",node:14 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);",node:14 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",node:14 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);",node:14 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();",node:14 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();",node:14 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",node:14 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();",node:14 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",node:14 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();",node:14 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();",node:14 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);",node:14 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",node:14 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));",node:14 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();",node:14 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));",node:14 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",node:14 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("",""));",node:14 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("",""));",node:14 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();",node:14 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);",node:14 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",node:14 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));",node:14 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);",node:14 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(','));",node:14 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()",node:14 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(','));",node:14 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",node:14 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);",node:14 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);",node:14 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) => {}",node:14 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);",node:14 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);",node:14 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);",node:14