-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1.go
83 lines (66 loc) · 1.37 KB
/
day1.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
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"bufio"
"os"
"regexp"
"sort"
"strconv"
)
// insert a number into a list in order
func insert(list []int, num int) []int {
if len(list) == 0 {
return []int{num}
}
for i := 0; i < len(list); i++ {
if num < list[i] {
list = append(list, 0)
copy(list[i+1:], list[i:])
list[i] = num
return list
}
}
return append(list, num)
}
// count the number of times a number appears in a sorted list
func count(list []int, num int) int {
count := 0
first := sort.SearchInts(list, num)
for i := first; i < len(list) && list[i] == num; i++ {
count++
}
return count
}
func day1() {
filepath := "input/day1.txt"
if len(os.Args) == 4 {
filepath = os.Args[3]
}
file, ferr := os.Open(filepath)
if ferr != nil {
panic(ferr)
}
list1 := []int{}
list2 := []int{}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
nums := regexp.MustCompile(`\s+`).Split(line, -1)
num1, _ := strconv.Atoi(nums[0])
num2, _ := strconv.Atoi(nums[1])
list1 = insert(list1, num1)
list2 = insert(list2, num2)
}
diffCount := 0
simCount := 0
for i := 0; i < len(list1); i++ {
diff := list1[i] - list2[i]
if diff < 0 {
diffCount -= diff
} else {
diffCount += diff
}
simCount += list1[i] * count(list2, list1[i])
}
println("The total distance is: ", diffCount)
println("The total similarity is: ", simCount)
}