aoc2024/01/main.go

94 lines
1.7 KiB
Go
Raw Normal View History

2024-12-01 19:32:12 +00:00
package main
import (
"fmt"
"os"
"sort"
"strconv"
"strings"
)
// Given a list of paired integers with columns representing two groups,
// compute the total distance between pairs in the sorted lists.
func main() {
// open input file
input, err := os.ReadFile("input")
if err != nil {
fmt.Println(err)
}
// Walk the list and create two lists, left and right
left, right := extractLists(string(input))
// Sort left and right
sort.Slice(left, func(i, j int) bool {
return left[i] < left[j]
})
sort.Slice(right, func(i, j int) bool {
return right[i] < right[j]
})
// lFreqMap := frequencyMap(left)
rFreqMap := frequencyMap(right)
// Walk through left and compare each element to its pair in right
differenceTotal := 0
scoreTotal := 0
for idx, val := range left {
var l, r int
l = val
r = right[idx]
// Sum distance between elements
difference := l - r
score := l * rFreqMap[l]
// Take absolute value
if difference < 0 {
difference = -difference
}
differenceTotal += difference
scoreTotal += score
}
// Return total distance
fmt.Println(differenceTotal)
fmt.Println(scoreTotal)
}
func frequencyMap(slice []int) map[int]int {
frequency := make(map[int]int) // val -> score
for _, val := range slice {
frequency[val] = frequency[val] + 1
}
return frequency
}
func extractLists(input string) ([]int, []int) {
var left, right []int
for _, val := range strings.Split(input, "\n") {
// fmt.Println(idx)
t := strings.Fields(val)
if len(t) < 2 {
continue
}
l, err := strconv.Atoi(t[0])
if err != nil {
panic("aaa")
}
left = append(left, l)
r, err := strconv.Atoi(t[1])
if err != nil {
panic("bbb")
}
right = append(right, r)
}
return left, right
}