Compare commits

...

10 Commits

Author SHA1 Message Date
Jake cc20656214 day 2 done, slightly late... 2025-12-03 09:55:11 +00:00
Jake 841bdbcfd6 2025 lets goooo 2025-12-01 11:42:09 +00:00
Jake Pullen b95908d5fc day 7 part 1 done. part 2 not 2024-12-07 11:28:45 +00:00
Jake Pullen 8c92951db5 day 6 done. im sure part 2 could be done better 2024-12-06 11:12:05 +00:00
Jake Pullen e7e179e84a day 5 done 2024-12-05 12:14:02 +00:00
Jake Pullen 7b930bd625 day 4 done 2024-12-04 13:16:22 +00:00
Jake Pullen 6959815188 Day 3 Done 2024-12-03 16:34:07 +00:00
Jake Pullen 582411d634 working on the get puzzel text revamp 2024-12-02 15:17:56 +00:00
Jake Pullen 8e2f448f8b day 2 done 2024-12-02 10:49:38 +00:00
Jake Pullen 3d180b17c5 advent_of_code_2024_day_1 2024-12-01 08:03:27 +00:00
25 changed files with 1267 additions and 11 deletions
+2
View File
@@ -1,6 +1,7 @@
session_cookie.txt
puzzle_text.md
input.txt
Untitled-1.py
# Byte-compiled / optimized / DLL files
__pycache__/
@@ -162,3 +163,4 @@ cython_debug/
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
+1
View File
@@ -0,0 +1 @@
3.14
+37
View File
@@ -0,0 +1,37 @@
with open(r'2024/01/input.txt', 'r') as file:
input = file.read()
test_input = '''3 4
4 3
2 5
1 3
3 9
3 3'''
# first split the input into two lists, left and right
left_list = []
right_list = []
for line in input.split('\n'):
left, right = line.split(' ')
left_list.append(int(left))
right_list.append(int(right))
# now sort each list acecnding
left_list.sort()
right_list.sort()
# print('left ',left_list)
# print('right',right_list)
# now compare each element in the left list with the corresponding element in the right list
# we need to get the difference between the two elements
diff_list = []
for i in range(len(left_list)):
diff_list.append(abs(left_list[i] - right_list[i]))
# print(diff_list)
# now we sum up all the items in the list
print(sum(diff_list))
+30
View File
@@ -0,0 +1,30 @@
with open(r'2024/01/input.txt', 'r') as file:
input = file.read()
test_input = '''3 4
4 3
2 5
1 3
3 9
3 3'''
# first split the input into two lists, left and right
left_list = []
right_list = []
for line in input.split('\n'):
left, right = line.split(' ')
left_list.append(int(left))
right_list.append(int(right))
# for every item in the left list we need to count how many times it appears in the right list
score = []
for i in left_list:
if i in right_list:
score.append(i * right_list.count(i))
#print(score)
print(sum(score))
+56
View File
@@ -0,0 +1,56 @@
with open(r'2024/02\input.txt', 'r') as file:
input = file.read()
test_input = '''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'''
# for each line we want to compare the current number to the next number
# if the number is between 1 and 3 difference it is valid
# we also need to know and store if it is ascending or descending
# because all numbers need to be ascending or descending and not mixed
# this will mean the line is valid
valid_list_count = 0
for line in input.split('\n'):
safe = False
line = line.split()
list_line = [int(i) for i in line]
# check all numbers in the line are ascending or descending
if list_line == sorted(list_line) or list_line == sorted(list_line, reverse=True):
#print(list_line, 'ascending or descending')
safe = True
print(list_line, 'steady')
else:
safe = False
print(list_line, 'unsteady')
continue
for i, num in enumerate(list_line):
if i == 0:
continue
check = abs(num - list_line[i-1])
if check >= 4 or check == 0:
#print(check)
safe = False
else:
#print(check)
safe = True
if not safe:
print(list_line, 'unsafe, big jumps')
break
if safe:
print(list_line, 'safe')
valid_list_count += 1
print(valid_list_count)
#print(valid_list_count)
+89
View File
@@ -0,0 +1,89 @@
testing = 0
if testing == 0:
with open(r'2024/02\input.txt', 'r') as file:
input = file.read()
else:
input = '''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'''
# for each line we want to compare the current number to the next number
# if the number is between 1 and 3 difference it is valid
# we also need to know and store if it is ascending or descending
# because all numbers need to be ascending or descending and not mixed
# this will mean the line is valid
valid_list_count = 0
retest_list = []
def test_line(line):
safe = False
# check all numbers in the line are ascending or descending
if line == sorted(line) or line == sorted(line, reverse=True):
#print(line, 'ascending or descending')
safe = True
print(line, 'steady')
else:
safe = False
print(line, 'unsteady')
#retest_list.append(line)
return 0
for i, num in enumerate(line):
if i == 0:
continue
check = abs(num - line[i-1])
if check >= 4 or check == 0:
#print(check)
safe = False
else:
#print(check)
safe = True
if not safe:
print(line, 'unsafe, big jumps')
#retest_list.append(line)
return 0
return 1
reports = []
# convert the input to a list of lists
for line in input.split('\n'):
data = line.split()
reads = [int(i) for i in data]
reports.append(reads)
#print(reports)
for report in reports:
safe = test_line(report)
if safe:
print(report, 'safe')
valid_list_count += 1
else:
#add the list to the retest list
retest_list.append(report)
print(retest_list)
# # we need to iterate over the retest list
# but this time removing one number and doing the test again,
# if it is safe we can add it to our safe count and move on
# if it is unsafe, we need to add back in our removed number and remove the next number
for list in retest_list:
for i, num in enumerate(list):
# remove the number
test_list = list.copy()
test_list.pop(i)
safe = test_line(test_list)
if safe:
print(test_list, 'safe')
valid_list_count += 1
break
print(valid_list_count)
+26
View File
@@ -0,0 +1,26 @@
testing = 0
if testing ==0:
with open(r'2024/03\input.txt', 'r') as file:
input = file.read()
else:
input = 'xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))'
# find every exact instance of mul() and multiply the two numbers together
import re
# Regular expression to find all instances of mul() with its arguments
pattern = r'mul\((\d+),(\d+)\)'
matches = re.findall(pattern, input)
numbers = [(int(x), int(y)) for x, y in matches]
print(numbers)
answer = 0
for x, y in numbers:
answer += x*y
print(answer)
+48
View File
@@ -0,0 +1,48 @@
testing = 0
if testing ==0:
with open(r'2024/03\input.txt', 'r') as file:
input = file.read()
else:
input = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"
# find every exact instance of mul() and multiply the two numbers together
import re
# Regular expression to find all instances of mul() with its arguments
pattern = r'mul\((\d+),(\d+)\)'
disable_pattern = r"don't\(\)"
enable_pattern = r"do\(\)"
enabled_list = []
disabled_list = []
is_active = True
# Split the input string by mul() to handle the state switching
parts = re.split(r'(mul\(\d+,\d+\))', input)
#print(parts)
for part in parts:
if re.search(disable_pattern, part):
is_active = False
elif re.search(enable_pattern, part):
is_active = True
elif re.match(pattern, part):
match = re.match(pattern, part)
numbers = (int(match.group(1)), int(match.group(2)))
if is_active:
enabled_list.append(numbers)
else:
disabled_list.append(numbers)
print("Enabled list:", enabled_list)
print("Disabled list:", disabled_list)
answer = 0
for x, y in enabled_list:
answer += x*y
print(answer)
+69
View File
@@ -0,0 +1,69 @@
testing = 0
if not testing:
with open(r'2024/04\input.txt', 'r') as file:
input = file.read()
else:
input = '''....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'''
# word search,
# allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words
# test input has 18 words
def count_occurance(input, WORD = 'XMAS'):
rows = len(input)
cols = len(input[0])
word_len = len(WORD)
directions = {
'north': (0, -1),
'north_east': (1, -1),
'east': (1, 0),
'south_east': (1, 1),
'south': (0, 1),
'south_west': (-1, 1),
'west': (-1, 0),
'north_west': (-1, -1),
}
def am_i_still_in_grid(x,y):
'Returns True if the coordinates are within the grid'
return 0 <= x < rows and 0 <= y < cols
def search_from(start_x, start_y, delta_x, delta_y):
"""
Check if the word can be found starting from (start_x, start_y)
in the direction specified by (delta_x, delta_y).
"""
for i in range(word_len):
# Calculate the new coordinates
new_x = start_x + i * delta_x
new_y = start_y + i * delta_y
# Check if the new coordinates are within the grid and match the word
if not am_i_still_in_grid(new_x, new_y) or input[new_x][new_y] != WORD[i]:
return False
# If all characters match, return True
return True
word_count = 0
for x in range(rows):
for y in range(cols):
for direction in directions.values():
if search_from(x, y, direction[0], direction[1]):
word_count += 1
return word_count
lines = input.split('\n')
print(count_occurance(lines))
+65
View File
@@ -0,0 +1,65 @@
testing = 0
if not testing:
with open(r'2024/04\input.txt', 'r') as file:
input = file.read()
else:
input = '''.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.
..........'''
# word search,
# allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words
# test input has 18 words
# part 2 calls for looking for 2x 'MAS' in the shape of an 'X'
# we can now ignore the NESW directions
# we should just check the diagonals of any 'A' we find
# if it has 2 'MAS' in the diagonals, we have a match
# turn the input into a list of lists so we can grid reference it
lines = input.split('\n')
grid = [list(line) for line in lines]
directions = {
'north_east': (1, -1),
'south_west': (-1, 1),
'south_east': (1, 1),
'north_west': (-1, -1),
}
grid_x_len = len(grid[0])
grid_y_len = len(grid)
# print(grid)
xmas_count = 0
# search for 'A's
for y, row in enumerate(grid):
for x, cell in enumerate(row):
if cell != 'A':
continue
# we found an 'A', check diagonals for 'M' and 'S'
if not (0 <= x + 1 < grid_x_len and 0 <= y + 1 < grid_y_len and
0 <= x - 1 < grid_x_len and 0 <= y - 1 < grid_y_len):
# we are at the edge of the grid, no need to check
continue
# take the character from the diagonal, including the middle 'A'
word_to_check = grid[y + 1][x + 1] + grid[y][x] + grid[y - 1][x - 1]
if word_to_check == 'MAS' or word_to_check == 'SAM':
# one diagonal has 'MAS', check the other
word_to_check = grid[y - 1][x + 1] + grid[y][x] + grid[y + 1][x - 1]
if word_to_check == 'MAS' or word_to_check == 'SAM':
xmas_count += 1
#print(word_to_check)
print(xmas_count)
+86
View File
@@ -0,0 +1,86 @@
testing = 0
if not testing:
with open(r"2024/05\input.txt", "r") as file:
input = file.read()
else:
input = """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"""
# first we split the input into the two parts
# the first part is the "rules" and the second part is the "updates"
rules, updates = input.split("\n\n")
# print(rules)
# print('^v^v^v^')
# print(updates)
# for each rule the left side is the page that must come before the right side
# to check the updates are correct we need to check that the left side of the update is before the right side
# if all updatesare correct then the rules are correct and we need to store the 'middle' number
# lets assign each update to a list of numbers
update_lists = []
for update in updates.split("\n"):
update_lists.append(list(map(int, update.split(","))))
#print(update_lists)
# lets also assign the rules to a list of tuples of numbers
rule_tuples = []
for rule in rules.split("\n"):
rule_tuples.append(tuple(map(int, rule.split("|"))))
#print(rule_tuples)
valid_updates = []
# now for each update we need to check that it follows the rules
for update in update_lists:
valid = True
# we need to check that the update is ordered correctly based on the rules
for rule in rule_tuples:
# if the update does not contain the any number in the rules we can ignore that rule
if rule[0] not in update or rule[1] not in update:
continue
# if the left side is before the right side then we can break out of the loop
if update.index(rule[0]) < update.index(rule[1]):
continue
# if the right side is before the left side then we can break out of the loop
if update.index(rule[0]) > update.index(rule[1]):
valid = False
break
if valid:
valid_updates.append(update)
print('The valid updates are',valid_updates)
numbers_to_sum = []
for update in valid_updates:
update_len = len(update)
# we need to find the middle number
middle = update_len // 2
numbers_to_sum.append(update[middle])
print('The numbers to sum are',numbers_to_sum)
print('The sum of the numbers is',sum(numbers_to_sum))
+106
View File
@@ -0,0 +1,106 @@
testing = 0
if not testing:
with open(r"2024/05\input.txt", "r") as file:
input = file.read()
else:
input = """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"""
# first we split the input into the two parts
# the first part is the "rules" and the second part is the "updates"
rules, updates = input.split("\n\n")
# print(rules)
# print('^v^v^v^')
# print(updates)
# for each rule the left side is the page that must come before the right side
# to check the updates are correct we need to check that the left side of the update is before the right side
# if all updatesare correct then the rules are correct and we need to store the 'middle' number
# lets assign each update to a list of numbers
update_lists = []
for update in updates.split("\n"):
update_lists.append(list(map(int, update.split(","))))
#print(update_lists)
# lets also assign the rules to a list of tuples of numbers
rule_tuples = []
for rule in rules.split("\n"):
rule_tuples.append(tuple(map(int, rule.split("|"))))
#print(rule_tuples)
def check_and_rearrange(update, rule):
if rule[0] in update and rule[1] in update:
index_0 = update.index(rule[0])
index_1 = update.index(rule[1])
if index_0 > index_1:
# Swap the elements to follow the rule
update[index_0], update[index_1] = update[index_1], update[index_0]
return False # Indicate that a change was made
return True # No change needed
#first pass, any updates that pass the rules are valid
valid_updates = []
incorrectly_ordered_updates = []
for update in update_lists:
valid = True
# we need to check that the update is ordered correctly based on the rules
for rule in rule_tuples:
# if the update does not contain the any number in the rules we can ignore that rule
if rule[0] not in update or rule[1] not in update:
continue
# if the left side is before the right side then we can break out of the loop
if update.index(rule[0]) < update.index(rule[1]):
continue
# if the right side is before the left side then we can break out of the loop
if update.index(rule[0]) > update.index(rule[1]):
valid = False
incorrectly_ordered_updates.append(update)
break
if valid:
valid_updates.append(update)
# reorder the incorrectly-ordered updates
for update in incorrectly_ordered_updates:
changed = True
while changed:
changed = False
for rule in rule_tuples:
if not check_and_rearrange(update, rule):
changed = True
# Extract the middle number from each reordered update and sum them
numbers_to_sum = []
for update in incorrectly_ordered_updates:
update_len = len(update)
middle = update_len // 2
numbers_to_sum.append(update[middle])
print('The numbers to sum are', numbers_to_sum)
print('The sum of the numbers is', sum(numbers_to_sum))
+66
View File
@@ -0,0 +1,66 @@
testing = 0
if not testing:
with open(r"2024/06\input.txt", "r") as file:
input = file.read()
else:
input = """....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#..."""
OBSTACLE = "#"
# first we should turn the input into a list of lists so we can use grid references
input = input.split("\n")
grid = [list(x) for x in input]
# for x in grid:
# print(x)
# we need to find the starting position
# our starting position is the only '^' in the grid
for x in range(len(grid)):
for y in range(len(grid[x])):
if grid[x][y] == "^":
position = (x, y)
break
print('start at',position)
# We start by travelling north until we hit an obstacle '#'
# then we turn right and travel east until we hit an obstacle
# we keep turning right and travelling until we hit an obstacle
# once we make it off the grid we stop
# count how many unique squares we visit
def count_unique_squares(grid, start):
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] # North, East, South, West
direction_index = 0 # Start by moving north
x, y = start
visited = set()
while True:
visited.add((x, y))
dx, dy = directions[direction_index]
new_x, new_y = x + dx, y + dy
# if new position is off the grid, we stop
if (new_x < 0 or new_x >= len(grid) or new_y < 0 or new_y >= len(grid[0])):
print(f"Moved off the grid to ({new_x}, {new_y}), stopping")
break
# if we hit an obstacle, we turn right
elif grid[new_x][new_y] == OBSTACLE:
direction_index = (direction_index + 1) % 4 # Turn right
print(f"Hit obstacle at ({new_x}, {new_y}), turning right to direction {directions[direction_index]}")
else:
x, y = new_x, new_y
print(f"Moved to ({x}, {y})")
return len(visited)
print(count_unique_squares(grid, position))
+74
View File
@@ -0,0 +1,74 @@
testing = 0
if not testing:
with open(r"2024/06\input.txt", "r") as file:
input = file.read()
else:
input = """....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#..."""
OBSTACLE = "#"
# first we should turn the input into a list of lists so we can use grid references
split_input = input.split("\n")
grid = [list(x) for x in split_input]
ROWS = len(grid)
COLUMNS = len(grid[0])
# for x in grid:
# print(x)
# we need to find the starting position
# our starting position is the only '^' in the grid
for x in range(len(grid)):
for y in range(len(grid[x])):
if grid[x][y] == "^":
position = (x, y)
break
#print('start at',position)
# We start by travelling north until we hit an obstacle '#'
# then we turn right and travel east until we hit an obstacle
# we keep turning right and travelling until we hit an obstacle
# once we make it off the grid we stop
# count how many unique squares we visit
loops = 0
for row in range(ROWS):
for col in range(COLUMNS):
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)] # North, East, South, West
direction_index = 0 # Start by moving north
x, y = position
visited = set()
visited_with_direction = set() # used for loop detection
while True:
visited.add((x, y))
if (x, y, direction_index) in visited_with_direction:
#print(f"Loop detected at ({x}, {y}) in direction {directions[direction_index]}")
loops += 1
break
visited_with_direction.add((x, y, direction_index))
dx, dy = directions[direction_index]
new_x, new_y = x + dx, y + dy
# if new position is off the grid, we stop
if (new_x < 0 or new_x >= len(grid) or new_y < 0 or new_y >= len(grid[0])):
#print(f"Moved off the grid to ({new_x}, {new_y}), stopping")
break
# if we hit an obstacle, we turn right
elif (grid[new_x][new_y] == OBSTACLE or (new_x, new_y) == (row,col)):
direction_index = (direction_index + 1) % 4 # Turn right
#print(f"Hit obstacle at ({new_x}, {new_y}), turning right to direction {directions[direction_index]}")
else:
x, y = new_x, new_y
#print(f"Moved to ({x}, {y})")
print('part 1 answer',len(visited))
print('part 2 answer',loops)
+76
View File
@@ -0,0 +1,76 @@
import logging
# Configure logging
logging.basicConfig(filename='debug.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
testing = 1
if not testing:
with open(r"2024/07/input.txt", "r") as file:
input = file.read()
else:
input = '''190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20'''
# first we organise the input to something more usable
input = input.split('\n')
#print(input)
input = [x.split(': ') for x in input if x.strip()]
#print(input)
input = [(int(x[0]), list(map(int, x[1].split()))) for x in input]
#print(input)
# # Find and print the largest target number
# largest_target = max(input.keys())
# print(f'The largest target number is: {largest_target}')
OPERATORS = ['+', '*']
def generate_expressions(numbers, current_expr=""):
if len(numbers) == 1:
yield current_expr + str(numbers[0])
else:
for operator in OPERATORS:
new_expr = current_expr + str(numbers[0]) + operator
yield from generate_expressions(numbers[1:], new_expr)
def evaluate_left_to_right(expr):
tokens = expr.split()
total = int(tokens[0])
i = 1
while i < len(tokens):
operator = tokens[i]
next_number = int(tokens[i + 1])
if operator == '+':
total += next_number
elif operator == '*':
total *= next_number
i += 2
return total
correct_results = []
for target, numbers in input:
logging.info(f'Processing target: {target} with numbers: {numbers}')
for expr in generate_expressions(numbers):
expr_with_spaces = expr.replace('+', ' + ').replace('*', ' * ')
result = evaluate_left_to_right(expr_with_spaces)
if int(result) == int(target):
correct_results.append(target)
logging.info(f'Tried {expr} = {result} matches {target}')
# we can break here because we only need to find one correct expression
break
else:
pass
logging.info(f'Tried {expr} = {result}, but target is {target}')
print(f'Sum of correct results: {sum(correct_results)}')
# too low 2501605300634
# print(2501605300634 - 2501605301465)
+82
View File
@@ -0,0 +1,82 @@
import logging
# Configure logging
logging.basicConfig(filename='debug.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
testing = 1
if not testing:
with open(r"2024/07/input.txt", "r") as file:
input = file.read()
else:
input = '''190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20'''
# first we organise the input to something more usable
input = input.split('\n')
#print(input)
input = [x.split(': ') for x in input if x.strip()]
#print(input)
input = [(int(x[0]), list(map(int, x[1].split()))) for x in input]
#print(input)
# # Find and print the largest target number
# largest_target = max(input.keys())
# print(f'The largest target number is: {largest_target}')
OPERATORS = ['+', '*', '|']
def generate_expressions(numbers, current_expr=""):
if len(numbers) == 1:
yield current_expr + str(numbers[0])
else:
for operator in OPERATORS:
if operator == '|' and len(numbers) > 1:
# Concatenate the current number with the next number
concatenated_number = int(str(numbers[0]) + str(numbers[1]))
new_expr = current_expr + str(concatenated_number)
yield from generate_expressions(numbers[2:], new_expr)
elif len(numbers) > 1:
new_expr = current_expr + str(numbers[0]) + operator
yield from generate_expressions(numbers[1:], new_expr)
def evaluate_left_to_right(expr):
tokens = expr.split()
total = int(tokens[0])
i = 1
while i < len(tokens):
operator = tokens[i]
next_number = int(tokens[i + 1])
if operator == '+':
total += next_number
elif operator == '*':
total *= next_number
i += 2
return total
correct_results = []
for target, numbers in input:
logging.info(f'Processing target: {target} with numbers: {numbers}')
for expr in generate_expressions(numbers):
expr_with_spaces = expr.replace('+', ' + ').replace('*', ' * ')
result = evaluate_left_to_right(expr_with_spaces)
if int(result) == int(target):
correct_results.append(target)
logging.info(f'Tried {expr} = {result} matches {target}')
# we can break here because we only need to find one correct expression
break
else:
pass
logging.info(f'Tried {expr} = {result}, but target is {target}')
print(f'Sum of correct results: {sum(correct_results)}')
# too low 2501605300634
# print(2501605300634 - 2501605301465)
+68
View File
@@ -0,0 +1,68 @@
testing = False
if not testing:
with open(r"2025/01/input.txt", "r") as file:
input = file.read()
else:
input = '''L68
L30
R48
L5
R60
L55
L1
L99
R14
L82'''
answer:int = 0
TEST_EXPECTED_ANSWER:int = 3
# make a list to simulate dial?
dial = [i for i in range(100)]
#print(dial)
direction = {
'L':'-=',
'R':'+='
}
position:int = 50
def perform_operation(value, operator, operand):
if operator == "+=":
return value + operand
elif operator == "-=":
return value - operand
else:
raise ValueError("Unsupported operator")
def move_dial(position, movement):
#print(movement)
direction_to_move = movement[0]
amount_to_move = movement[1:]
#print(direction_to_move)
#print(amount_to_move)
decide = direction[direction_to_move]
#print(decide)
new_position = perform_operation(int(position), decide, int(amount_to_move))
return new_position % 100
win_counter:int = 0
for step in input.split('\n'):
#print(position)
position = move_dial(position, step)
#print(position)
#print(dial[position])
if dial[position] == 0:
win_counter += 1
answer = win_counter
if testing:
if answer == TEST_EXPECTED_ANSWER:
print('test successful')
else:
print(f'wrong... expected {TEST_EXPECTED_ANSWER} received {answer}')
else:
print(answer)
+67
View File
@@ -0,0 +1,67 @@
testing = False
if not testing:
with open(r"2025/01/input.txt", "r") as file:
input = file.read()
else:
input = '''L68
L30
R48
L5
R60
L55
L1
L99
R14
L82'''
answer:int = 0
TEST_EXPECTED_ANSWER:int = 6
# make a list to simulate dial?
dial = [i for i in range(100)]
position:int = 50
zero_count: int = 0
def move_dial_with_zero_count(current_position, movement):
direction_to_move = movement[0]
amount_to_move = int(movement[1:])
# Determine the direction
if direction_to_move == 'L':
step = -1
elif direction_to_move == 'R':
step = 1
else:
raise ValueError("Invalid direction")
# Count how many times we hit 0 during this rotation
count = 0
current = current_position
# Go through each step of the rotation
for _ in range(amount_to_move):
current = (current + step) % 100
if current == 0:
count += 1
return current, count
# Process each step
for step in input.strip().split('\n'):
#print(f"Before: {position}")
position, zero_count_increment = move_dial_with_zero_count(position, step)
zero_count += zero_count_increment
#print(f"After: {position} (zero hits: {zero_count_increment})")
answer = zero_count
if testing:
if answer == TEST_EXPECTED_ANSWER:
print('test successful')
else:
print(f'wrong... expected {TEST_EXPECTED_ANSWER} received {answer}')
else:
print(answer)
+50
View File
@@ -0,0 +1,50 @@
testing = False
if not testing:
with open(r"2025/02/input.txt", "r") as file:
input = file.read()
else:
input = '''11-22,95-115,998-1012,1188511880-1188511890,222220-222224,1698522-1698528,446443-446449,38593856-38593862,565653-565659,824824821-824824827,2121212118-2121212124'''
product_id_list = input.split(',')
bad_products_list = []
def is_invalid_id(id_num):
"""
Check if an ID is invalid (made of some sequence repeated twice)
"""
id_str = str(id_num)
length = len(id_str)
# If length is odd, can't be made of two equal parts
if length % 2 != 0:
return False
# Split into two halves and check if they're identical
half_length = length // 2
first_half = id_str[:half_length]
second_half = id_str[half_length:]
return first_half == second_half
for product_id in product_id_list:
# print(product_id)
first_id,second_id = product_id.split('-')
print(first_id, 'to', second_id)
for product in range(int(first_id), int(second_id)+1):
# print(product)
if is_invalid_id(product):
print(f'{product} invalid')
bad_products_list.append(product)
else:
pass
# print(f'product {product} looks valid')
print(bad_products_list)
total_sum = 0
for bad_id in bad_products_list:
total_sum += int(bad_id)
print(total_sum)
+56
View File
@@ -0,0 +1,56 @@
testing = False
if not testing:
with open(r"2025/02/input.txt", "r") as file:
input = file.read()
else:
input = '''11-22,95-115,998-1012,1188511880-1188511890,222220-222224,1698522-1698528,446443-446449,38593856-38593862,565653-565659,824824821-824824827,2121212118-2121212124'''
product_id_list = input.split(',')
bad_products_list = []
def is_invalid_id(id_num):
"""
Check if an ID is invalid (made of some sequence repeated at least twice)
"""
id_str = str(id_num)
length = len(id_str)
# Try all possible pattern lengths from 1 to half the string length
for pattern_length in range(1, length // 2 + 1):
# Check if the string can be divided evenly by this pattern length
if length % pattern_length == 0:
# Get the pattern (first part)
pattern = id_str[:pattern_length]
# Calculate how many times this pattern should repeat
num_repeats = length // pattern_length
# If it repeats at least twice, it's invalid
if num_repeats >= 2:
# Check if the entire string is made up of this pattern repeated
if pattern * num_repeats == id_str:
return True
return False
for product_id in product_id_list:
# print(product_id)
first_id,second_id = product_id.split('-')
print(first_id, 'to', second_id)
for product in range(int(first_id), int(second_id)+1):
# print(product)
if is_invalid_id(product):
print(f'{product} invalid')
bad_products_list.append(product)
else:
pass
# print(f'product {product} looks valid')
print(bad_products_list)
total_sum = 0
for bad_id in bad_products_list:
total_sum += int(bad_id)
print(total_sum)
+7
View File
@@ -0,0 +1,7 @@
testing = True
if not testing:
with open(r"2025/03/input.txt", "r") as file:
input = file.read()
else:
input = '''
'''
View File
+16 -11
View File
@@ -3,7 +3,7 @@ import requests
from datetime import datetime
def get_puzzle_text(year, day):
with open(r'advent_of_code/session_cookie.txt', 'r') as file:
with open(r'session_cookie.txt', 'r') as file:
session_cookie = file.read().strip()
url = f"https://adventofcode.com/{year}/day/{day}"
cookies = {'session': session_cookie}
@@ -12,7 +12,7 @@ def get_puzzle_text(year, day):
return response.text
def get_puzzle_input(year, day):
with open(r'advent_of_code/session_cookie.txt', 'r') as file:
with open(r'session_cookie.txt', 'r') as file:
session_cookie = file.read().strip()
url = f"https://adventofcode.com/{year}/day/{day}/input"
cookies = {'session': session_cookie}
@@ -23,7 +23,7 @@ def get_puzzle_input(year, day):
return puzzle_input
def save_puzzle_text(year, day):
folder = rf"advent_of_code\{year}\{day:02}"
folder = rf"{year}/{day:02}"
os.makedirs(folder, exist_ok=True)
input_file = os.path.join(folder, "puzzle_text.md")
puzzle_text = get_puzzle_text(year, day)
@@ -34,7 +34,7 @@ def save_puzzle_text(year, day):
file.write(puzzle_text)
def save_puzzle_input(year, day):
folder = rf"advent_of_code\{year}\{day:02}"
folder = rf"{year}/{day:02}"
os.makedirs(folder, exist_ok=True)
input_file = os.path.join(folder, "input.txt")
puzzle_input = get_puzzle_input(year, day)
@@ -43,7 +43,7 @@ def save_puzzle_input(year, day):
file.write(puzzle_input)
def save_part_2_puzzle_text(year, day):
folder = rf"advent_of_code\{year}\{day:02}"
folder = rf"{year}/{day:02}"
input_file = os.path.join(folder, "puzzle_text.md")
# grab the existing puzzle text
with open(input_file, "r") as file:
@@ -66,7 +66,7 @@ def save_part_2_puzzle_text(year, day):
def get_puzzle_part(year, day):
# Check if the puzzle text for the day equals "# Day {day} Puzzle Text."
folder = rf"advent_of_code\{year}\{day:02}"
folder = rf"{year}/{day:02}"
os.makedirs(folder, exist_ok=True)
input_file = os.path.join(folder, "puzzle_text.md")
# Create the file if it doesn't exist
@@ -82,16 +82,21 @@ def get_puzzle_part(year, day):
return 2
def create_solution_file(year, day, part):
folder = rf"advent_of_code\{year}\{day:02}"
folder = rf"{year}/{day:02}"
os.makedirs(folder, exist_ok=True)
solution_file = os.path.join(folder, f"part {part} solution.py")
solution_file = os.path.join(folder, f"part_{part}_solution.py")
input_file_path = os.path.join(folder, "input.txt")
# Check if the solution file already exists
if not os.path.exists(solution_file):
with open(solution_file, "w") as file:
file.write(f"""with open(r'{input_file_path}', 'r') as file:
input = file.read()
file.write(f"""testing = True
if not testing:
with open(r"{year}/{day:02}/input.txt", "r") as file:
input = file.read()
else:
input = '''
'''
""")
print(f"Created {solution_file}")
else:
@@ -105,7 +110,7 @@ current_day = datetime.now().day
def populate_data(year = current_year, day=current_day):
"""
Populates data for the Advent of Code puzzle.
Requires a session cookie to be saved in advent_of_code/session_cookie.txt
Requires a session cookie to be saved in session_cookie.txt
This function checks if the puzzle text for the day equals "# Day {day} Puzzle Text."
If it does, it saves the puzzle text and input for part 1.
+9
View File
@@ -0,0 +1,9 @@
[project]
name = "advent-of-code"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.14"
dependencies = [
"requests>=2.32.5",
]
Generated
+81
View File
@@ -0,0 +1,81 @@
version = 1
revision = 3
requires-python = ">=3.14"
[[package]]
name = "advent-of-code"
version = "0.1.0"
source = { virtual = "." }
dependencies = [
{ name = "requests" },
]
[package.metadata]
requires-dist = [{ name = "requests", specifier = ">=2.32.5" }]
[[package]]
name = "certifi"
version = "2025.11.12"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/a2/8c/58f469717fa48465e4a50c014a0400602d3c437d7c0c468e17ada824da3a/certifi-2025.11.12.tar.gz", hash = "sha256:d8ab5478f2ecd78af242878415affce761ca6bc54a22a27e026d7c25357c3316", size = 160538, upload-time = "2025-11-12T02:54:51.517Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/70/7d/9bc192684cea499815ff478dfcdc13835ddf401365057044fb721ec6bddb/certifi-2025.11.12-py3-none-any.whl", hash = "sha256:97de8790030bbd5c2d96b7ec782fc2f7820ef8dba6db909ccf95449f2d062d4b", size = 159438, upload-time = "2025-11-12T02:54:49.735Z" },
]
[[package]]
name = "charset-normalizer"
version = "3.4.4"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/13/69/33ddede1939fdd074bce5434295f38fae7136463422fe4fd3e0e89b98062/charset_normalizer-3.4.4.tar.gz", hash = "sha256:94537985111c35f28720e43603b8e7b43a6ecfb2ce1d3058bbe955b73404e21a", size = 129418, upload-time = "2025-10-14T04:42:32.879Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2a/35/7051599bd493e62411d6ede36fd5af83a38f37c4767b92884df7301db25d/charset_normalizer-3.4.4-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:da3326d9e65ef63a817ecbcc0df6e94463713b754fe293eaa03da99befb9a5bd", size = 207746, upload-time = "2025-10-14T04:41:33.773Z" },
{ url = "https://files.pythonhosted.org/packages/10/9a/97c8d48ef10d6cd4fcead2415523221624bf58bcf68a802721a6bc807c8f/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8af65f14dc14a79b924524b1e7fffe304517b2bff5a58bf64f30b98bbc5079eb", size = 147889, upload-time = "2025-10-14T04:41:34.897Z" },
{ url = "https://files.pythonhosted.org/packages/10/bf/979224a919a1b606c82bd2c5fa49b5c6d5727aa47b4312bb27b1734f53cd/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:74664978bb272435107de04e36db5a9735e78232b85b77d45cfb38f758efd33e", size = 143641, upload-time = "2025-10-14T04:41:36.116Z" },
{ url = "https://files.pythonhosted.org/packages/ba/33/0ad65587441fc730dc7bd90e9716b30b4702dc7b617e6ba4997dc8651495/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:752944c7ffbfdd10c074dc58ec2d5a8a4cd9493b314d367c14d24c17684ddd14", size = 160779, upload-time = "2025-10-14T04:41:37.229Z" },
{ url = "https://files.pythonhosted.org/packages/67/ed/331d6b249259ee71ddea93f6f2f0a56cfebd46938bde6fcc6f7b9a3d0e09/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d1f13550535ad8cff21b8d757a3257963e951d96e20ec82ab44bc64aeb62a191", size = 159035, upload-time = "2025-10-14T04:41:38.368Z" },
{ url = "https://files.pythonhosted.org/packages/67/ff/f6b948ca32e4f2a4576aa129d8bed61f2e0543bf9f5f2b7fc3758ed005c9/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ecaae4149d99b1c9e7b88bb03e3221956f68fd6d50be2ef061b2381b61d20838", size = 152542, upload-time = "2025-10-14T04:41:39.862Z" },
{ url = "https://files.pythonhosted.org/packages/16/85/276033dcbcc369eb176594de22728541a925b2632f9716428c851b149e83/charset_normalizer-3.4.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cb6254dc36b47a990e59e1068afacdcd02958bdcce30bb50cc1700a8b9d624a6", size = 149524, upload-time = "2025-10-14T04:41:41.319Z" },
{ url = "https://files.pythonhosted.org/packages/9e/f2/6a2a1f722b6aba37050e626530a46a68f74e63683947a8acff92569f979a/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c8ae8a0f02f57a6e61203a31428fa1d677cbe50c93622b4149d5c0f319c1d19e", size = 150395, upload-time = "2025-10-14T04:41:42.539Z" },
{ url = "https://files.pythonhosted.org/packages/60/bb/2186cb2f2bbaea6338cad15ce23a67f9b0672929744381e28b0592676824/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:47cc91b2f4dd2833fddaedd2893006b0106129d4b94fdb6af1f4ce5a9965577c", size = 143680, upload-time = "2025-10-14T04:41:43.661Z" },
{ url = "https://files.pythonhosted.org/packages/7d/a5/bf6f13b772fbb2a90360eb620d52ed8f796f3c5caee8398c3b2eb7b1c60d/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:82004af6c302b5d3ab2cfc4cc5f29db16123b1a8417f2e25f9066f91d4411090", size = 162045, upload-time = "2025-10-14T04:41:44.821Z" },
{ url = "https://files.pythonhosted.org/packages/df/c5/d1be898bf0dc3ef9030c3825e5d3b83f2c528d207d246cbabe245966808d/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:2b7d8f6c26245217bd2ad053761201e9f9680f8ce52f0fcd8d0755aeae5b2152", size = 149687, upload-time = "2025-10-14T04:41:46.442Z" },
{ url = "https://files.pythonhosted.org/packages/a5/42/90c1f7b9341eef50c8a1cb3f098ac43b0508413f33affd762855f67a410e/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:799a7a5e4fb2d5898c60b640fd4981d6a25f1c11790935a44ce38c54e985f828", size = 160014, upload-time = "2025-10-14T04:41:47.631Z" },
{ url = "https://files.pythonhosted.org/packages/76/be/4d3ee471e8145d12795ab655ece37baed0929462a86e72372fd25859047c/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:99ae2cffebb06e6c22bdc25801d7b30f503cc87dbd283479e7b606f70aff57ec", size = 154044, upload-time = "2025-10-14T04:41:48.81Z" },
{ url = "https://files.pythonhosted.org/packages/b0/6f/8f7af07237c34a1defe7defc565a9bc1807762f672c0fde711a4b22bf9c0/charset_normalizer-3.4.4-cp314-cp314-win32.whl", hash = "sha256:f9d332f8c2a2fcbffe1378594431458ddbef721c1769d78e2cbc06280d8155f9", size = 99940, upload-time = "2025-10-14T04:41:49.946Z" },
{ url = "https://files.pythonhosted.org/packages/4b/51/8ade005e5ca5b0d80fb4aff72a3775b325bdc3d27408c8113811a7cbe640/charset_normalizer-3.4.4-cp314-cp314-win_amd64.whl", hash = "sha256:8a6562c3700cce886c5be75ade4a5db4214fda19fede41d9792d100288d8f94c", size = 107104, upload-time = "2025-10-14T04:41:51.051Z" },
{ url = "https://files.pythonhosted.org/packages/da/5f/6b8f83a55bb8278772c5ae54a577f3099025f9ade59d0136ac24a0df4bde/charset_normalizer-3.4.4-cp314-cp314-win_arm64.whl", hash = "sha256:de00632ca48df9daf77a2c65a484531649261ec9f25489917f09e455cb09ddb2", size = 100743, upload-time = "2025-10-14T04:41:52.122Z" },
{ url = "https://files.pythonhosted.org/packages/0a/4c/925909008ed5a988ccbb72dcc897407e5d6d3bd72410d69e051fc0c14647/charset_normalizer-3.4.4-py3-none-any.whl", hash = "sha256:7a32c560861a02ff789ad905a2fe94e3f840803362c84fecf1851cb4cf3dc37f", size = 53402, upload-time = "2025-10-14T04:42:31.76Z" },
]
[[package]]
name = "idna"
version = "3.11"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/6f/6d/0703ccc57f3a7233505399edb88de3cbd678da106337b9fcde432b65ed60/idna-3.11.tar.gz", hash = "sha256:795dafcc9c04ed0c1fb032c2aa73654d8e8c5023a7df64a53f39190ada629902", size = 194582, upload-time = "2025-10-12T14:55:20.501Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },
]
[[package]]
name = "requests"
version = "2.32.5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "certifi" },
{ name = "charset-normalizer" },
{ name = "idna" },
{ name = "urllib3" },
]
sdist = { url = "https://files.pythonhosted.org/packages/c9/74/b3ff8e6c8446842c3f5c837e9c3dfcfe2018ea6ecef224c710c85ef728f4/requests-2.32.5.tar.gz", hash = "sha256:dbba0bac56e100853db0ea71b82b4dfd5fe2bf6d3754a8893c3af500cec7d7cf", size = 134517, upload-time = "2025-08-18T20:46:02.573Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl", hash = "sha256:2462f94637a34fd532264295e186976db0f5d453d1cdd31473c85a6a161affb6", size = 64738, upload-time = "2025-08-18T20:46:00.542Z" },
]
[[package]]
name = "urllib3"
version = "2.5.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/15/22/9ee70a2574a4f4599c47dd506532914ce044817c7752a79b6a51286319bc/urllib3-2.5.0.tar.gz", hash = "sha256:3fc47733c7e419d4bc3f6b3dc2b4f890bb743906a30d56ba4a5bfa4bbff92760", size = 393185, upload-time = "2025-06-18T14:07:41.644Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a7/c2/fe1e52489ae3122415c51f387e221dd0773709bad6c6cdaa599e8a2c5185/urllib3-2.5.0-py3-none-any.whl", hash = "sha256:e6b01673c0fa6a13e374b50871808eb3bf7046c4b125b216f6bf1cc604cff0dc", size = 129795, upload-time = "2025-06-18T14:07:40.39Z" },
]