Skip to content

Commit

Permalink
[2024] Add memoization to Day 19 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
kfarnung committed Dec 19, 2024
1 parent 49b0524 commit b0b290f
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions 2024/day19/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import (

func part1(input string) int64 {
towels, patterns := parseInput(input)
memo := make(map[string]bool)
count := int64(0)

for _, pattern := range patterns {
if isValidPattern(towels, pattern) {
if isValidPattern(towels, pattern, memo) {
count++
}
}
Expand All @@ -34,18 +35,24 @@ func part2(input string) int64 {
return count
}

func isValidPattern(towels []string, pattern string) bool {
func isValidPattern(towels []string, pattern string, memo map[string]bool) bool {
if pattern == "" {
return true
}

if isValid, ok := memo[pattern]; ok {
return isValid
}

for _, towel := range towels {
if len(towel) > len(pattern) {
continue
}

if strings.HasPrefix(pattern, towel) {
if isValidPattern(towels, pattern[len(towel):]) {
isValid := isValidPattern(towels, pattern[len(towel):], memo)
memo[pattern] = isValid
if isValid {
return true
}
}
Expand Down

0 comments on commit b0b290f

Please sign in to comment.