From 35cf750af8c429be1dc7c921fcc63f517ba1df50 Mon Sep 17 00:00:00 2001 From: Kuaku Date: Thu, 19 Dec 2024 22:19:24 +0100 Subject: [PATCH] [ADD] Added day 19 solution part 2 --- 19/main.go | 86 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 62 insertions(+), 24 deletions(-) diff --git a/19/main.go b/19/main.go index 428529e..ab34fc3 100644 --- a/19/main.go +++ b/19/main.go @@ -43,41 +43,79 @@ func TransformInput(lines []string) structuredInput { return Puzzle{strings.Split(lines[0], ", "), lines[2:]} } +var poss []string +var cachePart1 map[string]bool = make(map[string]bool) + +func hasSolution(input string) bool { + if len(input) == 0 { + return true + } + + value, ok := cachePart1[input] + + if ok { + return value + } + + var result = false + + for i := 0; i < len(poss); i++ { + if len(input) >= len(poss[i]) && input[:len(poss[i])] == poss[i] && hasSolution(input[len(poss[i]):]) { + result = true + break + } + } + + cachePart1[input] = result + return result +} + func Part1(input structuredInput) int { var result = 0 - var poss []string - var found bool - var work string + poss = input.poss - for i, line := range input.lines { - fmt.Println(i) - poss = []string{line} - found = false - for !found && len(poss) > 0 { - work = poss[0] - poss = poss[1:] - for j := 0; j < len(input.poss); j++ { - if len(input.poss[j]) <= len(work) { - if work[:len(input.poss[j])] == input.poss[j] { - poss = append(poss, work[len(input.poss[j]):]) - if len(work[len(input.poss[j]):]) == 0 { - found = true - break - } - } - } - } - } - if found { - result += 1 + for _, line := range input.lines { + if hasSolution(line) { + result++ } } return result } +var cachePart2 map[string]int = make(map[string]int) + +func findSolutionCount(input string) int { + if len(input) == 0 { + return 1 + } + + value, ok := cachePart2[input] + + if ok { + return value + } + + var result = 0 + + for i := 0; i < len(poss); i++ { + if len(input) >= len(poss[i]) && input[:len(poss[i])] == poss[i] { + result += findSolutionCount(input[len(poss[i]):]) + } + } + + cachePart2[input] = result + return result +} + func Part2(input structuredInput) int { var result = 0 + poss = input.poss + + for _, line := range input.lines { + result += findSolutionCount(line) + } + return result }