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"
|
|
|
|
)
|
|
|
|
|
2024-12-03 15:43:58 +00:00
|
|
|
var reMul = regexp.MustCompile(`mul\(([0-9]{1,3}),([0-9]{1,3})\)`)
|
2024-12-03 14:42:28 +00:00
|
|
|
|
2024-12-06 19:57:07 +00:00
|
|
|
func Solve(buf []byte) (int, error) {
|
|
|
|
r := bytes.NewReader(buf)
|
2024-12-03 14:42:28 +00:00
|
|
|
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() {
|
2024-12-03 15:43:58 +00:00
|
|
|
matches := reMul.FindAllStringSubmatch(scanner.Text(), -1)
|
|
|
|
for _, m := range matches {
|
|
|
|
sum += util.MustConv(m[1]) * util.MustConv(m[2])
|
2024-12-03 14:42:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return sum, nil
|
|
|
|
}
|