Skip to content

Instantly share code, notes, and snippets.

@Ranudar
Last active December 5, 2024 21:45
Show Gist options
  • Save Ranudar/130f7d0b3cbb839ccc8ea5c6821154a9 to your computer and use it in GitHub Desktop.
Save Ranudar/130f7d0b3cbb839ccc8ea5c6821154a9 to your computer and use it in GitHub Desktop.
My solution for day 5 of the 2024 Advent of Code. I couldn't wrap my head around how to order the instructions correctly in part 2, so I thought "why not simply let Python sort it out for me ;)".
from collections import defaultdict
with open(r'day_5') as f:
data = f.read()
first_part, second_part = data.split("\n\n")
first_part = [element.split("|") for element in first_part.split("\n")]
first_part = [[int(element) for element in rule] for rule in first_part]
second_part = second_part.split("\n")
second_part = [[int(element) for element in instruction.split(",")] for instruction in second_part]
# --- part 1 ---
rules = defaultdict(set)
for rule in first_part:
first, second = rule
rules[first].add(second)
faulty_instructions = []
def calculate_middle_values(instructions, rules):
result = 0
for instruction in second_part:
for index, num in enumerate(instruction):
if index == len(instruction) - 1: # last element reached
result += instruction[len(instruction) // 2] # add value of middle num to result
if not set(instruction[index + 1:]) <= rules[num]:
faulty_instructions.append(instruction) # could be used for part 2
break
return result
print(calculate_middle_values(second_part, rules))
# --- part 2 ---
class Position:
# use a class attribute to share it among all instances.
rules = defaultdict(set)
def __init__(self, num):
self.num = num
def __lt__(self, other):
"""if the other's number is in the corresponding set of self.num, return True"""
return other.num in self.rules[self.num]
first_part, second_part = data.split("\n\n")
first_part = [element.split("|") for element in first_part.split("\n")]
first_part = [[int(element) for element in rule] for rule in first_part]
# fill the Position's rules attribute
for rule in first_part:
first, second = rule
Position.rules[first].add(second)
second_part = second_part.split("\n")
second_part = [[Position(int(element)) for element in instruction.split(",")] for instruction in second_part]
result = 0
for instruction in second_part:
for i, num in enumerate(instruction):
# faulty = None
if any(num > (faulty := other_num) for other_num in instruction[i + 1:]):
# print([num.num for num in instruction])
# print(f"faulty instruction found: {num.num=} and {faulty.num=}\n\n")
sorted_instruction = sorted(instruction)
value_of_num = sorted_instruction[len(sorted_instruction) // 2].num
result += value_of_num
break
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment