mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2025-01-10 14:50:46 +00:00
59 lines
1.1 KiB
Go
59 lines
1.1 KiB
Go
|
package two
|
||
|
|
||
|
import (
|
||
|
"bufio"
|
||
|
"bytes"
|
||
|
"io"
|
||
|
"regexp"
|
||
|
|
||
|
"github.com/onyx-and-iris/aoc2024/day-03/internal/util"
|
||
|
|
||
|
log "github.com/sirupsen/logrus"
|
||
|
)
|
||
|
|
||
|
var reMulOrDoOrDont = regexp.MustCompile(`mul\((?P<first>[0-9]{1,3}),(?P<second>[0-9]{1,3})\)|do\(\)|don't\(\)`)
|
||
|
|
||
|
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() {
|
||
|
m := reMulOrDoOrDont.FindAllString(scanner.Text(), -1)
|
||
|
for _, v := range m {
|
||
|
switch v {
|
||
|
case "do()":
|
||
|
do = true
|
||
|
log.Debug("hit a do")
|
||
|
case "don't()":
|
||
|
do = false
|
||
|
log.Debug("hit a don't")
|
||
|
}
|
||
|
|
||
|
if do {
|
||
|
groups := util.GetGroups(reMulOrDoOrDont, v)
|
||
|
if groups["first"] != "" && groups["second"] != "" {
|
||
|
log.Debugf("%s * %s\n", groups["first"], groups["second"])
|
||
|
sum += util.MustConv(groups["first"]) * util.MustConv(groups["second"])
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if err := scanner.Err(); err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
return sum, nil
|
||
|
}
|