mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2025-01-10 06:40:47 +00:00
39 lines
607 B
Go
39 lines
607 B
Go
package one
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"io"
|
|
"regexp"
|
|
)
|
|
|
|
var reMul = regexp.MustCompile(`mul\(([0-9]{1,3}),([0-9]{1,3})\)`)
|
|
|
|
func Solve(buf []byte) (int, error) {
|
|
r := bytes.NewReader(buf)
|
|
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() {
|
|
matches := reMul.FindAllStringSubmatch(scanner.Text(), -1)
|
|
for _, m := range matches {
|
|
sum += mustConv(m[1]) * mustConv(m[2])
|
|
}
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return sum, nil
|
|
}
|