aboutsummaryrefslogtreecommitdiff
path: root/2021/07/second.go
blob: 5133f6607f3a7a8a2a4ceff9e2f50c7edd1ecffe (plain)
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
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func min(a, b int) int {
	if a < b {
		return a
	} else {
		return b
	}
}
func abs(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func splitOnCommas(data []byte, atEOF bool) (advance int, token []byte, err error) {
	var ch byte
	for advance, ch = range data {
		if ch < '0' || ch > '9' {
			break
		}
	}
	if advance > 0 {
		token = data[0:advance]
		advance++ // skip the comma
	}
	return
}

func main() {
	positions := make([]int, 0)

	s := bufio.NewScanner(os.Stdin)
	s.Split(splitOnCommas)
	for s.Scan() {
		n, _ := strconv.Atoi(s.Text())
		positions = append(positions, n)
	}

	sum := 0
	for _, i := range positions {
		sum += i
	}
	mean := sum / len(positions)

	// doing a mean with integers sucks
	total := 0
	total2 := 0
	for _, i := range positions {
		diff := abs(i - mean)
		total += diff * (diff + 1) / 2
		diff = abs(i - mean - 1)
		total2 += diff * (diff + 1) / 2
	}
	fmt.Println(min(total, total2))
}