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
86
87
88
89
|
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
func IntAbs(a int) int {
if a >= 0 {
return a
}
return -a
}
func main() {
part2(readData("data.txt"))
}
func readData(fileName string) (list1, list2 []int) {
fp, err := os.Open(fileName)
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(fp)
list1 = make([]int, 0)
list2 = make([]int, 0)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
split := strings.Split(line, " ")
if len(split) != 2 {
continue
}
value1, err := strconv.Atoi(split[0])
if err != nil {
continue
}
value2, err := strconv.Atoi(split[1])
if err != nil {
continue
}
list1 = append(list1, value1)
list2 = append(list2, value2)
}
return
}
func part1(list1, list2 []int) {
sort.Sort(sort.IntSlice(list1))
sort.Sort(sort.IntSlice(list2))
dist := 0
for i := range list1 {
dist += IntAbs(list1[i] - list2[i])
}
fmt.Println(dist)
}
func countInstances(list []int) (counts map[int]int) {
counts = make(map[int]int)
for _, n := range list {
counts[n] += 1
}
return
}
func part2(list1, list2 []int) {
counts1 := countInstances(list1)
counts2 := countInstances(list2)
total := 0
for n, c1 := range counts1 {
c2, _ := counts2[n]
total += n * c1 * c2
}
fmt.Println(total)
}
|