Skip to content

Commit

Permalink
feat: 2024 day 1
Browse files Browse the repository at this point in the history
  • Loading branch information
scarf005 committed Dec 1, 2024
1 parent c71bfce commit 877b652
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
21 changes: 21 additions & 0 deletions 2024/day01.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package `2024`.day01

import prelude.*

def parse(s: String) = s lift { case s"$a $b" => (a.toInt, b.toInt) }

extension [A](xs: Iterable[A])
def counts: Map[A, Int] =
xs.groupMapReduce(identity)(_ => 1)(_ + _)

def part1(lefts: Vector[Int], rights: Vector[Int]) =
(lefts.sorted zip rights.sorted).map((a, b) => (b - a).abs).sum

def part2(lefts: Vector[Int], rights: Vector[Int]) =
(lefts.counts zipByKey rights.counts).sumBy { case (k, (a, b)) => k * a * b }

@main def main() =
val (lefts, rights) = readInput(this).getLines.toVector.flatMap(parse).unzip

println(part1(lefts, rights))
println(part2(lefts, rights))
21 changes: 21 additions & 0 deletions 2024/day01.test.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package `2024`.day01

import munit.FunSuite

class Tests extends FunSuite:
val example = Vector(
"3 4",
"4 3",
"2 5",
"1 3",
"3 9",
"3 3",
)

val (lefts, rights) = example.flatMap(parse).unzip

test("part 1"):
assertEquals(part1(lefts, rights), 11)

test("part 2"):
assertEquals(part2(lefts, rights), 31)

0 comments on commit 877b652

Please sign in to comment.