Skip to content

Commit

Permalink
Day 1 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
horothesun committed Dec 1, 2024
1 parent a3f8e93 commit 6615283
Show file tree
Hide file tree
Showing 3 changed files with 1,047 additions and 6 deletions.
24 changes: 22 additions & 2 deletions src/main/scala/Day01.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
import cats.derived.*
import cats.syntax.all.*

object Day01:

def day01: Int = 42
case class LocationId(value: Int)

object LocationId:
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

object Input:
def parse(inputs: List[String]): Option[Input] =
inputs.traverse {
_.split(" {3}") match
case Array(l, r) => (l.toIntOption, r.toIntOption).tupled
case _ => None
}.map { lrs =>
Input(
left = lrs.map((l, _) => LocationId(l)),
right = lrs.map((_, r) => LocationId(r))
)
}

def totalDistance(inputs: List[String]): Option[Long] = Input.parse(inputs).map(_.totalDistance)
29 changes: 25 additions & 4 deletions src/test/scala/Day01Suite.scala
Original file line number Diff line number Diff line change
@@ -1,14 +1,35 @@
import Day01.*
import Day01Suite.*
import munit.ScalaCheckSuite
import org.scalacheck.Gen
import org.scalacheck.Prop.*

class Day01Suite extends ScalaCheckSuite:

test("day01 == 42"):
assertEquals(day01, 42)
test("parse small input"):
assertEquals(
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(_))
)
)
)

test("total distance for small input is 11"):
assertEquals(totalDistance(smallInput), Some(11L))

test("total distance for big input is 1_223_326"):
assertEquals(totalDistance(bigInput), Some(1_223_326L))

object Day01Suite:

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

val smallInput: List[String] = List(
"3 4",
"4 3",
"2 5",
"1 3",
"3 9",
"3 3"
)
Loading

0 comments on commit 6615283

Please sign in to comment.