-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
85 lines (67 loc) · 1.38 KB
/
main.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
85
package main
import (
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"github.com/devries/advent_of_code_2021/utils"
)
func main() {
f, err := os.Open("../inputs/day07.txt")
utils.Check(err, "error opening input.txt")
defer f.Close()
r := solve(f)
fmt.Println(r)
}
func solve(r io.Reader) int {
lines := utils.ReadLines(r)
parts := strings.Split(lines[0], ",")
values := make([]int, 0)
for _, p := range parts {
v, err := strconv.Atoi(p)
utils.Check(err, "unable to convert string to integer")
values = append(values, v)
}
sort.Ints(values)
// Search the parameter space
interval := values[len(values)-1] - values[0]
cpos := values[0] + interval/2
interval = interval / 4
fuels := make(map[int]int)
for {
h := cpos + interval
l := cpos - interval
cfuel := fuelCalc(values, cpos, fuels)
hfuel := fuelCalc(values, h, fuels)
lfuel := fuelCalc(values, l, fuels)
if interval == 1 && cfuel <= hfuel && cfuel <= lfuel {
// Success
return cfuel
}
if lfuel <= cfuel && lfuel <= hfuel {
cpos = l
} else if hfuel <= cfuel && hfuel <= lfuel {
cpos = h
}
if interval > 1 {
interval = interval / 2
}
}
}
func fuelCalc(values []int, pos int, fuels map[int]int) int {
if f, ok := fuels[pos]; ok {
return f
}
f := 0
for _, v := range values {
d := v - pos
if d < 0 {
d = -d
}
f += ((d + 1) * d) / 2
}
fuels[pos] = f
return f
}