diff --git a/src/main/scala/eu/sim642/adventofcode2024/Day22.scala b/src/main/scala/eu/sim642/adventofcode2024/Day22.scala index 0484f576..0c7ba679 100644 --- a/src/main/scala/eu/sim642/adventofcode2024/Day22.scala +++ b/src/main/scala/eu/sim642/adventofcode2024/Day22.scala @@ -21,11 +21,32 @@ object Day22 { def sumSecretsAfter(secrets: Seq[Secret], after: Int = 2000): Secret = secrets.map(secretAfter(_, after)).sum + def mostBananas(secrets: Seq[Secret]): Int = { + // TODO: optimize (~4.7s) + val secretMaps = secrets + .map({ initialSecret => + Iterator.iterate(initialSecret, 2000 + 1)(nextSecret) + .map(_ % 10) + .map(_.toInt) + .sliding(5) + .map({ prices => + val changes = (prices lazyZip prices.tail).map((a, b) => b - a) + changes -> prices.last + }) + .groupMapReduce(_._1)(_._2)((a, _) => a) + }) + val secretMaps2 = secretMaps + .flatten + .groupMapReduce(_._1)(_._2)(_ + _) + secretMaps2.values.max + } + def parseSecrets(input: String): Seq[Secret] = input.linesIterator.map(_.toLong).toSeq lazy val input: String = scala.io.Source.fromInputStream(getClass.getResourceAsStream("day22.txt")).mkString.trim def main(args: Array[String]): Unit = { println(sumSecretsAfter(parseSecrets(input))) + println(mostBananas(parseSecrets(input))) } } diff --git a/src/test/scala/eu/sim642/adventofcode2024/Day22Test.scala b/src/test/scala/eu/sim642/adventofcode2024/Day22Test.scala index 12490287..b81cbfd7 100644 --- a/src/test/scala/eu/sim642/adventofcode2024/Day22Test.scala +++ b/src/test/scala/eu/sim642/adventofcode2024/Day22Test.scala @@ -11,6 +11,12 @@ class Day22Test extends AnyFunSuite { |100 |2024""".stripMargin + val exampleInput2 = + """1 + |2 + |3 + |2024""".stripMargin + test("Part 1 examples") { assert(secretAfter(123, 1) == 15887950) assert(secretAfter(123, 2) == 16495136) @@ -28,4 +34,12 @@ class Day22Test extends AnyFunSuite { test("Part 1 input answer") { assert(sumSecretsAfter(parseSecrets(input)) == 21147129593L) } + + test("Part 2 examples") { + assert(mostBananas(parseSecrets(exampleInput2)) == 23) + } + + test("Part 2 input answer") { + assert(mostBananas(parseSecrets(input)) == 2445) + } }