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

56 lines
898 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
"github.com/onyx-and-iris/aoc2024/day-01/internal/util"
)
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 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
left[util.MustConv(nums[0])]++
2024-12-01 17:50:02 +00:00
right = util.InsertSorted(right, util.MustConv(nums[1]))
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
return left, right, nil
}