day 6 puzzle 2

This commit is contained in:
Louis Heredero 2023-12-06 08:31:14 +01:00
parent c8ea1636e1
commit 86ca2c95af
3 changed files with 64 additions and 8 deletions

View File

@ -5,11 +5,11 @@ This repo contains my attempt at this year's Advent of Code (2023)
I will try and do some problems (probably not all of them) in Scala I will try and do some problems (probably not all of them) in Scala
## Progress: ## Progress:
#### Stars: 11 / 50 #### Stars: 12 / 50
| Mon | Tue | Wed | Thu | Fri | Sat | Sun | | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|:-----------------:|:-----------------:|:-----------:|:---:|:-----------------:|:-----------------:|:-----------------:| |:-----------------:|:-----------------:|:-----------------:|:---:|:-----------------:|:-----------------:|:-----------------:|
| | | | | 1<br>:star::star: | 2<br>:star::star: | 3<br>:star::star: | | | | | | 1<br>:star::star: | 2<br>:star::star: | 3<br>:star::star: |
| 4<br>:star::star: | 5<br>:star::star: | 6<br>:star: | 7 | 8 | 9 | 10 | | 4<br>:star::star: | 5<br>:star::star: | 6<br>:star::star: | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 | | 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 | | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | | | | | | | | 25 | | | | | | |

47
src/day6/Puzzle2.scala Normal file
View File

@ -0,0 +1,47 @@
package day6
import scala.io.{BufferedSource, Source}
object Puzzle2 {
case class Race(duration: Long, record: Long)
var race: Race = Race(0, 0)
def loadInput(path: String): Unit = {
val source: BufferedSource = Source.fromFile(path)
val lines: Array[String] = source.getLines().toArray
val duration: Long = lines(0).split(": +")(1).replace(" ", "").toLong
val record: Long = lines(1).split(": +")(1).replace(" ", "").toLong
race = Race(duration, record)
source.close()
}
def getMargin(race: Race): Int = {
// dist = (dur - press) * press
// dist-record > 0 <=> f(press) = dur*press - press^2 - record > 0
// x^2 - d*x + r = 0
// x = ( d +- sqrt(d^2 - 4r) ) / 2
val delta: Double = race.duration*race.duration - 4*race.record
val x0: Double = (race.duration - Math.sqrt(delta))/2
val x1: Double = (race.duration + Math.sqrt(delta))/2
val margin: Int = (Math.ceil(x1) - Math.floor(x0) - 1).toInt
return margin
}
def solve(path: String): Int = {
loadInput(path)
return getMargin(race)
}
def main(args: Array[String]): Unit = {
val solution: Int = solve("./res/day6/input1.txt")
println(solution)
}
}

View File

@ -0,0 +1,9 @@
package day6
import org.scalatest.funsuite.AnyFunSuite
class Puzzle2Test extends AnyFunSuite {
test("Puzzle2.solve") {
assert(Puzzle2.solve("tests_res/day6/input1.txt") == 71503)
}
}