-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
70 lines (58 loc) · 1.22 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
package main
import (
"io"
"sort"
aoc "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader) int {
s := aoc.ReaderToString(input)
positions := aoc.NewDelimiter(s, ",").GetInts()
sort.Ints(positions)
median := 0
if len(positions)%2 == 0 {
median = positions[len(positions)/2-1]
} else {
median = positions[len(positions)/2]
}
return positionFromMedian(positions, median)
}
func positionFromMedian(positions []int, median int) int {
sum := 0
for _, position := range positions {
sum += aoc.Abs(median - position)
}
return sum
}
func fs2(input io.Reader) int {
s := aoc.ReaderToString(input)
positions := aoc.NewDelimiter(s, ",").GetInts()
minMax := aoc.NewMinerMaxer()
for _, position := range positions {
minMax.Add(position)
}
m := aoc.NewMiner()
for i := minMax.GetMin(); i <= minMax.GetMax(); i++ {
v := totalDistance(positions, i)
m.Add(v)
}
return m.Get()
}
func totalDistance(positions []int, target int) int {
sum := 0
for _, position := range positions {
sum += distance(aoc.Abs(position - target))
}
return sum
}
var dp = map[int]int{}
func distance(d int) int {
if d == 0 {
return 0
}
if v, exists := dp[d]; exists {
return v
}
v := d + distance(d-1)
dp[d] = v
return v
}