Skip to content

Commit

Permalink
feat: day 3 aoc
Browse files Browse the repository at this point in the history
  • Loading branch information
Jitesh117 committed Dec 3, 2024
1 parent 1ec6a5d commit 297fa07
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions content/blog/aoc_2024.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,66 @@ func main() {
}

```

## Day 3

```go
package main

import (
"fmt"
"os"
"regexp"
"strconv"
)

func part1(input string) int {
mulPattern := regexp.MustCompile(`mul\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)`)

results := 0
for _, match := range mulPattern.FindAllStringSubmatch(input, -1) {
num1, _ := strconv.Atoi(match[1])
num2, _ := strconv.Atoi(match[2])
results += num1 * num2
}
return results
}

func part2(input string) int {
mulPattern := regexp.MustCompile(`mul\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)`)
doPattern := regexp.MustCompile(`do\(\)`)
dontPattern := regexp.MustCompile(`don'?t\(\)`)

results := 0
mulEnabled := true

combinedPattern := regexp.MustCompile(
fmt.Sprintf(`%s|%s|%s`, mulPattern.String(), doPattern.String(), dontPattern.String()),
)

for _, match := range combinedPattern.FindAllStringSubmatch(input, -1) {
if doPattern.MatchString(match[0]) {
mulEnabled = true
} else if dontPattern.MatchString(match[0]) {
mulEnabled = false
} else if mulPattern.MatchString(match[0]) && mulEnabled {
num1, _ := strconv.Atoi(match[1])
num2, _ := strconv.Atoi(match[2])
results += num1 * num2
}
}
return results
}

func main() {
inputBytes, err := os.ReadFile("input.txt")
if err != nil {
panic(err)
}
input := string(inputBytes)

fmt.Printf("Part 1 Result: %d\n", part1(input))
fmt.Printf("Part 2 Result: %d\n", part2(input))
}

```

0 comments on commit 297fa07

Please sign in to comment.