summaryrefslogtreecommitdiff
path: root/2024
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2024-12-13 16:47:51 +0100
committerSanto Cariotti <santo@dcariotti.me>2024-12-13 16:47:51 +0100
commitbfce436b111fd8d45ae5b9f61dd8d05323867891 (patch)
tree3e66e31e8761e826ec2ce8e8a327f5b0dda707b9 /2024
parent1f177db7f118ede6652b7217de5e8d9fcbe1ce2e (diff)
Add day1 for 2024main
Diffstat (limited to '2024')
-rw-r--r--2024/scala/.gitignore2
-rw-r--r--2024/scala/day1.scala38
2 files changed, 40 insertions, 0 deletions
diff --git a/2024/scala/.gitignore b/2024/scala/.gitignore
new file mode 100644
index 0000000..b3c6c86
--- /dev/null
+++ b/2024/scala/.gitignore
@@ -0,0 +1,2 @@
+.bsp/
+.scala-build/
diff --git a/2024/scala/day1.scala b/2024/scala/day1.scala
new file mode 100644
index 0000000..3803572
--- /dev/null
+++ b/2024/scala/day1.scala
@@ -0,0 +1,38 @@
+import scala.io.Source
+
+object Day1 {
+ def part1(lefts: Array[Int], rights: Array[Int]): Int = {
+ lefts
+ .zip(rights)
+ .map { case (l, r) =>
+ math.abs(l - r)
+ }
+ .sum
+ }
+
+ def part2(lefts: Array[Int], rights: Array[Int]): Int = {
+ val rightsCount = rights.groupBy(identity).map { case (k, v) =>
+ (k, v.size)
+ }
+ lefts
+ .map(x => x * rightsCount.getOrElse(x, 0))
+ .sum
+ }
+
+ def main(args: Array[String]): Unit = {
+ val lines =
+ Source
+ .fromFile(args(0))
+ .mkString
+ .split("\n")
+ .map(_.split(" ").map(_.toInt))
+
+ val (lefts_, rights_) = lines.map(arr => (arr(0), arr(1))).unzip
+ val lefts = lefts_.sorted
+ val rights = rights_.sorted
+
+ assert(part1(lefts, rights) == 3569916)
+ assert(part2(lefts, rights) == 26407426)
+ }
+}
+