year
stringclasses
1 value
day
stringclasses
25 values
part
stringclasses
2 values
question
stringclasses
49 values
answer
stringclasses
49 values
solution
stringlengths
143
7.63k
language
stringclasses
3 values
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<b-a<u for a,b in zip(s,s[1:])) for d,u in[(0,4),(-4,0)])for s in l))
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] 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<n and 0 <=c<m): break if grid[r][c] == "#" or r == i and c == j: r -= dirs[dirIndex][0] c -= dirs[dirIndex][1] dirIndex = (dirIndex + 1) % 4 return numObstacles if __name__ == "__main__": # Open file 'day6-2.txt' in read mode with open('day6-2.txt', 'r') as f: # Read each line of the file grid = [] for line in f: grid.append(line.strip()) print("Number of possible obstacles: " + str(get_possible_obstacles(grid)))
python:3.9
2024
6
2
--- Day 6: Guard Gallivant --- The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? You start by making a map (your puzzle input) of the situation. For example: ....#..... .........# .......... ..#....... .......#.. .......... .#..^..... ........#. #......... ......#... The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: If there is something directly in front of you, turn right 90 degrees. Otherwise, take a step forward. Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): ....#..... ....^....# .......... ..#....... .......#.. .......... .#........ ........#. #......... ......#... Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: ....#..... ........># .......... ..#....... .......#.. .......... .#........ ........#. #......... ......#... Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: ....#..... .........# .......... ..#....... .......#.. .......... .#......v. ........#. #......... ......#... This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): ....#..... .........# .......... ..#....... .......#.. .......... .#........ ........#. #......... ......#v.. By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: ....#..... ....XXXXX# ....X...X. ..#.X...X. ..XXXXX#X. ..X.X.X.X. .#XXXXXXX. .XXXXXXX#. #XXXXXXX.. ......#X.. In this example, the guard will visit 41 distinct positions on your map. Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? Your puzzle answer was 4890. --- Part Two --- While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. Option one, put a printing press next to the guard's starting position: ....#..... ....+---+# ....|...|. ..#.|...|. ....|..#|. ....|...|. .#.O^---+. ........#. #......... ......#... Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: ....#..... ....+---+# ....|...|. ..#.|...|. ..+-+-+#|. ..|.|.|.|. .#+-^-+-+. ......O.#. #......... ......#... Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: ....#..... ....+---+# ....|...|. ..#.|...|. ..+-+-+#|. ..|.|.|.|. .#+-^-+-+. .+----+O#. #+----+... ......#... Option four, put an alchemical retroencabulator near the bottom left corner: ....#..... ....+---+# ....|...|. ..#.|...|. ..+-+-+#|. ..|.|.|.|. .#+-^-+-+. ..|...|.#. #O+---+... ......#... Option five, put the alchemical retroencabulator a bit to the right instead: ....#..... ....+---+# ....|...|. ..#.|...|. ..+-+-+#|. ..|.|.|.|. .#+-^-+-+. ....|.|.#. #..O+-+... ......#... Option six, put a tank of sovereign glue right next to the tank of universal solvent: ....#..... ....+---+# ....|...|. ..#.|...|. ..+-+-+#|. ..|.|.|.|. .#+-^-+-+. .+----++#. #+----++.. ......#O.. It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?
1995
def get_positions(data: 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<rows and 0<=cc<cols and int(grid[rr][cc]) == int(grid[r][c])-1: ans += ways(rr, cc) dp[(r, c)] = ans return ans for r in range(rows): for c in range(cols): if grid[r][c] == '9': part2 += ways(r, c) print(part2) if __name__ == '__main__': main()
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
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): def aux(height, pos): if int(data[pos[0]][pos[1]]) != height: return 0 elif int(data[pos[0]][pos[1]]) == height == 9: return 1 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
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