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

58 lines
1010 B
Go
Raw Normal View History

2024-12-03 14:42:28 +00:00
package two
import (
"bufio"
"bytes"
"io"
"regexp"
"github.com/onyx-and-iris/aoc2024/day-03/internal/util"
log "github.com/sirupsen/logrus"
)
2024-12-03 15:43:58 +00:00
var reMulOrDoOrDont = regexp.MustCompile(`mul\(([0-9]{1,3}),([0-9]{1,3})\)|do\(\)|don't\(\)`)
2024-12-03 14:42:28 +00:00
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
var do bool = true
scanner := bufio.NewScanner(r)
for scanner.Scan() {
2024-12-03 15:43:58 +00:00
matches := reMulOrDoOrDont.FindAllStringSubmatch(scanner.Text(), -1)
for _, m := range matches {
switch m[0] {
2024-12-03 14:42:28 +00:00
case "do()":
do = true
log.Debug("hit a do")
case "don't()":
do = false
log.Debug("hit a don't")
}
if do {
2024-12-03 15:43:58 +00:00
if m[1] != "" && m[2] != "" {
log.Debugf("%s * %s\n", m[1], m[2])
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
}