This commit is contained in:
Neil Hanlon 2024-12-01 14:32:12 -05:00
parent fafe7121c4
commit f0e842308b
Signed by: neil
GPG Key ID: 705BC21EC3C70F34
2 changed files with 1093 additions and 0 deletions

1000
01/input Normal file

File diff suppressed because it is too large Load Diff

93
01/main.go Normal file
View File

@ -0,0 +1,93 @@
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
}