60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package day_03
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
// task:https://adventofcode.com/2024/day/2
|
|
// short summary - find valid mul instructions in corrupted memory
|
|
// commands are valid if they are in the form "mul(" + %d "," + %d + ")"
|
|
func SolveBasic(input string) int {
|
|
expr, err := regexp.Compile("mul\\(\\d*,\\d*\\)")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
instructions := expr.FindAllString(input, -1)
|
|
sum := calculate(instructions)
|
|
return sum
|
|
}
|
|
|
|
// task:https://adventofcode.com/2024/day/2#part2
|
|
// short summary - find valid mul instructions in corrupted memory
|
|
// commands are valid if they are in the form "mul(" + %d "," + %d + ")"
|
|
// everytime there is a don't() instruction in memory we ignore muls until we reach a do() command
|
|
func SolveComplex(input string) int {
|
|
expr, err := regexp.Compile("mul\\(\\d*,\\d*\\)")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
instructionString := ""
|
|
// we split string everytime actions get enabled
|
|
doSubstrings := strings.Split(input, "do()")
|
|
for _, s := range doSubstrings {
|
|
// then we split on the first appearance of don't(),
|
|
// making that the first substrings has valid instructions
|
|
substrings := strings.Split(s, "don't()")
|
|
instructionString += substrings[0]
|
|
}
|
|
instructions := expr.FindAllString(instructionString, -1)
|
|
sum := calculate(instructions)
|
|
return sum
|
|
}
|
|
|
|
func calculate(instructions []string) int {
|
|
sum := 0
|
|
for _, instr := range instructions {
|
|
a := 0
|
|
b := 0
|
|
_, err := fmt.Sscanf(instr, "mul(%d,%d)", &a, &b)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
sum += a * b
|
|
}
|
|
return sum
|
|
}
|
|
|
|
// helper methods
|