-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
99 lines (79 loc) · 1.93 KB
/
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"bufio"
"fmt"
"os"
"slices"
"strconv"
"strings"
)
// https://adventofcode.com/2024/day/1
func main() {
firstPart()
secondPart()
}
// firstPart reads pairs of integers from a file, sorts them, and computes the
// sum of the absolute differences between corresponding elements from two lists.
func firstPart() {
inputFile, err := os.Open("../input")
if err != nil {
fmt.Printf("Unable to read puzzle file: %s\n", err)
return
}
scanner := bufio.NewScanner(inputFile)
scanner.Split(bufio.ScanLines)
first := []int{}
second := []int{}
for scanner.Scan() {
line := scanner.Text()
nums := strings.Split(line, " ")
// skip errors, inputs must be correct
x, _ := strconv.Atoi(nums[0])
y, _ := strconv.Atoi(nums[1])
first = append(first, x)
second = append(second, y)
}
inputFile.Close()
slices.Sort(first)
slices.Sort(second)
var sum int = 0
for i := 0; i < len(first); i++ {
distance := first[i] - second[i]
if distance < 0 {
sum += distance * -1
} else {
sum += distance
}
}
fmt.Printf("Result of fist part: %d\n", sum)
}
// secondPart reads pairs of integers from a file, and computes the sum of the
// occurances of each number in the first column multiplied by the number itself.
func secondPart() {
inputFile, err := os.Open("../input")
if err != nil {
fmt.Printf("Unable to read puzzle file: %s", err)
return
}
scanner := bufio.NewScanner(inputFile)
scanner.Split(bufio.ScanLines)
first := []int{}
occurances := map[int]int{}
for scanner.Scan() {
line := scanner.Text()
nums := strings.Split(line, " ")
// skip errors, inputs must be correct
x, _ := strconv.Atoi(nums[0])
y, _ := strconv.Atoi(nums[1])
first = append(first, x)
occurances[y] = occurances[y] + 1
}
inputFile.Close()
var sum int = 0
for i := 0; i < len(first); i++ {
x := first[i]
count := occurances[x]
sum += x * count
}
fmt.Printf("Result of second part: %d\n", sum)
}