aoc24/day1/main.go

61 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-12-02 13:42:47 +00:00
package main
import (
"fmt"
"slices"
"strconv"
"strings"
"git.mstar.dev/mstar/aoc24/util"
"git.mstar.dev/mstar/goutils/sliceutils"
)
func LineExtract(line string) (int, int) {
tmp := sliceutils.Filter(strings.Split(line, " "), func(s string) bool {
return len(s) > 0
})
if len(tmp) != 2 {
return 1, 1
}
left, err := strconv.Atoi(tmp[0])
if err != nil {
panic(err)
}
right, err := strconv.Atoi(tmp[1])
if err != nil {
panic(err)
}
return left, right
}
func main() {
data := util.LoadFileFromArgs()
lines := sliceutils.Filter(
strings.Split(string(data), "\n"),
func(t string) bool { return len(t) > 0 },
)
numbersLeft := []int{}
numberRight := []int{}
for _, line := range lines {
l, r := LineExtract(line)
numbersLeft = append(numbersLeft, l)
numberRight = append(numberRight, r)
}
slices.Sort(numberRight)
slices.Sort(numbersLeft)
diffs := make([]int, len(lines))
for i := range len(lines) {
diffs = append(diffs, util.AbsI(numbersLeft[i]-numberRight[i]))
}
total := sliceutils.Compact(diffs, func(acc, next int) int { return acc + next })
fmt.Printf("Task 1: %d\n", total)
acc := 0
for _, v := range numbersLeft {
acc += len(sliceutils.Filter(numberRight, func(t int) bool { return t == v })) * v
}
fmt.Printf("Task 2: %d\n", acc)
}