day12, part2

This commit is contained in:
efim 2023-12-13 02:41:08 +00:00
parent 6398a4d468
commit 4d346a23db
1 changed files with 14 additions and 4 deletions

View File

@ -55,7 +55,8 @@ func Run() int {
blockLengthSum += blockLen blockLengthSum += blockLen
} }
variantsCount := generatePermutations("", len(mask), blockLengs, blockLengthSum, mask) memo := make(map[string]int)
variantsCount := generatePermutations("", len(mask), blockLengs, blockLengthSum, mask, memo)
log.Printf("%d : for line %s blocks %+v matches %d\n", lineNum, mask, blockLengs, variantsCount) log.Printf("%d : for line %s blocks %+v matches %d\n", lineNum, mask, blockLengs, variantsCount)
matches <- variantsCount matches <- variantsCount
@ -115,7 +116,14 @@ func ReadLine(line string) (string, []int) {
return mask, blockLengs return mask, blockLengs
} }
func generatePermutations(curString string, targetLength int, blockLengths []int, blockLengthsSum int, mask string) int { func generatePermutations(curString string, targetLength int, blockLengths []int, blockLengthsSum int, mask string, memo map[string]int) int {
memoKey := fmt.Sprintf("%+v|%d", blockLengths, len(curString))
memoized, memoFound := memo[memoKey]
if memoFound {
return memoized
}
// fmt.Printf("> entering with \n%s\nfor map \n%s\n\n", curString, mask) // fmt.Printf("> entering with \n%s\nfor map \n%s\n\n", curString, mask)
// time.Sleep(time.Second) // time.Sleep(time.Second)
if !isVariantMatchesMask(curString, mask) { if !isVariantMatchesMask(curString, mask) {
@ -131,6 +139,7 @@ func generatePermutations(curString string, targetLength int, blockLengths []int
if !isVariantMatchesMask(variant, mask) { if !isVariantMatchesMask(variant, mask) {
return 0 return 0
} }
memo[memoKey] = 1
return 1 return 1
} }
@ -150,9 +159,10 @@ func generatePermutations(curString string, targetLength int, blockLengths []int
whenPass := curString + "." whenPass := curString + "."
whenAdd := curString + strings.Repeat("#", nextBlock) + strings.Repeat(".", rightPointRepeat) whenAdd := curString + strings.Repeat("#", nextBlock) + strings.Repeat(".", rightPointRepeat)
passCount := generatePermutations(whenPass, targetLength, blockLengths, blockLengthsSum, mask) passCount := generatePermutations(whenPass, targetLength, blockLengths, blockLengthsSum, mask, memo)
addCount := generatePermutations(whenAdd, targetLength, restBlocks, blockLengthsSum-nextBlock, mask) addCount := generatePermutations(whenAdd, targetLength, restBlocks, blockLengthsSum-nextBlock, mask, memo)
memo[memoKey] = passCount + addCount
return passCount + addCount return passCount + addCount
} }