Skip to content

Commit 3e735bb

Browse files
committed
day3: first part
1 parent da4ebd9 commit 3e735bb

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

day3/example.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))

day3/main.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"fmt"
6+
"github.com/fxnn/adventofcode2024/util"
7+
"os"
8+
"regexp"
9+
)
10+
11+
func main() {
12+
scanner := bufio.NewScanner(os.Stdin)
13+
scanner.Split(bufio.ScanLines)
14+
15+
var text string
16+
for scanner.Scan() {
17+
text += scanner.Text()
18+
}
19+
20+
pattern := regexp.MustCompile(`mul\((\d+),(\d+)\)`)
21+
result := 0
22+
for _, match := range pattern.FindAllStringSubmatch(text, -1) {
23+
n1 := util.Atoi(match[1])
24+
n2 := util.Atoi(match[2])
25+
result += n1 * n2
26+
}
27+
28+
fmt.Printf("result: %d\n", result)
29+
}

util/util.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,21 @@
11
package util
22

3-
import "fmt"
3+
import (
4+
"fmt"
5+
"os"
6+
"strconv"
7+
)
8+
9+
// Atoi converts string to integer, and exist immediately upon error
10+
func Atoi(s string) int {
11+
if i, err := strconv.Atoi(s); err != nil {
12+
fmt.Fprintf(os.Stderr, "Error in Atoi(%s): %s\n", s, err)
13+
os.Exit(1)
14+
return 0
15+
} else {
16+
return i
17+
}
18+
}
419

520
// Abs calculates the absolute value of an integer
621
func Abs(x int) int {

0 commit comments

Comments
 (0)