This commit is contained in:
Gareth
2024-12-03 11:15:43 +00:00
parent 8f4649e0aa
commit f6f5a10270
4 changed files with 76 additions and 4 deletions

View File

@@ -0,0 +1,49 @@
package day03
import (
"regexp"
"strconv"
)
func Part1(input string) int {
total := 0
regex := regexp.MustCompile(`mul\((\d+),(\d+)\)`)
matches := regex.FindAllStringSubmatch(input, -1)
for _, match := range matches {
if len(match) == 3 {
x, _ := strconv.Atoi(match[1])
y, _ := strconv.Atoi(match[2])
total += x * y
}
}
return total
}
func Part2(input string) int {
total := 0
isEnabled := true
mulRegex := regexp.MustCompile(`mul\((\d+),(\d+)\)`)
doRegex := regexp.MustCompile(`do\(\)`)
dontRegex := regexp.MustCompile(`don't\(\)`)
tokenizeRegex := regexp.MustCompile(`(mul\(\d+,\d+\)|do\(\)|don't\(\))`)
tokens := tokenizeRegex.FindAllString(input, -1)
for _, token := range tokens {
if doRegex.MatchString(token) {
isEnabled = true
} else if dontRegex.MatchString(token) {
isEnabled = false
} else if mulRegex.MatchString(token) && isEnabled {
mulMatch := mulRegex.FindStringSubmatch(token)
x, _ := strconv.Atoi(mulMatch[1])
y, _ := strconv.Atoi(mulMatch[2])
total += x * y
}
}
return total
}