54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package day03
|
|
|
|
import (
|
|
"regexp"
|
|
"strings"
|
|
|
|
"aoc2024/internal/common"
|
|
)
|
|
|
|
func Handle(input []byte) (int, int) {
|
|
result1 := getSumMulStr(input)
|
|
result2 := 0
|
|
dos := getDo(input)
|
|
for _, do := range dos {
|
|
result2 += getSumMulStr(do)
|
|
}
|
|
|
|
return result1, result2
|
|
}
|
|
|
|
func getSumMulStr(input []byte) int {
|
|
sum := 0
|
|
re := regexp.MustCompile(`(mul\(\d+,\d+\))`)
|
|
reNumber := regexp.MustCompile(`(\d+)`)
|
|
|
|
matches := re.FindAll(input, -1)
|
|
for _, match := range matches {
|
|
numberStr := reNumber.FindAll(match, -1)
|
|
sum += common.StrToInt(string(numberStr[0])) * common.StrToInt(string(numberStr[1]))
|
|
|
|
}
|
|
|
|
return sum
|
|
}
|
|
|
|
func getDo(input []byte) [][]byte {
|
|
re := regexp.MustCompile(`(do\(\)|don't\(\))`)
|
|
firstIndex := re.FindIndex(input)
|
|
firstSegment := input[:firstIndex[1]]
|
|
re = regexp.MustCompile(`do\(\)`)
|
|
indexes := re.FindAllIndex(input, -1)
|
|
lastSegment := input[indexes[len(indexes)-1][0]:]
|
|
|
|
re = regexp.MustCompile(`(?s)(do\(\)).*?(don't\(\))`)
|
|
matches := re.FindAll(input, -1)
|
|
|
|
matches = append(matches, firstSegment)
|
|
if !strings.Contains(string(lastSegment), "don't()") {
|
|
matches = append(matches, lastSegment)
|
|
}
|
|
|
|
return matches
|
|
}
|