add day3
This commit is contained in:
47
day3/conditional_mul.go
Normal file
47
day3/conditional_mul.go
Normal file
@@ -0,0 +1,47 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user