Skip to content

Commit

Permalink
day 3 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
gamersi committed Dec 3, 2024
1 parent ff1b03c commit b0a45f3
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
46 changes: 46 additions & 0 deletions day03p2/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package day03p2

import (
"io"
"regexp"
"strconv"

"aoc/utils"
)

func Solve(r io.Reader) any {
lines := utils.ReadLines(r)
sum := 0

cumulStr := ""
for _, line := range lines {
cumulStr += line
}

instructionRegex, _ := regexp.Compile(`(mul\((\d+),(\d+)\)|do\(\)|don't\(\))`)
matches := instructionRegex.FindAllStringSubmatch(cumulStr, -1)

mulEnabled := true

for _, match := range matches {
instruction := match[1]

if instruction == "do()" {
mulEnabled = true
} else if instruction == "don't()" {
mulEnabled = false
} else if match[2] != "" && match[3] != "" {
if mulEnabled {
x, _ := strconv.Atoi(match[2])
y, _ := strconv.Atoi(match[3])
sum += x * y
}
}
}

return sum
}

func ArrayIsEmpty(a []int) bool {
return len(a) == 0
}
33 changes: 33 additions & 0 deletions day03p2/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package day03p2

import (
"strings"
"testing"

"aoc/utils"
)

var testInput = `xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))`

func TestSolve(t *testing.T) {
tests := []struct {
input string
answer int
}{
{testInput, 48},
}

if testing.Verbose() {
utils.Verbose = true
}

for _, test := range tests {
r := strings.NewReader(test.input)

result := Solve(r).(int)

if result != test.answer {
t.Errorf("Expected %d, got %d", test.answer, result)
}
}
}

0 comments on commit b0a45f3

Please sign in to comment.