|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/kfarnung/advent-of-code/2024/lib" |
| 10 | +) |
| 11 | + |
| 12 | +func part1(input string) int64 { |
| 13 | + towels, patterns := parseInput(input) |
| 14 | + count := int64(0) |
| 15 | + |
| 16 | + for _, pattern := range patterns { |
| 17 | + if isValidPattern(towels, pattern) { |
| 18 | + count++ |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + return count |
| 23 | +} |
| 24 | + |
| 25 | +func part2(input string) int64 { |
| 26 | + towels, patterns := parseInput(input) |
| 27 | + memo := make(map[string]int64) |
| 28 | + count := int64(0) |
| 29 | + |
| 30 | + for _, pattern := range patterns { |
| 31 | + count += countValidPatterns(towels, pattern, memo) |
| 32 | + } |
| 33 | + |
| 34 | + return count |
| 35 | +} |
| 36 | + |
| 37 | +func isValidPattern(towels []string, pattern string) bool { |
| 38 | + if pattern == "" { |
| 39 | + return true |
| 40 | + } |
| 41 | + |
| 42 | + for _, towel := range towels { |
| 43 | + if len(towel) > len(pattern) { |
| 44 | + continue |
| 45 | + } |
| 46 | + |
| 47 | + if strings.HasPrefix(pattern, towel) { |
| 48 | + if isValidPattern(towels, pattern[len(towel):]) { |
| 49 | + return true |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return false |
| 55 | +} |
| 56 | + |
| 57 | +func countValidPatterns(towels []string, pattern string, memo map[string]int64) int64 { |
| 58 | + if pattern == "" { |
| 59 | + return 1 |
| 60 | + } |
| 61 | + |
| 62 | + if count, ok := memo[pattern]; ok { |
| 63 | + return count |
| 64 | + } |
| 65 | + |
| 66 | + count := int64(0) |
| 67 | + |
| 68 | + for _, towel := range towels { |
| 69 | + if len(towel) > len(pattern) { |
| 70 | + continue |
| 71 | + } |
| 72 | + |
| 73 | + if strings.HasPrefix(pattern, towel) { |
| 74 | + nextPattern := pattern[len(towel):] |
| 75 | + tempCount := countValidPatterns(towels, nextPattern, memo) |
| 76 | + memo[nextPattern] = tempCount |
| 77 | + count += tempCount |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return count |
| 82 | +} |
| 83 | + |
| 84 | +func parseInput(input string) ([]string, []string) { |
| 85 | + var towels []string |
| 86 | + var patterns []string |
| 87 | + for _, line := range lib.SplitLines(input) { |
| 88 | + if line == "" { |
| 89 | + continue |
| 90 | + } |
| 91 | + |
| 92 | + if towels == nil { |
| 93 | + towels = strings.Split(line, ", ") |
| 94 | + } else { |
| 95 | + patterns = append(patterns, line) |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + return towels, patterns |
| 100 | +} |
| 101 | + |
| 102 | +func main() { |
| 103 | + name := os.Args[1] |
| 104 | + content, err := lib.LoadFileContent(name) |
| 105 | + if err != nil { |
| 106 | + log.Fatal(err) |
| 107 | + } |
| 108 | + |
| 109 | + fmt.Printf("Part 1: %d\n", part1(content)) |
| 110 | + fmt.Printf("Part 2: %d\n", part2(content)) |
| 111 | +} |
0 commit comments