aoc-23: solve day 6

This commit is contained in:
Ivan R. 2024-02-06 11:10:29 +05:00
parent 891a0ecf91
commit c8a967dcaa
Signed by: lumin
GPG key ID: 927D3132247BDE4E
4 changed files with 103 additions and 0 deletions

View file

@ -0,0 +1,66 @@
import kotlin.math.ceil
import kotlin.math.sqrt
class Solution06(lines: List<String>) {
private val races = mutableListOf<Race>()
init {
val times = lines[0]
.replace("Time:", "")
.split(" ")
.filter{it.isNotEmpty()}
val records = lines[1]
.replace("Distance:", "")
.split(" ")
.filter{it.isNotEmpty()}
for (i in times.indices) {
races.add(
Race(records[i].toLong(), times[i].toLong())
)
}
}
fun getMultipliedNumbersOfWays(): Int {
var res = 1
println("races: $races")
for (race in races) {
var x1 = (race.duration - sqrt(race.duration * race.duration - 4.0 * race.distance)) / 2.0
val x2 = (race.duration + sqrt(race.duration * race.duration - 4.0 * race.distance)) / 2.0
if (ceil(x1) - x1 < 1e-4) {
x1 += 0.5
}
println("x1 = $x1, x2 = $x2")
res *= (ceil(x2) - ceil(x1)).toInt()
}
return res
}
fun getNumberOfWaysForOneRace(): Int {
val race = Race(
races.map{it.distance.toString()}.reduce{acc, s -> acc + s}.toLong(),
races.map{it.duration.toString()}.reduce{acc, s -> acc + s}.toLong(),
)
println("distance: ${race.distance}, duration: ${race.duration}")
var x1 = (race.duration - sqrt(race.duration * race.duration - 4.0 * race.distance)) / 2.0
val x2 = (race.duration + sqrt(race.duration * race.duration - 4.0 * race.distance)) / 2.0
if (ceil(x1) - x1 < 1e-4) {
x1 += 0.5
}
println("x1 = $x1, x2 = $x2")
return (ceil(x2) - ceil(x1)).toInt()
}
}
data class Race(val distance: Long, val duration: Long)

View file

@ -0,0 +1,2 @@
Time: 47 84 74 67
Distance: 207 1394 1209 1014

View file

@ -0,0 +1,2 @@
Time: 7 15 30
Distance: 9 40 200

View file

@ -0,0 +1,33 @@
import kotlin.test.Test
import kotlin.test.assertEquals
class Solution06Test{
@Test
fun testGetMultipliedNumbersOfWays() {
val text = ResourceReader().readFile("day-06/test.txt")
val res = Solution06(text).getMultipliedNumbersOfWays()
assertEquals(288, res)
}
@Test
fun solvePart1() {
val text = ResourceReader().readFile("day-06/input.txt")
val res = Solution06(text).getMultipliedNumbersOfWays()
println(res)
}
@Test
fun testGetNumberOfWaysForOneRace() {
val text = ResourceReader().readFile("day-06/test.txt")
val res = Solution06(text).getNumberOfWaysForOneRace()
assertEquals(71503, res)
}
@Test
fun solvePart2() {
val text = ResourceReader().readFile("day-06/input.txt")
val res = Solution06(text).getNumberOfWaysForOneRace()
println(res)
}
}