aoc2024/day-01/internal/one/solve.go

42 lines
679 B
Go

package one
import (
"bufio"
"bytes"
"io"
"math"
"strings"
)
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
left, right, err := parseLines(r)
if err != nil {
return 0, err
}
var sum int
for i, n := range left {
sum += int(math.Abs(float64(n - right[i])))
}
return sum, nil
}
func parseLines(r io.Reader) ([]int, []int, error) {
var left, right []int
scanner := bufio.NewScanner(r)
for scanner.Scan() {
nums := strings.Fields(scanner.Text())
left = insertSorted(left, mustConv(nums[0]))
right = insertSorted(right, mustConv(nums[1]))
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
return left, right, nil
}