Day03
This commit is contained in:
49
2024/gareth/day03/day03.go
Normal file
49
2024/gareth/day03/day03.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user