-
Notifications
You must be signed in to change notification settings - Fork 0
/
day7.go
49 lines (42 loc) · 880 Bytes
/
day7.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
package main
import (
"math"
"sort"
"strings"
)
func calcCrabFuel(lines []string, gausFuel bool) int {
var crabs = extractCrabs(lines)
var fuel int = 0
if gausFuel {
var average = calcAverage(crabs)
for _, v := range crabs {
var steps = int(math.Abs(float64(average - v)))
fuel += (steps * (steps + 1) / 2)
}
} else {
var median = calcMedian(crabs)
for _, v := range crabs {
fuel += int(math.Abs(float64(median - v)))
}
}
return fuel
}
func calcMedian(crabs []int) int {
sort.Ints(crabs)
return crabs[len(crabs)/2]
}
func calcAverage(crabs []int) int {
var sum int = 0
for _, v := range crabs {
sum += v
}
return sum / len(crabs)
}
func extractCrabs(lines []string) []int {
crabStrings := strings.Split(lines[0], ",")
var crabs []int
for i := range crabStrings {
crabs = append(crabs, strToInt(crabStrings[i]))
}
return crabs
}