This commit is contained in:
Paul-Henri Froidmont 2023-12-06 14:45:03 +01:00
parent 6565c94961
commit 6e5bb0fffe
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE
2 changed files with 52 additions and 0 deletions

2
input/day06 Normal file
View file

@ -0,0 +1,2 @@
Time: 61 67 75 71
Distance: 430 1036 1307 1150

50
src/day06.scala Normal file
View file

@ -0,0 +1,50 @@
package aoc
package day06
val dayNumber = "06"
@main def part1: Unit =
println(part1(loadInput(dayNumber)))
@main def part2: Unit =
println(part2(loadInput(dayNumber)))
def part1(input: String) =
val Array(times, distances) = input
.split("\n")
.map(_.dropWhile(_ != ' ').trim.split("""\W+""").map(_.toInt))
times
.zip(distances)
.map((time, distanceToBeat) =>
for
pushDuration <- (0 to time)
distance = (time - pushDuration) * pushDuration
if distance > distanceToBeat
yield pushDuration
)
.map(_.length)
.product
.toString
def part2(input: String) =
val Array(time, distance) = input
.split("\n")
.map(_.replaceAll(" ", "").dropWhile(!_.isDigit).toDouble)
// We are looking for x such that
// d < (t - x) * t
// Which is
// x² - t * x + d > 0
// This is a parabola and we need to find its roots
val disc = Math.sqrt(time * time - 4 * distance)
val root1 = time / 2 - disc / 2
val root2 = time / 2 + disc / 2
// Count integers between roots
val int1 = root1.ceil.toLong
val res1 = if int1 == root1 then int1 + 1 else int1
val int2 = root2.floor.toLong
val res2 = if int2 == root2 then int2 - 1 else int2
(res2 - res1 + 1L).toString