Skip to content

Commit

Permalink
Day 1 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
horothesun committed Dec 1, 2024
1 parent 6615283 commit dc7c39c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
11 changes: 9 additions & 2 deletions src/main/scala/Day01.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ object Day01:
given Ordering[LocationId] = Ordering.by(_.value)

case class Input(left: List[LocationId], right: List[LocationId]):

def totalDistance: Long = left.sorted.zip(right.sorted).map((l, r) => Math.abs(l.value - r.value).toLong).sum

def similarityScore: Long =
val rightCount = right.groupBy(identity).map((k, vs) => (k, vs.length))
left.map(l => (l.value * rightCount.getOrElse(l, 0)).toLong).sum

object Input:
def parse(inputs: List[String]): Option[Input] =
inputs.traverse {
Expand All @@ -18,9 +23,11 @@ object Day01:
case _ => None
}.map { lrs =>
Input(
left = lrs.map((l, _) => LocationId(l)),
right = lrs.map((_, r) => LocationId(r))
left = lrs.map(_._1).map(LocationId.apply),
right = lrs.map(_._2).map(LocationId.apply)
)
}

def totalDistance(inputs: List[String]): Option[Long] = Input.parse(inputs).map(_.totalDistance)

def similarityScore(inputs: List[String]): Option[Long] = Input.parse(inputs).map(_.similarityScore)
10 changes: 8 additions & 2 deletions src/test/scala/Day01Suite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ class Day01Suite extends ScalaCheckSuite:
Input.parse(smallInput),
Some(
Input(
left = List(3, 4, 2, 1, 3, 3).map(LocationId(_)),
right = List(4, 3, 5, 3, 9, 3).map(LocationId(_))
left = List(3, 4, 2, 1, 3, 3).map(LocationId.apply),
right = List(4, 3, 5, 3, 9, 3).map(LocationId.apply)
)
)
)
Expand All @@ -21,6 +21,12 @@ class Day01Suite extends ScalaCheckSuite:
test("total distance for big input is 1_223_326"):
assertEquals(totalDistance(bigInput), Some(1_223_326L))

test("similarity score for small input is 31"):
assertEquals(similarityScore(smallInput), Some(31L))

test("similarity score for big input is 21_070_419"):
assertEquals(similarityScore(bigInput), Some(21_070_419L))

object Day01Suite:

val bigInput: List[String] = getLinesFromFile("src/test/scala/day01_input.txt")
Expand Down

0 comments on commit dc7c39c

Please sign in to comment.