aoc24/day3/main.go
2024-12-03 12:13:28 +01:00

48 lines
1.1 KiB
Go

package main
import (
"fmt"
"regexp"
"strconv"
"strings"
"git.mstar.dev/mstar/aoc24/util"
"git.mstar.dev/mstar/goutils/other"
)
var mulRegex = regexp.MustCompile(`mul\((\d+),(\d+)\)`)
var doDontMulRegex = regexp.MustCompile(`mul\(\d+,\d+\)|do\(\)|don't\(\)`)
func dissectInstruction(inst string) int {
stringElems := strings.TrimSuffix(strings.TrimPrefix(inst, "mul("), ")")
elems := strings.Split(stringElems, ",")
left := other.Must(strconv.Atoi(elems[0]))
right := other.Must(strconv.Atoi(elems[1]))
return left * right
}
func main() {
data := util.LoadFileFromArgs()
matches := mulRegex.FindAllString(string(data), -1)
acc := 0
for _, match := range matches {
acc += dissectInstruction(match)
}
fmt.Printf("Part 1: %d\n", acc)
doDontMatches := doDontMulRegex.FindAllString(string(data), -1)
acc2 := 0
active := true
for _, match := range doDontMatches {
switch {
case strings.HasPrefix(match, "don't()"):
active = false
case strings.HasPrefix(match, "do()"):
active = true
default:
if active {
acc2 += dissectInstruction(match)
}
}
}
fmt.Printf("Part 2: %d\n", acc2)
}