Skip to content

Commit

Permalink
feat: day 07 part 2 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
agrmohit committed Dec 7, 2024
1 parent 549c239 commit 717730f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
40 changes: 40 additions & 0 deletions 2024/07/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
_ "embed"
"fmt"
"log"
"strconv"
"strings"

"github.com/agrmohit/aoc/internal/inputs"
Expand All @@ -12,6 +13,12 @@ import (
//go:embed input.txt
var input string

func concat(a int, b int) int {
result, _ := strconv.Atoi(strconv.Itoa(a) + strconv.Itoa(b))

return result
}

// doesSolutionExist checks whether a solution exists recursively
func doesSolutionExist(result int, current int, rest []int) bool {
// Exit condition
Expand All @@ -25,6 +32,19 @@ func doesSolutionExist(result int, current int, rest []int) bool {
return doesSolutionExist(result, current+current1, rest1) || doesSolutionExist(result, current*current1, rest1)
}

// doesSolutionExist checks whether a solution exists recursively, including concat operator
func doesSolutionExist2(result int, current int, rest []int) bool {
// Exit condition
if len(rest) == 0 {
return result == current
}

current1 := rest[0]
rest1 := rest[1:]

return doesSolutionExist2(result, current+current1, rest1) || doesSolutionExist2(result, current*current1, rest1) || doesSolutionExist2(result, concat(current, current1), rest1)
}

func solvePart1(input string) int {
input = strings.ReplaceAll(input, ":", "")
rows, err := inputs.ExtractIntRows(input)
Expand All @@ -43,8 +63,28 @@ func solvePart1(input string) int {
return solutionExistsSum
}

func solvePart2(input string) int {
input = strings.ReplaceAll(input, ":", "")
rows, err := inputs.ExtractIntRows(input)
if err != nil {
log.Fatalf("ERROR: %v", err)
}

solutionExistsSum := 0

for _, line := range rows {
if doesSolutionExist2(line[0], line[1], line[2:]) {
solutionExistsSum += line[0]
}
}

return solutionExistsSum
}

func main() {
part1Solution := solvePart1(input)
part2Solution := solvePart2(input)

fmt.Println("Day 07 Part 1 solution:", part1Solution)
fmt.Println("Day 07 Part 2 solution:", part2Solution)
}
9 changes: 9 additions & 0 deletions 2024/07/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,13 @@ func TestSolution(t *testing.T) {
t.Errorf("Incorrect solution, got %d want %d", got, want)
}
})

t.Run("Day 07 part 2 test 1", func(t *testing.T) {
want := 11387
got := solvePart2(test1)

if got != want {
t.Errorf("Incorrect solution, got %d want %d", got, want)
}
})
}

0 comments on commit 717730f

Please sign in to comment.