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

46 lines
811 B
Go
Raw Normal View History

2024-12-01 17:50:02 +00:00
package one
import (
"bufio"
"bytes"
"io"
"math"
"regexp"
"github.com/onyx-and-iris/aoc2024/day-01/internal/util"
)
var reNums = regexp.MustCompile(`[0-9]+`)
2024-12-02 00:23:59 +00:00
func Solve(data []byte) (int, error) {
2024-12-01 17:50:02 +00:00
r := bytes.NewReader(data)
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 := reNums.FindAllString(scanner.Text(), -1)
2024-12-01 22:04:49 +00:00
2024-12-01 17:50:02 +00:00
left = util.InsertSorted(left, util.MustConv(nums[0]))
right = util.InsertSorted(right, util.MustConv(nums[1]))
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
return left, right, nil
}