-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
102 lines (91 loc) · 1.85 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
94
95
96
97
98
99
100
101
102
package main
import (
"io"
"strings"
"github.com/teivah/go-aoc"
)
func fs1(input io.Reader) int {
patterns, designs := parse(input)
dict := make(map[uint8][]string)
for _, pattern := range patterns {
dict[pattern[0]] = append(dict[pattern[0]], pattern)
}
res := 0
cache := make(map[string]bool)
for _, design := range designs {
if solvable(design, dict, cache) {
res++
}
}
return res
}
func parse(input io.Reader) ([]string, []string) {
groups := aoc.StringGroups(aoc.ReaderToStrings(input))
del := aoc.NewDelimiter(groups[0][0], ", ")
return del.GetStrings(), groups[1]
}
func solvable(s string, dict map[uint8][]string, cache map[string]bool) bool {
if len(s) == 0 {
return true
}
if found, ok := cache[s]; ok {
return found
}
patterns, ok := dict[s[0]]
if !ok {
cache[s] = false
return false
}
for _, pattern := range patterns {
if len(pattern) > len(s) {
continue
}
if !strings.HasPrefix(s, pattern) {
continue
}
if solvable(s[len(pattern):], dict, cache) {
cache[s] = true
return true
}
}
cache[s] = false
return false
}
func fs2(input io.Reader) int {
patterns, designs := parse(input)
dict := make(map[uint8][]string)
for _, pattern := range patterns {
dict[pattern[0]] = append(dict[pattern[0]], pattern)
}
res := 0
cache := make(map[string]int)
for _, design := range designs {
res += solvable2(design, dict, cache)
}
return res
}
func solvable2(s string, dict map[uint8][]string, cache map[string]int) int {
if len(s) == 0 {
return 1
}
if found, ok := cache[s]; ok {
return found
}
patterns, ok := dict[s[0]]
if !ok {
cache[s] = 0
return 0
}
count := 0
for _, pattern := range patterns {
if len(pattern) > len(s) {
continue
}
if !strings.HasPrefix(s, pattern) {
continue
}
count += solvable2(s[len(pattern):], dict, cache)
}
cache[s] = count
return count
}