Skip to content

Instantly share code, notes, and snippets.

@object
Created December 5, 2024 05:52
Show Gist options
  • Save object/319414b73e26568cf45d6b03635374ad to your computer and use it in GitHub Desktop.
Save object/319414b73e26568cf45d6b03635374ad to your computer and use it in GitHub Desktop.
Advent of Code 2024, day 05
with open("./data/input05.txt") as inputFile:
input = inputFile.read().splitlines()
orders = set()
updates = []
for line in input:
if '|' in line:
pages = line.split('|')
orders.add((int(pages[0]), int(pages[1])))
elif ',' in line:
update = []
pages = line.split(',')
for page in pages:
update.append(int(int(page)))
updates.append(update)
def in_order(update):
for order in orders:
if order[0] in update and order[1] in update:
n1 = update.index(order[0])
n2 = update.index(order[1])
if n1 > n2: return False
return True
def get_middle_page(update):
return update[int(len(update)/2)]
# Part 1
res = 0
for update in updates:
if in_order(update):
res += get_middle_page(update)
print(res)
# Part 2
def find_first_page(update):
for page in update:
is_first = True
for order in orders:
if order[0] in update and order[1] in update and page == order[1]:
is_first = False
if is_first:
return page
def reorder(before, after):
if len(before) == 0: return after
first_page = find_first_page(before)
after.append(first_page)
del before[before.index(first_page)]
return reorder(before, after)
res = 0
for update in updates:
if not(in_order(update)):
res += get_middle_page(reorder(update, []))
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment