Skip to content

Commit 717730f

Browse files
committed
feat: day 07 part 2 solution
1 parent 549c239 commit 717730f

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

2024/07/main.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
_ "embed"
55
"fmt"
66
"log"
7+
"strconv"
78
"strings"
89

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

16+
func concat(a int, b int) int {
17+
result, _ := strconv.Atoi(strconv.Itoa(a) + strconv.Itoa(b))
18+
19+
return result
20+
}
21+
1522
// doesSolutionExist checks whether a solution exists recursively
1623
func doesSolutionExist(result int, current int, rest []int) bool {
1724
// Exit condition
@@ -25,6 +32,19 @@ func doesSolutionExist(result int, current int, rest []int) bool {
2532
return doesSolutionExist(result, current+current1, rest1) || doesSolutionExist(result, current*current1, rest1)
2633
}
2734

35+
// doesSolutionExist checks whether a solution exists recursively, including concat operator
36+
func doesSolutionExist2(result int, current int, rest []int) bool {
37+
// Exit condition
38+
if len(rest) == 0 {
39+
return result == current
40+
}
41+
42+
current1 := rest[0]
43+
rest1 := rest[1:]
44+
45+
return doesSolutionExist2(result, current+current1, rest1) || doesSolutionExist2(result, current*current1, rest1) || doesSolutionExist2(result, concat(current, current1), rest1)
46+
}
47+
2848
func solvePart1(input string) int {
2949
input = strings.ReplaceAll(input, ":", "")
3050
rows, err := inputs.ExtractIntRows(input)
@@ -43,8 +63,28 @@ func solvePart1(input string) int {
4363
return solutionExistsSum
4464
}
4565

66+
func solvePart2(input string) int {
67+
input = strings.ReplaceAll(input, ":", "")
68+
rows, err := inputs.ExtractIntRows(input)
69+
if err != nil {
70+
log.Fatalf("ERROR: %v", err)
71+
}
72+
73+
solutionExistsSum := 0
74+
75+
for _, line := range rows {
76+
if doesSolutionExist2(line[0], line[1], line[2:]) {
77+
solutionExistsSum += line[0]
78+
}
79+
}
80+
81+
return solutionExistsSum
82+
}
83+
4684
func main() {
4785
part1Solution := solvePart1(input)
86+
part2Solution := solvePart2(input)
4887

4988
fmt.Println("Day 07 Part 1 solution:", part1Solution)
89+
fmt.Println("Day 07 Part 2 solution:", part2Solution)
5090
}

2024/07/main_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,13 @@ func TestSolution(t *testing.T) {
1717
t.Errorf("Incorrect solution, got %d want %d", got, want)
1818
}
1919
})
20+
21+
t.Run("Day 07 part 2 test 1", func(t *testing.T) {
22+
want := 11387
23+
got := solvePart2(test1)
24+
25+
if got != want {
26+
t.Errorf("Incorrect solution, got %d want %d", got, want)
27+
}
28+
})
2029
}

0 commit comments

Comments
 (0)