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

54 lines
823 B
Go

package two
import (
"bufio"
"bytes"
"io"
"slices"
"strings"
)
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
left, right, err := parseLines(r)
if err != nil {
return 0, err
}
var similarity int
for k, v := range left {
indx := slices.Index(right, k)
if indx == -1 {
continue
}
for i, n := range right[indx:] {
if n > k {
similarity += k * v * i
break
}
}
}
return similarity, nil
}
func parseLines(r io.Reader) (map[int]int, []int, error) {
left := make(map[int]int)
right := []int{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
nums := strings.Fields(scanner.Text())
left[mustConv(nums[0])]++
right = insertSorted(right, mustConv(nums[1]))
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
return left, right, nil
}