Day 06
This commit is contained in:
parent
6565c94961
commit
6e5bb0fffe
2 changed files with 52 additions and 0 deletions
2
input/day06
Normal file
2
input/day06
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
Time: 61 67 75 71
|
||||
Distance: 430 1036 1307 1150
|
||||
50
src/day06.scala
Normal file
50
src/day06.scala
Normal 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue