Skip to content

Commit

Permalink
Solve 2024 day 22 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 22, 2024
1 parent 18ab2ed commit 0103bd6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/main/scala/eu/sim642/adventofcode2024/Day22.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
}
}
14 changes: 14 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2024/Day22Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
}
}

0 comments on commit 0103bd6

Please sign in to comment.