From cb8122da59bc3468e534fa3087d73c1f577655cd Mon Sep 17 00:00:00 2001 From: Simmo Saan Date: Wed, 6 Dec 2023 08:15:28 +0200 Subject: [PATCH] Solve 2023 day 6 part 1 --- .../eu/sim642/adventofcode2023/day6.txt | 2 ++ .../eu/sim642/adventofcode2023/Day6.scala | 26 +++++++++++++++++++ .../eu/sim642/adventofcode2023/Day6Test.scala | 19 ++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 src/main/resources/eu/sim642/adventofcode2023/day6.txt create mode 100644 src/main/scala/eu/sim642/adventofcode2023/Day6.scala create mode 100644 src/test/scala/eu/sim642/adventofcode2023/Day6Test.scala diff --git a/src/main/resources/eu/sim642/adventofcode2023/day6.txt b/src/main/resources/eu/sim642/adventofcode2023/day6.txt new file mode 100644 index 00000000..f3805ad9 --- /dev/null +++ b/src/main/resources/eu/sim642/adventofcode2023/day6.txt @@ -0,0 +1,2 @@ +Time: 48 93 85 95 +Distance: 296 1928 1236 1391 diff --git a/src/main/scala/eu/sim642/adventofcode2023/Day6.scala b/src/main/scala/eu/sim642/adventofcode2023/Day6.scala new file mode 100644 index 00000000..ec51cf7d --- /dev/null +++ b/src/main/scala/eu/sim642/adventofcode2023/Day6.scala @@ -0,0 +1,26 @@ +package eu.sim642.adventofcode2023 + +object Day6 { + + case class Race(time: Int, recordDistance: Int) { + def wins: Int = { + (0 to time).count(t => t * (time - t) > recordDistance) + } + } + + def multiplyRaceWins(races: Seq[Race]): Int = races.map(_.wins).product + + + def parseRaces(input: String): Seq[Race] = input.linesIterator.toSeq match { + case Seq(s"Time:$timesStr", s"Distance:$distancesStr") => + val times = timesStr.trim.split(" +").map(_.toInt).toSeq + val distances = distancesStr.trim.split(" +").map(_.toInt).toSeq + (times lazyZip distances).map(Race.apply) + } + + lazy val input: String = io.Source.fromInputStream(getClass.getResourceAsStream("day6.txt")).mkString.trim + + def main(args: Array[String]): Unit = { + println(multiplyRaceWins(parseRaces(input))) + } +} diff --git a/src/test/scala/eu/sim642/adventofcode2023/Day6Test.scala b/src/test/scala/eu/sim642/adventofcode2023/Day6Test.scala new file mode 100644 index 00000000..e349d85c --- /dev/null +++ b/src/test/scala/eu/sim642/adventofcode2023/Day6Test.scala @@ -0,0 +1,19 @@ +package eu.sim642.adventofcode2023 + +import Day6._ +import org.scalatest.funsuite.AnyFunSuite + +class Day6Test extends AnyFunSuite { + + private val exampleInput = + """Time: 7 15 30 + |Distance: 9 40 200""".stripMargin + + test("Part 1 examples") { + assert(multiplyRaceWins(parseRaces(exampleInput)) == 288) + } + + test("Part 1 input answer") { + assert(multiplyRaceWins(parseRaces(input)) == 2756160) + } +}