Skip to content

Commit

Permalink
Solve 2023 day 6 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
sim642 committed Dec 6, 2023
1 parent cb8122d commit ca341e9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/main/scala/eu/sim642/adventofcode2023/Day6.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,33 @@ 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)
}
case class Race(time: Long, recordDistance: Long) {
def wins: Long = // TODO: optimize with math
(0L to time).count(t => t * (time - t) > recordDistance)

def ++(that: Race): Race =
Race(
(time.toString + that.time.toString).toLong,
(recordDistance.toString + that.recordDistance.toString).toLong
)
}

def multiplyRaceWins(races: Seq[Race]): Int = races.map(_.wins).product
def multiplyRaceWins(races: Seq[Race]): Long = races.map(_.wins).product

def concatenatedRaceWin(races: Seq[Race]): Long = races.reduce(_ ++ _).wins


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
val times = timesStr.trim.split(" +").map(_.toLong).toSeq
val distances = distancesStr.trim.split(" +").map(_.toLong).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)))
println(concatenatedRaceWin(parseRaces(input)))
}
}
8 changes: 8 additions & 0 deletions src/test/scala/eu/sim642/adventofcode2023/Day6Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,12 @@ class Day6Test extends AnyFunSuite {
test("Part 1 input answer") {
assert(multiplyRaceWins(parseRaces(input)) == 2756160)
}

test("Part 2 examples") {
assert(concatenatedRaceWin(parseRaces(exampleInput)) == 71503)
}

test("Part 2 input answer") {
assert(concatenatedRaceWin(parseRaces(input)) == 34788142)
}
}

0 comments on commit ca341e9

Please sign in to comment.