-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (52 loc) · 977 Bytes
/
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
package main
import (
"bufio"
"fmt"
"os"
"slices"
)
func main() {
var input []string
for s := bufio.NewScanner(os.Stdin); s.Scan(); {
input = append(input, s.Text())
}
fmt.Printf("Part 1: %d\n", part1(input))
fmt.Printf("Part 2: %d\n", part2(input))
}
func part1(input []string) int {
list1, list2 := parse(input)
slices.Sort(list1)
slices.Sort(list2)
var sum int
for n := range list1 {
sum += abs(list1[n] - list2[n])
}
return sum
}
func part2(input []string) int {
list1, list2 := parse(input)
freq := make(map[int]int)
for n := range list2 {
freq[list2[n]]++
}
var sum int
for n := range list1 {
sum += list1[n] * freq[list1[n]]
}
return sum
}
func parse(input []string) (list1, list2 []int) {
for _, line := range input {
var n1, n2 int
fmt.Sscanf(line, "%d %d", &n1, &n2)
list1 = append(list1, n1)
list2 = append(list2, n2)
}
return list1, list2
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}