Skip to content

Commit

Permalink
day22 part2
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasrenault committed Dec 22, 2024
1 parent f51b02a commit 4c883b9
Showing 1 changed file with 49 additions and 3 deletions.
52 changes: 49 additions & 3 deletions advent/advent2024/day22.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from collections import deque

from tqdm import tqdm

from advent.utils.utils import Advent

advent = Advent(22, 2024)
Expand All @@ -6,13 +10,55 @@
def main():
lines = advent.get_input_lines()
secrets = list(map(int, lines))

evolved = generate_random_secrets(secrets)
advent.submit(1, sum(evolved))

buyer_prices = get_buyer_prices(secrets)
sequences = set()
for buyer in buyer_prices:
sequences.update(buyer.keys())

best_bananas = 0
for sequence in tqdm(sequences):
bananas = 0
for buyer in buyer_prices:
bananas += buyer.get(sequence, 0)
if bananas > best_bananas:
best_bananas = bananas

advent.submit(2, best_bananas)


def get_buyer_prices(
secrets: list[int], steps: int = 2001
) -> list[dict[tuple[int, ...], int]]:
buyer_prices = []
for secret in tqdm(secrets):
previous = None
changes: deque[int] = deque([])
prices: dict[tuple[int, ...], int] = dict()
for _ in range(steps):
price = int(str(secret)[-1])
if previous is not None:
changes.append(price - previous)
if len(changes) > 4:
changes.popleft()
if len(changes) == 4 and tuple(changes) not in prices:
prices[tuple(changes)] = price
previous = price
secret = evolve(secret)
buyer_prices.append(prices)
return buyer_prices


def generate_random_secrets(secrets: list[int], steps: int = 2000) -> list[int]:
evolved = []
for secret in secrets:
for _ in range(2000):
for _ in range(steps):
secret = evolve(secret)
evolved.append(secret)

advent.submit(1, sum(evolved))
return evolved


def evolve(secret: int) -> int:
Expand Down

0 comments on commit 4c883b9

Please sign in to comment.