diff --git a/day6/day6.go b/day6/day6.go new file mode 100644 index 0000000..ea6a622 --- /dev/null +++ b/day6/day6.go @@ -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 +} diff --git a/day6/day6_test.go b/day6/day6_test.go new file mode 100644 index 0000000..8ed6177 --- /dev/null +++ b/day6/day6_test.go @@ -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) + } +} diff --git a/utils/utils.go b/utils/utils.go index 0d4ce34..950b9d1 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -73,3 +73,13 @@ func IntPow(x int, y int) int { return result } + +func Int64Pow(x int64, y int64) int64 { + result := int64(1) + + for i := int64(0); i < y; i++ { + result *= x + } + + return result +}