-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06p1.go
84 lines (67 loc) · 2.07 KB
/
06p1.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"math"
"strconv"
"aoc2023/utils"
)
type boatRace struct {
time int
distanceRecord int
}
func D06P1() {
lines := utils.ReadLines("inputs/06.txt")
boatRaces := parseBoatRaces(lines)
totalWins := 1
for _, boatRace := range boatRaces {
possibleWinningScenarios := findBoatRaceWins(boatRace)
totalWins *= possibleWinningScenarios
}
fmt.Printf("Product of possible winning scenarios: %d\n", totalWins)
}
func parseBoatRaces(lines []string) []boatRace {
boatRaces := []boatRace{}
timeDigitString := ""
currentBoatRace := boatRace{}
// Parse times
for _, timeDigit := range lines[0] {
if timeDigit >= '0' && timeDigit <= '9' {
timeDigitString += string(timeDigit)
} else if timeDigit == ' ' && timeDigitString != "" {
currentBoatRace.time, _ = strconv.Atoi(timeDigitString)
boatRaces = append(boatRaces, currentBoatRace)
timeDigitString = ""
currentBoatRace = boatRace{}
}
}
// Append the last time
currentBoatRace.time, _ = strconv.Atoi(timeDigitString)
boatRaces = append(boatRaces, currentBoatRace)
distanceDigitString := ""
boatRaceIndex := 0
// Parse distances
for _, distanceDigit := range lines[1] {
if distanceDigit >= '0' && distanceDigit <= '9' {
distanceDigitString += string(distanceDigit)
} else if distanceDigit == ' ' && distanceDigitString != "" {
boatRaces[boatRaceIndex].distanceRecord, _ = strconv.Atoi(distanceDigitString)
distanceDigitString = ""
if boatRaceIndex < len(boatRaces)-1 {
boatRaceIndex++
currentBoatRace = boatRaces[boatRaceIndex]
}
}
}
// Append the last distance
boatRaces[boatRaceIndex].distanceRecord, _ = strconv.Atoi(distanceDigitString)
return boatRaces
}
func findBoatRaceWins(boatRace boatRace) int {
t := boatRace.time
d := boatRace.distanceRecord
// Get the minimum and maximum hold times to improve upon d (distanceRecord)
t1 := (t - int(math.Sqrt(float64(t*t-4*d)))) / 2
t2 := (t + int(math.Sqrt(float64(t*t-4*d)))) / 2
// the difference between the two represents ALL the possible hold times that result in a win
return t2 - t1 + 1
}