1
0
Fork 0
adventofcode/2024/01/main.go

57 lines
842 B
Go
Raw Permalink Normal View History

2024-12-01 18:43:58 +00:00
package main
import (
"fmt"
"sort"
"aoc/helper"
2024-12-01 18:43:58 +00:00
)
type list struct {
2024-12-03 19:23:59 +00:00
left []int
right []int
}
2024-12-01 18:43:58 +00:00
func main() {
list_a, list_b := helper.ReadLinesTwoIntSlices()
2024-12-03 19:23:59 +00:00
list := list{left: list_a, right: list_b}
2024-12-01 18:43:58 +00:00
// part 1
distance := list.distance()
2024-12-01 18:43:58 +00:00
fmt.Printf("Distance: %v\n", distance)
// part 2
similarity := list.similarity()
2024-12-01 18:43:58 +00:00
fmt.Printf("Similarity: %v\n", similarity)
}
func (l list) distance() (dist int) {
2024-12-03 19:23:59 +00:00
sort.Ints(l.left)
sort.Ints(l.right)
2024-12-01 18:43:58 +00:00
2024-12-03 19:23:59 +00:00
for i := range l.left {
dist += helper.Abs(l.left[i] - l.right[i])
2024-12-01 18:43:58 +00:00
}
2024-12-03 19:23:59 +00:00
2024-12-01 18:43:58 +00:00
return dist
}
func (l list) similarity() (sim int) {
2024-12-03 19:23:59 +00:00
for _, lval := range l.left {
valcount := countIntInSlice(l.right, lval)
sim += lval * valcount
2024-12-01 18:43:58 +00:00
}
2024-12-03 19:23:59 +00:00
2024-12-01 18:43:58 +00:00
return sim
}
func countIntInSlice(lst []int, i int) (count int) {
2024-12-01 18:43:58 +00:00
for _, val := range lst {
if val == i {
count++
}
}
2024-12-03 19:23:59 +00:00
2024-12-01 18:43:58 +00:00
return count
}