/
b.go
52 lines (40 loc) · 855 Bytes
/
b.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
package day07
import (
"math"
"strconv"
"strings"
)
type PuzzleB struct{}
func (p PuzzleB) String() string {
return "07b"
}
func (p PuzzleB) Run() int {
nums := strings.Split(input, ",")
hpos := make([]int, len(nums))
for i, n := range nums {
hpos[i], _ = strconv.Atoi(n)
}
// Calculate the mean distance
sum, mean := 0, 0
for _, hp := range hpos {
sum += hp
}
// Due to rounding around the mean, sample both bounds and return the smallest total
mean = sum / len(hpos)
dists := [2]int{}
calculateDist := func(m int) int {
t := 0
for _, hp := range hpos {
dist := int(math.Abs(float64(hp - m)))
// Include incremental fuel increase
t += dist * (dist + 1) / 2
}
return t
}
dists[0] = calculateDist(mean)
dists[1] = calculateDist(mean + 1)
if dists[0] < dists[1] {
return dists[0]
}
return dists[1]
}