Skip to content

Commit 6a06527

Browse files
committed
Solve 2024 day 1 part 2
1 parent 57f21e2 commit 6a06527

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package eu.sim642.adventofcode2024
22

3+
import eu.sim642.adventofcodelib.IterableImplicits._
4+
35
object Day1 {
46

57
def totalListDistance(lists: Seq[(Int, Int)]): Int = {
@@ -9,6 +11,14 @@ object Day1 {
911
.sum
1012
}
1113

14+
def similarityScore(lists: Seq[(Int, Int)]): Int = {
15+
val (list1, list2) = lists.unzip
16+
val list2Count = list2.groupCount(identity).withDefaultValue(0)
17+
list1
18+
.map(i => i * list2Count(i))
19+
.sum
20+
}
21+
1222
def parsePair(s: String): (Int, Int) = s match {
1323
case s"$i $j" => (i.toInt, j.toInt)
1424
}
@@ -19,5 +29,6 @@ object Day1 {
1929

2030
def main(args: Array[String]): Unit = {
2131
println(totalListDistance(parseLists(input)))
32+
println(similarityScore(parseLists(input)))
2233
}
2334
}

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,12 @@ class Day1Test extends AnyFunSuite {
2020
test("Part 1 input answer") {
2121
assert(totalListDistance(parseLists(input)) == 1666427)
2222
}
23+
24+
test("Part 2 examples") {
25+
assert(similarityScore(parseLists(exampleInput)) == 31)
26+
}
27+
28+
test("Part 2 input answer") {
29+
assert(similarityScore(parseLists(input)) == 24316233)
30+
}
2331
}

0 commit comments

Comments
 (0)