-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
93 lines (80 loc) · 1.83 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"fmt"
"slices"
"strings"
"github.com/Gavin152/aoc24/internal/filereader"
)
var towels = []string{}
var patterns = []string{}
func parseInput(lines []string) {
part2 := false
for _, line := range lines {
if line == "" {
part2 = true
continue
}
if part2 {
patterns = append(patterns, line)
} else {
split := strings.Split(line, ", ")
for _, towel := range split {
towels = append(towels, strings.TrimSpace(towel))
}
}
}
}
func checkpattern(pattern string, cache map[string]int) int {
val, ok := cache[pattern]
if ok {
return val
}
matches := 0
if pattern == ""{
// fmt.Println("Pattern matched")
return 1
}
for _, towel := range towels {
if towel == pattern {
matches++
} else if strings.HasPrefix(pattern, towel) {
matches += checkpattern(pattern[len(towel):], cache)
}
}
cache[pattern] = matches
return matches
}
func checkpatterns() int {
cache := map[string]int{}
count := 0
for _, pattern := range patterns {
fmt.Printf("Checking pattern %s\n", pattern)
patternMatches := checkpattern(pattern, cache)
fmt.Printf("Pattern %s can be matched %d different ways\n", pattern, patternMatches)
fmt.Println("================")
count += patternMatches
}
return count
}
func main() {
// filePath := "example"
filePath := "data"
var lines []string
err := filereader.ReadFileLineByLine(filePath, func(line string) error {
lines = append(lines, line)
return nil
})
if err != nil {
fmt.Printf("Error reading file: %v\n", err)
return
}
parseInput(lines)
slices.SortFunc(towels, func(a, b string) int {
// Compare lengths in reverse order for descending sort
return len(b) - len(a)
})
// fmt.Printf("Towles: %v\n", towels)
// fmt.Printf("Patterns: %v\n", patterns)
count := checkpatterns()
fmt.Printf("%d matching patterns found", count)
}