From 9b19247c8f7954f1147abbf2c0a2043889b7b775 Mon Sep 17 00:00:00 2001 From: Adam Millerchip Date: Sun, 22 Dec 2024 19:21:13 +0900 Subject: [PATCH] 2024 Day 22 Part 2 --- 2024/day22.exs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/2024/day22.exs b/2024/day22.exs index 811dd63..47969ce 100755 --- a/2024/day22.exs +++ b/2024/day22.exs @@ -8,8 +8,7 @@ defmodule Day22 do def next(secret) do secret - |> Kernel.*(64) - |> mix(secret) + |> then(fn secret -> (secret * 64) |> mix(secret) end) |> prune() |> then(fn secret -> div(secret, 32) |> mix(secret) end) |> prune() @@ -20,8 +19,25 @@ defmodule Day22 do def mix(num, secret), do: Bitwise.bxor(secret, num) def prune(secret), do: rem(secret, 16_777_216) - def part2(_input) do - :not_implemented + def part2(input) do + input + |> Enum.map(fn secret -> + secret + |> Stream.iterate(&next/1) + |> Stream.map(&bananas/1) + |> Stream.take(2000) + |> Stream.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) + end + + def bananas(secret) do + secret |> Integer.to_string() |> String.last() |> String.to_integer() end def input do