get rid of named match groups

This commit is contained in:
onyx-and-iris 2024-12-03 15:43:58 +00:00
parent d32b376619
commit fca32422e4
3 changed files with 11 additions and 25 deletions

View File

@ -9,7 +9,7 @@ import (
"github.com/onyx-and-iris/aoc2024/day-03/internal/util" "github.com/onyx-and-iris/aoc2024/day-03/internal/util"
) )
var reMul = regexp.MustCompile(`mul\((?P<first>[0-9]{1,3}),(?P<second>[0-9]{1,3})\)`) var reMul = regexp.MustCompile(`mul\(([0-9]{1,3}),([0-9]{1,3})\)`)
func Solve(data []byte) (int, error) { func Solve(data []byte) (int, error) {
r := bytes.NewReader(data) r := bytes.NewReader(data)
@ -26,10 +26,9 @@ func parseLines(r io.Reader) (int, error) {
scanner := bufio.NewScanner(r) scanner := bufio.NewScanner(r)
for scanner.Scan() { for scanner.Scan() {
m := reMul.FindAllString(scanner.Text(), -1) matches := reMul.FindAllStringSubmatch(scanner.Text(), -1)
for _, v := range m { for _, m := range matches {
groups := util.GetGroups(reMul, v) sum += util.MustConv(m[1]) * util.MustConv(m[2])
sum += util.MustConv(groups["first"]) * util.MustConv(groups["second"])
} }
} }

View File

@ -11,7 +11,7 @@ import (
log "github.com/sirupsen/logrus" 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\(\)`) var reMulOrDoOrDont = regexp.MustCompile(`mul\(([0-9]{1,3}),([0-9]{1,3})\)|do\(\)|don't\(\)`)
func Solve(data []byte) (int, error) { func Solve(data []byte) (int, error) {
r := bytes.NewReader(data) r := bytes.NewReader(data)
@ -29,9 +29,9 @@ func parseLines(r io.Reader) (int, error) {
scanner := bufio.NewScanner(r) scanner := bufio.NewScanner(r)
for scanner.Scan() { for scanner.Scan() {
m := reMulOrDoOrDont.FindAllString(scanner.Text(), -1) matches := reMulOrDoOrDont.FindAllStringSubmatch(scanner.Text(), -1)
for _, v := range m { for _, m := range matches {
switch v { switch m[0] {
case "do()": case "do()":
do = true do = true
log.Debug("hit a do") log.Debug("hit a do")
@ -41,10 +41,9 @@ func parseLines(r io.Reader) (int, error) {
} }
if do { if do {
groups := util.GetGroups(reMulOrDoOrDont, v) if m[1] != "" && m[2] != "" {
if groups["first"] != "" && groups["second"] != "" { log.Debugf("%s * %s\n", m[1], m[2])
log.Debugf("%s * %s\n", groups["first"], groups["second"]) sum += util.MustConv(m[1]) * util.MustConv(m[2])
sum += util.MustConv(groups["first"]) * util.MustConv(groups["second"])
} }
} }
} }

View File

@ -1,21 +1,9 @@
package util package util
import ( import (
"regexp"
"strconv" "strconv"
) )
func GetGroups(r *regexp.Regexp, s string) map[string]string {
groups := make(map[string]string)
names := r.SubexpNames()
for i, res := range r.FindStringSubmatch(s) {
if i != 0 {
groups[names[i]] = res
}
}
return groups
}
func MustConv(s string) int { func MustConv(s string) int {
n, err := strconv.Atoi(s) n, err := strconv.Atoi(s)
if err != nil { if err != nil {