Completed both parts of Day 6 puzzle
parent
013d806543
commit
4262c9e715
@ -0,0 +1,40 @@
|
|||||||
|
package day6
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.paas.celticinfo.fr/oabrivard/aoc2023/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RaceWinsCount(lines []string) int64 {
|
||||||
|
result := int64(1)
|
||||||
|
times := utils.ParseInt64Array(strings.TrimPrefix(lines[0], "Time: "), " ")
|
||||||
|
dists := utils.ParseInt64Array(strings.TrimPrefix(lines[1], "Distance: "), " ")
|
||||||
|
|
||||||
|
for i, t := range times {
|
||||||
|
d := dists[i]
|
||||||
|
|
||||||
|
// Solve -x^2 + tx - d > 0
|
||||||
|
|
||||||
|
// delta = b^2 - 4ac
|
||||||
|
delta := utils.Int64Pow(t, 2) - 4*d
|
||||||
|
|
||||||
|
// x1 = (-t + sqrt(delta)) / -2
|
||||||
|
// x2 = (-t - sqrt(delta)) / -2
|
||||||
|
x1 := (-float64(t) + math.Sqrt(float64(delta))) / -2.0
|
||||||
|
x2 := (-float64(t) - math.Sqrt(float64(delta))) / -2.0
|
||||||
|
x1_int := math.Ceil(x1)
|
||||||
|
x2_int := math.Floor(x2)
|
||||||
|
if x1_int == x1 {
|
||||||
|
x1_int++
|
||||||
|
}
|
||||||
|
if x2_int == x2 {
|
||||||
|
x2_int--
|
||||||
|
}
|
||||||
|
count := int64(x2_int) - int64(x1_int) + 1
|
||||||
|
result *= count
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
package day6
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRaceWinsCount(t *testing.T) {
|
||||||
|
lines := []string{
|
||||||
|
"Time: 7 15 30",
|
||||||
|
"Distance: 9 40 200",
|
||||||
|
}
|
||||||
|
|
||||||
|
result := RaceWinsCount(lines)
|
||||||
|
|
||||||
|
if result != 288 {
|
||||||
|
t.Fatalf("expected 288, got %v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRaceWinsCountWithInput(t *testing.T) {
|
||||||
|
lines := []string{
|
||||||
|
"Time: 54 81 70 88",
|
||||||
|
"Distance: 446 1292 1035 1007",
|
||||||
|
}
|
||||||
|
result := RaceWinsCount(lines)
|
||||||
|
|
||||||
|
if result != 2065338 {
|
||||||
|
t.Fatalf("expected 2065338, got %v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRaceWinsCount2(t *testing.T) {
|
||||||
|
lines := []string{
|
||||||
|
"Time: 71530",
|
||||||
|
"Distance: 940200",
|
||||||
|
}
|
||||||
|
|
||||||
|
result := RaceWinsCount(lines)
|
||||||
|
|
||||||
|
if result != 71503 {
|
||||||
|
t.Fatalf("expected 71503, got %v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRaceWinsCountWithInput2(t *testing.T) {
|
||||||
|
lines := []string{
|
||||||
|
"Time: 54817088",
|
||||||
|
"Distance: 446129210351007",
|
||||||
|
}
|
||||||
|
|
||||||
|
result := RaceWinsCount(lines)
|
||||||
|
|
||||||
|
if result != 34934171 {
|
||||||
|
t.Fatalf("expected 34934171, got %v", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue