Files
advent-of-code-2024/day3/conditional_mul.go

48 lines
1.0 KiB
Go
Raw Normal View History

2024-12-03 09:47:45 +01:00
package main
import (
"fmt"
"os"
"regexp"
"strconv"
)
func check(e error) {
if e != nil { panic(e) }
}
func main() {
dat, err := os.ReadFile("data.txt")
check(err)
dat_str := string(dat)
// get all numbers within mul(*,*) using capture groups and do() / don't()
r := regexp.MustCompile("mul\\(([0-9]{1,3}),([0-9]{1,3})\\)|do\\(\\)|don't\\(\\)")
matches := r.FindAllStringSubmatch(dat_str, -1)
acc := 0
enabled := true
for _, elem := range matches {
switch elem[0] {
case "do()":
enabled = true
case "don't()":
enabled = false
default:
if enabled {
// convert to numbers
num1, err := strconv.Atoi(elem[1])
check(err)
num2, err := strconv.Atoi(elem[2])
check(err)
acc += num1 * num2
}
}
}
fmt.Println(acc)
}