Skip to content

Commit b0b290f

Browse files
committed
[2024] Add memoization to Day 19 part 1
1 parent 49b0524 commit b0b290f

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

2024/day19/main.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,11 @@ import (
1111

1212
func part1(input string) int64 {
1313
towels, patterns := parseInput(input)
14+
memo := make(map[string]bool)
1415
count := int64(0)
1516

1617
for _, pattern := range patterns {
17-
if isValidPattern(towels, pattern) {
18+
if isValidPattern(towels, pattern, memo) {
1819
count++
1920
}
2021
}
@@ -34,18 +35,24 @@ func part2(input string) int64 {
3435
return count
3536
}
3637

37-
func isValidPattern(towels []string, pattern string) bool {
38+
func isValidPattern(towels []string, pattern string, memo map[string]bool) bool {
3839
if pattern == "" {
3940
return true
4041
}
4142

43+
if isValid, ok := memo[pattern]; ok {
44+
return isValid
45+
}
46+
4247
for _, towel := range towels {
4348
if len(towel) > len(pattern) {
4449
continue
4550
}
4651

4752
if strings.HasPrefix(pattern, towel) {
48-
if isValidPattern(towels, pattern[len(towel):]) {
53+
isValid := isValidPattern(towels, pattern[len(towel):], memo)
54+
memo[pattern] = isValid
55+
if isValid {
4956
return true
5057
}
5158
}

0 commit comments

Comments
 (0)