Skip to content

Commit

Permalink
Solve 2023 day 6 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 6, 2023
1 parent 840f216 commit cb8122d
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/main/resources/eu/sim642/adventofcode2023/day6.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time: 48 93 85 95
Distance: 296 1928 1236 1391
26 changes: 26 additions & 0 deletions src/main/scala/eu/sim642/adventofcode2023/Day6.scala
Original file line number Diff line number Diff line change
@@ -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)))
}
}
19 changes: 19 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day6Test.scala
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit cb8122d

Please sign in to comment.