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

56 lines
940 B
Go

package two
import (
"bufio"
"bytes"
"io"
"regexp"
log "github.com/sirupsen/logrus"
)
var reMulOrDoOrDont = regexp.MustCompile(`mul\(([0-9]{1,3}),([0-9]{1,3})\)|do\(\)|don't\(\)`)
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
var do bool = true
scanner := bufio.NewScanner(r)
for scanner.Scan() {
matches := reMulOrDoOrDont.FindAllStringSubmatch(scanner.Text(), -1)
for _, m := range matches {
switch m[0] {
case "do()":
do = true
log.Debug("hit a do")
case "don't()":
do = false
log.Debug("hit a don't")
}
if do {
if m[1] != "" && m[2] != "" {
log.Debugf("%s * %s\n", m[1], m[2])
sum += mustConv(m[1]) * mustConv(m[2])
}
}
}
}
if err := scanner.Err(); err != nil {
return 0, err
}
return sum, nil
}