summaryrefslogtreecommitdiff
path: root/2023/go/internal/day_06/part_01/part_01.go
blob: 57359248658fe65be1765ee45e867060eff451d6 (plain)
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
85
package part_01

import (
	"os"
	"strconv"
	"strings"
)

const USE_SAMPLE = false

/**
 * Tried:
 * - 72128 (too low)
 * - 3317888 (correct!)
 */
func Solve() {
	var filePath string
	if USE_SAMPLE {
		filePath = "../_input/day_06_part_01_sample.txt"
	} else {
		filePath = "../_input/day_06.txt"
	}
	contents, _ := os.ReadFile(filePath)

	lines := strings.Split(string(contents), "\r\n")

	timeLine := lines[0]
	times := parseTimeLine(timeLine)

	distLine := lines[1]
	distances := parseDistanceLine(distLine)

	answer := calculateAnswer(times, distances)

	println(answer)
}

func parseTimeLine(timeLine string) []int {
	prefix := "Time:"
	return parseLine(prefix, timeLine)
}

func parseDistanceLine(distLine string) []int {
	prefix := "Distance:"
	return parseLine(prefix, distLine)
}

func parseLine(prefix string, line string) []int {
	withoutTitle := strings.TrimPrefix(line, prefix)

	numbers := []int{}
	for _, number := range strings.Split(withoutTitle, " ") {
		if number == "" {
			continue
		}
		numberInt, _ := strconv.Atoi(number)
		numbers = append(numbers, numberInt)
	}
	return numbers
}

func calculateAnswer(times []int, distances []int) int {
	answer := 1
	for i, maxTime := range times {
		recordDistance := distances[i]

		var greaterThanRecord []int
		for buttonPressedFor := 0; buttonPressedFor <= maxTime; buttonPressedFor++ {
			distance := calculateDistance(buttonPressedFor, maxTime)
			if distance > recordDistance {
				greaterThanRecord = append(greaterThanRecord, distance)
			}
		}

		if len(greaterThanRecord) > 0 {
			answer *= len(greaterThanRecord)
		}
	}

	return answer
}

func calculateDistance(buttonPressedFor int, maxTime int) int {
	return buttonPressedFor * (maxTime - buttonPressedFor)
}