day06
This commit is contained in:
71
2023/go/day06/day06.go
Normal file
71
2023/go/day06/day06.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package day06
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
type Input struct {
|
||||
Time uint64
|
||||
Distance uint64
|
||||
}
|
||||
func Part1(input string) int {
|
||||
answer := 1.0
|
||||
ins := parseInput1(input)
|
||||
for _, in := range ins {
|
||||
t1, t2, _ := solveQuadratic(1, float64(in.Time) * -1, float64(in.Distance))
|
||||
fmt.Printf("t1: %v t2: %v ans: %v\n", t1, t2, (t1 - t2 + 1))
|
||||
answer *= (t1 - t2 + 1)
|
||||
|
||||
}
|
||||
return int(answer)
|
||||
}
|
||||
|
||||
func Part2(input string) int {
|
||||
answer := 1.0
|
||||
ins := parseInput2(input)
|
||||
for _, in := range ins {
|
||||
t1, t2, _ := solveQuadratic(1, float64(in.Time) * -1, float64(in.Distance))
|
||||
fmt.Printf("t1: %v t2: %v ans: %v\n", t1, t2, (t1 - t2 + 1))
|
||||
answer *= (t1 - t2 + 1)
|
||||
|
||||
}
|
||||
return int(answer)}
|
||||
|
||||
func parseInput1(input string) []Input {
|
||||
var in []Input
|
||||
in = append(in, Input{46, 214})
|
||||
in = append(in, Input{80, 1177})
|
||||
in = append(in, Input{78, 1402})
|
||||
in = append(in, Input{66, 1024})
|
||||
return in
|
||||
}
|
||||
|
||||
func parseInput2(input string) []Input {
|
||||
var in []Input
|
||||
in = append(in, Input{46807866, 214117714021024})
|
||||
return in
|
||||
}
|
||||
|
||||
func solveQuadratic(a, b, c float64) (float64, float64, error) {
|
||||
// Calculate the discriminant
|
||||
discriminant := b*b - 4*a*c
|
||||
|
||||
// Check if the discriminant is non-negative
|
||||
if discriminant < 0 {
|
||||
return 0, 0, fmt.Errorf("no real roots, discriminant is negative")
|
||||
}
|
||||
|
||||
// Calculate the roots
|
||||
root1 := (-b + math.Sqrt(discriminant)) / (2 * a)
|
||||
root2 := (-b - math.Sqrt(discriminant)) / (2 * a)
|
||||
|
||||
if isWholeNumber(root1) { root1 = root1 - 1.0 }
|
||||
if isWholeNumber(root2) { root2 = root2 + 1.0 }
|
||||
return math.Floor(root1), math.Ceil(root2), nil
|
||||
}
|
||||
|
||||
func isWholeNumber(x float64) bool {
|
||||
rounded := math.Round(x)
|
||||
return x == rounded
|
||||
}
|
||||
17
2023/go/day06/day06_test.go
Normal file
17
2023/go/day06/day06_test.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package day06
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPart1(t *testing.T) {
|
||||
r := Part1("")
|
||||
require.Equal(t, 512295, r)
|
||||
}
|
||||
|
||||
func TestPart2(t *testing.T) {
|
||||
r := Part2("")
|
||||
require.Equal(t, 36530883, r)
|
||||
}
|
||||
2
2023/go/day06/input.txt
Normal file
2
2023/go/day06/input.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
Time: 46 80 78 66
|
||||
Distance: 214 1177 1402 1024
|
||||
Reference in New Issue
Block a user