add day3
This commit is contained in:
36
day3/mul.go
Normal file
36
day3/mul.go
Normal file
@@ -0,0 +1,36 @@
|
||||
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
|
||||
r := regexp.MustCompile("mul\\(([0-9]{1,3}),([0-9]{1,3})\\)")
|
||||
matches := r.FindAllStringSubmatch(dat_str, -1)
|
||||
|
||||
acc := 0
|
||||
for _, elem := range matches {
|
||||
// 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