Skip to content

Commit 0103bd6

Browse files
committed
Solve 2024 day 22 part 2
1 parent 18ab2ed commit 0103bd6

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/main/scala/eu/sim642/adventofcode2024/Day22.scala

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,32 @@ object Day22 {
2121
def sumSecretsAfter(secrets: Seq[Secret], after: Int = 2000): Secret =
2222
secrets.map(secretAfter(_, after)).sum
2323

24+
def mostBananas(secrets: Seq[Secret]): Int = {
25+
// TODO: optimize (~4.7s)
26+
val secretMaps = secrets
27+
.map({ initialSecret =>
28+
Iterator.iterate(initialSecret, 2000 + 1)(nextSecret)
29+
.map(_ % 10)
30+
.map(_.toInt)
31+
.sliding(5)
32+
.map({ prices =>
33+
val changes = (prices lazyZip prices.tail).map((a, b) => b - a)
34+
changes -> prices.last
35+
})
36+
.groupMapReduce(_._1)(_._2)((a, _) => a)
37+
})
38+
val secretMaps2 = secretMaps
39+
.flatten
40+
.groupMapReduce(_._1)(_._2)(_ + _)
41+
secretMaps2.values.max
42+
}
43+
2444
def parseSecrets(input: String): Seq[Secret] = input.linesIterator.map(_.toLong).toSeq
2545

2646
lazy val input: String = scala.io.Source.fromInputStream(getClass.getResourceAsStream("day22.txt")).mkString.trim
2747

2848
def main(args: Array[String]): Unit = {
2949
println(sumSecretsAfter(parseSecrets(input)))
50+
println(mostBananas(parseSecrets(input)))
3051
}
3152
}

src/test/scala/eu/sim642/adventofcode2024/Day22Test.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ class Day22Test extends AnyFunSuite {
1111
|100
1212
|2024""".stripMargin
1313

14+
val exampleInput2 =
15+
"""1
16+
|2
17+
|3
18+
|2024""".stripMargin
19+
1420
test("Part 1 examples") {
1521
assert(secretAfter(123, 1) == 15887950)
1622
assert(secretAfter(123, 2) == 16495136)
@@ -28,4 +34,12 @@ class Day22Test extends AnyFunSuite {
2834
test("Part 1 input answer") {
2935
assert(sumSecretsAfter(parseSecrets(input)) == 21147129593L)
3036
}
37+
38+
test("Part 2 examples") {
39+
assert(mostBananas(parseSecrets(exampleInput2)) == 23)
40+
}
41+
42+
test("Part 2 input answer") {
43+
assert(mostBananas(parseSecrets(input)) == 2445)
44+
}
3145
}

0 commit comments

Comments
 (0)