]> fbox.kageds.com Git - adventofcode.git/blob - 2023/go/day06/day06.go
day07
[adventofcode.git] / 2023 / go / day06 / day06.go
1 package day06
2
3 import (
4 "fmt"
5 "math"
6 )
7
8 type Input struct {
9 Time uint64
10 Distance uint64
11 }
12 func Part1(input string) int {
13 answer := 1.0
14 ins := parseInput1(input)
15 for _, in := range ins {
16 t1, t2, _ := solveQuadratic(1, float64(in.Time) * -1, float64(in.Distance))
17 fmt.Printf("t1: %v t2: %v ans: %v\n", t1, t2, (t1 - t2 + 1))
18 answer *= (t1 - t2 + 1)
19
20 }
21 return int(answer)
22 }
23
24 func Part2(input string) int {
25 answer := 1.0
26 ins := parseInput2(input)
27 for _, in := range ins {
28 t1, t2, _ := solveQuadratic(1, float64(in.Time) * -1, float64(in.Distance))
29 fmt.Printf("t1: %v t2: %v ans: %v\n", t1, t2, (t1 - t2 + 1))
30 answer *= (t1 - t2 + 1)
31
32 }
33 return int(answer)}
34
35 func parseInput1(input string) []Input {
36 var in []Input
37 in = append(in, Input{46, 214})
38 in = append(in, Input{80, 1177})
39 in = append(in, Input{78, 1402})
40 in = append(in, Input{66, 1024})
41 return in
42 }
43
44 func parseInput2(input string) []Input {
45 var in []Input
46 in = append(in, Input{46807866, 214117714021024})
47 return in
48 }
49
50 func solveQuadratic(a, b, c float64) (float64, float64, error) {
51 // Calculate the discriminant
52 discriminant := b*b - 4*a*c
53
54 // Check if the discriminant is non-negative
55 if discriminant < 0 {
56 return 0, 0, fmt.Errorf("no real roots, discriminant is negative")
57 }
58
59 // Calculate the roots
60 root1 := (-b + math.Sqrt(discriminant)) / (2 * a)
61 root2 := (-b - math.Sqrt(discriminant)) / (2 * a)
62
63 if isWholeNumber(root1) { root1 = root1 - 1.0 }
64 if isWholeNumber(root2) { root2 = root2 + 1.0 }
65 return math.Floor(root1), math.Ceil(root2), nil
66 }
67
68 func isWholeNumber(x float64) bool {
69 rounded := math.Round(x)
70 return x == rounded
71 }