File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed
main/scala/eu/sim642/adventofcode2024
test/scala/eu/sim642/adventofcode2024 Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -21,11 +21,32 @@ object Day22 {
21
21
def sumSecretsAfter (secrets : Seq [Secret ], after : Int = 2000 ): Secret =
22
22
secrets.map(secretAfter(_, after)).sum
23
23
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
+
24
44
def parseSecrets (input : String ): Seq [Secret ] = input.linesIterator.map(_.toLong).toSeq
25
45
26
46
lazy val input : String = scala.io.Source .fromInputStream(getClass.getResourceAsStream(" day22.txt" )).mkString.trim
27
47
28
48
def main (args : Array [String ]): Unit = {
29
49
println(sumSecretsAfter(parseSecrets(input)))
50
+ println(mostBananas(parseSecrets(input)))
30
51
}
31
52
}
Original file line number Diff line number Diff line change @@ -11,6 +11,12 @@ class Day22Test extends AnyFunSuite {
11
11
|100
12
12
|2024""" .stripMargin
13
13
14
+ val exampleInput2 =
15
+ """ 1
16
+ |2
17
+ |3
18
+ |2024""" .stripMargin
19
+
14
20
test(" Part 1 examples" ) {
15
21
assert(secretAfter(123 , 1 ) == 15887950 )
16
22
assert(secretAfter(123 , 2 ) == 16495136 )
@@ -28,4 +34,12 @@ class Day22Test extends AnyFunSuite {
28
34
test(" Part 1 input answer" ) {
29
35
assert(sumSecretsAfter(parseSecrets(input)) == 21147129593L )
30
36
}
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
+ }
31
45
}
You can’t perform that action at this time.
0 commit comments