2024-12-03 08:02:16 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"regexp"
|
|
|
|
|
|
|
|
"aoc/helper"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
corruptedMemory := helper.ReadLinesToString()
|
|
|
|
|
|
|
|
// part 1
|
|
|
|
instructions_result := findAndExecuteInstructions(corruptedMemory)
|
|
|
|
fmt.Printf("Result: %d\n", instructions_result)
|
|
|
|
|
|
|
|
// part 2
|
|
|
|
enabled_instructions_result := findAndExecuteEnabledInstructions(corruptedMemory)
|
|
|
|
fmt.Printf("Result (only enabled): %d\n", enabled_instructions_result)
|
|
|
|
}
|
|
|
|
|
|
|
|
func findAndExecuteInstructions(memory string) (res int) {
|
2024-12-04 14:33:55 +00:00
|
|
|
// find all `mul()` and save numbers as MatchGroup 1 + 2
|
2024-12-03 08:02:16 +00:00
|
|
|
re := regexp.MustCompile(`mul\((\d{1,3}),(\d{1,3})\)`)
|
|
|
|
instructions := re.FindAllStringSubmatch(memory, -1)
|
|
|
|
|
|
|
|
for _, inst := range instructions {
|
|
|
|
res += helper.ToInt(inst[1]) * helper.ToInt(inst[2])
|
|
|
|
}
|
|
|
|
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
func findAndExecuteEnabledInstructions(memory string) (res int) {
|
2024-12-04 14:33:55 +00:00
|
|
|
// find all `mul()` and save numbers as MatchGroup 1 + 2
|
|
|
|
// save `do()` and `dont()` in MatchGroup 0
|
2024-12-03 08:02:16 +00:00
|
|
|
re := regexp.MustCompile(`mul\((\d{1,3}),(\d{1,3})\)|do\(\)|don't\(\)`)
|
|
|
|
instructions := re.FindAllStringSubmatch(memory, -1)
|
|
|
|
|
|
|
|
enabled := true
|
|
|
|
for _, inst := range instructions {
|
|
|
|
switch inst[0] {
|
|
|
|
case "do()":
|
|
|
|
enabled = true
|
|
|
|
case "don't()":
|
|
|
|
enabled = false
|
|
|
|
default:
|
|
|
|
if enabled {
|
|
|
|
res += helper.ToInt(inst[1]) * helper.ToInt(inst[2])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return res
|
|
|
|
}
|