-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (60 loc) · 1.5 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
package main
import (
"fmt"
"strings"
aoc "github.com/shraddhaag/aoc/library"
)
func main() {
input := aoc.ReadFileLineByLine("input.txt")
ans1, ans2 := getPossibleCount(getTowelsAndDesigns(input))
fmt.Println("answer to part 1: ", ans1)
fmt.Println("answer to part 2: ", ans2)
}
func getTowelsAndDesigns(input []string) (towels []string, designs []string) {
for _, row := range input {
if len(row) == 0 {
continue
}
if strings.Contains(row, ",") {
towels = append(towels, strings.Split(row, ",")...)
} else {
designs = append(designs, strings.TrimSpace(row))
}
}
for i, t := range towels {
towels[i] = strings.TrimSpace(t)
}
return
}
func isTowelPossible(towelDesign string, towelPatterns []string, possible map[string]int) int {
if val, ok := possible[towelDesign]; ok {
return val
}
isPossibleCount := 0
for _, t := range towelPatterns {
if len(t) > len(towelDesign) {
continue
}
if strings.HasPrefix(towelDesign, t) {
if len(t) == len(towelDesign) {
isPossibleCount++
continue
}
isPossibleCount += isTowelPossible(towelDesign[len(t):], towelPatterns, possible)
}
}
possible[towelDesign] = isPossibleCount
return isPossibleCount
}
func getPossibleCount(towels []string, designs []string) (int, int) {
count1, count2 := 0, 0
possible := make(map[string]int)
for _, d := range designs {
isPossibleCount := isTowelPossible(d, towels, possible)
count2 += isPossibleCount
if isPossibleCount > 0 {
count1 += 1
}
}
return count1, count2
}