-
Notifications
You must be signed in to change notification settings - Fork 1
/
aoc7.go
69 lines (59 loc) · 1.23 KB
/
aoc7.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
// aoc7.go --
// advent of code 2021 day 7
//
// https://adventofcode.com/2021/day/7
// https://github.com/erik-adelbert/aoc
//
// (ɔ) Erik Adelbert - erik_AT_adelbert_DOT_fr
// -------------------------------------------
// 2021-12-7: initial commit
package main
import (
"bufio"
"fmt"
"math"
"os"
"sort"
"strconv"
"strings"
)
type pos []int
func (p pos) mean() int {
sum := 0
for _, x := range p {
sum += x
}
return int(math.Floor(float64(sum) / float64(len(p)))) // Round doesn't work on my input
}
func (p pos) median() int {
sort.Ints(p)
return p[len(p)/2]
}
// sumdist does parallel summation of distances for part1 & part2.
func (p pos) sumdist() (int, int) {
m1, m2 := p.median(), p.mean()
g := func(x int) int { return (x * (x + 1)) / 2 } // gauss sum
sum1, sum2 := 0, 0
for _, x := range p {
sum1 += abs(x - m1) // dist1
sum2 += g(abs(x - m2)) // dist2
}
return sum1, sum2
}
func main() {
crabs := make(pos, 0, 1000)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
for _, arg := range strings.Split(input.Text(), ",") {
x, _ := strconv.Atoi(arg)
crabs = append(crabs, x)
}
}
fmt.Println(crabs.sumdist()) // part1 & part2
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}