igorb
Advent of Code 2024 - Day 22
Today was a nice break from Day 21. Part 2 is just brute-force, with a bit of optimization tracking what sequences return how many bananas per number: advent-of-code-2024/lib/advent_of_code2024/day22.ex at main · ibarakaiev/advent-of-code-2024 · GitHub
Most Liked
lud
I found a first optimization on reddit.
Instead of doing:
seq = {a,b,c,d} # last 4 price changes
Map.put(sequences, seq, price)
It is possible to do:
<<seq::integer-20>> = <<a::5, b::5, c::5, d::5>>
Map.put_new(sequences, seq, price)
That’s not a game changer but it definitely improve times.
bjorng
This was a nice break after the last two days.
The combined runtime for both parts is 2.4 seconds.
adamu
(lud beat me to it while typing)
It says that the bid is placed as soon as the sequence occurs. So even if there’s a better price for a later secret (same seed, later iteration) with the same sequence, that’s too late and shouldn’t be used.
adamu
Yep. I did part 1 just to prove to myself that part 2 was going to be “and now a bazillion secrets??”, but was pleasantly surprised.
My part 2 takes ~7 seconds on a Core i5.
For each secret, I built a map of changes to bananas, using Map.put_new/3 to make sure I didn’t count a repeated sequence. Then I merged all the maps together, and took the maximum.
input
|> Enum.map(fn secret ->
1..2000
|> Enum.map_reduce(secret, fn _, secret -> {rem(secret, 10), next(secret)} end)
|> elem(0)
|> Enum.chunk_every(5, 1, :discard)
|> Enum.reduce(%{}, fn [a, b, c, d, bananas], changes ->
Map.put_new(changes, {b - a, c - b, d - c, bananas - d}, bananas)
end)
end)
|> Enum.reduce(&Map.merge(&1, &2, fn _k, v1, v2 -> v1 + v2 end))
|> Enum.max_by(fn {_sequence, bananas} -> bananas end)
|> elem(1)







