Files
adventofcode/2024/gareth/day03/day03.go
2024-12-03 11:15:43 +00:00

50 lines
1.0 KiB
Go

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
}