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

54 lines
823 B
Go
Raw Normal View History

2024-12-01 17:50:02 +00:00
package two
import (
"bufio"
"bytes"
"io"
"slices"
"strings"
2024-12-01 17:50:02 +00:00
)
2024-12-06 19:57:07 +00:00
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
2024-12-01 17:50:02 +00:00
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
}
2024-12-01 21:14:02 +00:00
for i, n := range right[indx:] {
if n > k {
2024-12-01 21:14:02 +00:00
similarity += k * v * i
break
2024-12-01 17:50:02 +00:00
}
}
}
return similarity, nil
}
func parseLines(r io.Reader) (map[int]int, []int, error) {
2024-12-01 21:14:02 +00:00
left := make(map[int]int)
right := []int{}
2024-12-01 17:50:02 +00:00
scanner := bufio.NewScanner(r)
for scanner.Scan() {
nums := strings.Fields(scanner.Text())
2024-12-01 21:14:02 +00:00
2025-01-07 17:18:38 +00:00
left[mustConv(nums[0])]++
right = insertSorted(right, mustConv(nums[1]))
2024-12-01 17:50:02 +00:00
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
return left, right, nil
}