aoc2024/day-03/internal/one/solve.go

42 lines
737 B
Go
Raw Normal View History

2024-12-03 14:42:28 +00:00
package one
import (
"bufio"
"bytes"
"io"
"regexp"
"github.com/onyx-and-iris/aoc2024/day-03/internal/util"
)
var reMul = regexp.MustCompile(`mul\((?P<first>[0-9]{1,3}),(?P<second>[0-9]{1,3})\)`)
func Solve(data []byte) (int, error) {
r := bytes.NewReader(data)
sum, err := parseLines(r)
if err != nil {
return 0, err
}
return sum, nil
}
func parseLines(r io.Reader) (int, error) {
var sum int
scanner := bufio.NewScanner(r)
for scanner.Scan() {
m := reMul.FindAllString(scanner.Text(), -1)
for _, v := range m {
groups := util.GetGroups(reMul, v)
sum += util.MustConv(groups["first"]) * util.MustConv(groups["second"])
}
}
if err := scanner.Err(); err != nil {
return 0, err
}
return sum, nil
}