Skip to content

Commit d31aa6c

Browse files
committed
day 1
0 parents  commit d31aa6c

File tree

4 files changed

+81
-0
lines changed

4 files changed

+81
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
day?-inputs.txt

day1-example.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
3 4
2+
4 3
3+
2 5
4+
1 3
5+
3 9
6+
3 3

day1.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"fmt"
6+
"os"
7+
"regexp"
8+
"sort"
9+
"strconv"
10+
)
11+
12+
func convertAndAppend(list []int, strVal string) []int {
13+
intVal, err := strconv.Atoi(strVal)
14+
if err != nil {
15+
fmt.Fprintf(os.Stderr, "Couldn't convert %s to int: %s\n", strVal, err)
16+
os.Exit(1)
17+
}
18+
return append(list, intVal)
19+
}
20+
21+
func abs(x int) int {
22+
if x < 0 {
23+
return -x
24+
}
25+
return x
26+
}
27+
28+
func count(list []int, val int) int {
29+
count := 0
30+
for _, elem := range list {
31+
if elem == val {
32+
count++
33+
}
34+
}
35+
return count
36+
}
37+
38+
func main() {
39+
scanner := bufio.NewScanner(os.Stdin)
40+
pattern := regexp.MustCompile(`^(\d+)\s+(\d+)$`)
41+
42+
var list1 []int
43+
var list2 []int
44+
for scanner.Scan() {
45+
line := scanner.Text()
46+
matches := pattern.FindStringSubmatch(line)
47+
if len(matches) > 0 {
48+
list1 = convertAndAppend(list1, matches[1])
49+
list2 = convertAndAppend(list2, matches[2])
50+
}
51+
}
52+
if err := scanner.Err(); err != nil {
53+
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
54+
os.Exit(1)
55+
}
56+
57+
sort.Ints(list1)
58+
sort.Ints(list2)
59+
distanceSum := 0
60+
for i := 0; i < len(list1); i++ {
61+
distanceSum += abs(list1[i] - list2[i])
62+
}
63+
64+
fmt.Printf("sum of distances is %d\n", distanceSum)
65+
66+
similarity := 0
67+
for i := 0; i < len(list1); i++ {
68+
similarity += list1[i] * count(list2, list1[i])
69+
}
70+
fmt.Printf("similarity score is %d\n", similarity)
71+
}

go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/fxnn/adventofcode2024
2+
3+
go 1.23.2

0 commit comments

Comments
 (0)