mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2025-01-10 06:40:47 +00:00
65 lines
1.1 KiB
Go
65 lines
1.1 KiB
Go
package two
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"embed"
|
|
"io"
|
|
"regexp"
|
|
"slices"
|
|
|
|
"github.com/onyx-and-iris/aoc2024/day-01/internal/util"
|
|
)
|
|
|
|
//go:embed testdata
|
|
var files embed.FS
|
|
|
|
var reNums = regexp.MustCompile(`[0-9]+`)
|
|
|
|
func Solve() (int, error) {
|
|
data, _ := files.ReadFile("testdata/input.txt")
|
|
|
|
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
|
|
}
|
|
|
|
var occurrences int
|
|
for _, n := range right[indx:] {
|
|
if n > k {
|
|
break
|
|
}
|
|
occurrences++
|
|
}
|
|
similarity += k * v * occurrences
|
|
}
|
|
|
|
return similarity, nil
|
|
}
|
|
|
|
func parseLines(r io.Reader) (map[int]int, []int, error) {
|
|
var left map[int]int = make(map[int]int)
|
|
var right []int
|
|
|
|
scanner := bufio.NewScanner(r)
|
|
for scanner.Scan() {
|
|
nums := reNums.FindAllString(scanner.Text(), -1)
|
|
left[util.MustConv(nums[0])] = left[util.MustConv(nums[0])] + 1
|
|
right = util.InsertSorted(right, util.MustConv(nums[1]))
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
return left, right, nil
|
|
}
|