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 2
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 |
Advent of Code Dataset
This dataset provides various Python solutions for advent of code question from year 2024.
More languages and years will be included in future releases.
Key Features
Enriched solutions: Each part of every question include at least 5 different solutions.
Test cases: Each question come with 3 test cases
Statistics:
Year | Language | Day | Total |
---|---|---|---|
2024 | Python | 1 to 25 | 245 |
Data Instance Example:
{
"Year": "2024",
"Day": "1",
"Part": "1",
"Question": "--- 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?",
"Answer": "2378066",
"Solution": "raw = open("i.txt").readlines()
l = sorted(int(x.split()[0]) for x in raw)
r = sorted(int(x.split()[1]) for x in raw)
print(sum(abs(l[i] - r[i]) for i in range(len(l))))",
"Language": "python:3.9"
}
Test Cases
The test cases are in the following file structure:
aoc.csv
test_cases/
βββ 2024/
β βββ ori_prompt/
β β βββ day1_part1.txt
β β βββ day1_part2.txt
β β βββ ...
β β βββ day25_part1.txt
β βββ test_case1/
β β βββ answers.csv
β β βββ day_1_input.txt
β β βββ ...
β β βββ day_25_input.txt
β βββ test_case2/
β β βββ answers.csv
β β βββ day_1_input.txt
β β βββ ...
β β βββ day_25_input.txt
β βββ test_case3/
β βββ answers.csv
β βββ day_1_input.txt
β βββ ...
β βββ day_25_input.txt
Getting Started
You can access the dataset on Hugging Face using the following commands:
from huggingface_hub import hf_hub_download
import pandas as pd
REPO_ID = "Supa-AI/advent_of_code"
FILENAME = "aoc.csv"
dataset = pd.read_csv(
hf_hub_download(repo_id=REPO_ID, filename=FILENAME, repo_type="dataset")
)
Source
The dataset is derived from a combination of various websites. We performed data cleaning and validation to ensure the quality of the dataset.
For full details on how we cleaned the data, visit our blog post.
Versioning and Maintenance
Current Version: 1.1.0
Release Date: January 19, 2025
Contact: We welcome any feedback or corrections to improve the dataset quality.
How can you contribute?
We welcome contributions that fill gaps in our current dataset, such as data from different years or in additional languages. Feel free to email your solutions to us at [email protected]. Once verified, we will incorporate them into the dataset.
- Downloads last month
- 36