2024-12-01 17:50:02 +00:00
|
|
|
package two
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
"io"
|
|
|
|
"slices"
|
2024-12-02 18:28:28 +00:00
|
|
|
"strings"
|
2024-12-01 17:50:02 +00:00
|
|
|
|
|
|
|
"github.com/onyx-and-iris/aoc2024/day-01/internal/util"
|
|
|
|
)
|
|
|
|
|
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:] {
|
2024-12-01 18:03:05 +00:00
|
|
|
if n > k {
|
2024-12-01 21:14:02 +00:00
|
|
|
similarity += k * v * i
|
2024-12-01 18:03:05 +00:00
|
|
|
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() {
|
2024-12-02 18:28:28 +00:00
|
|
|
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
|
|
|
|
}
|