-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (70 loc) · 1.46 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
package main
import (
"fmt"
"strconv"
"strings"
"github.com/devkvlt/aoc"
)
var lines = aoc.Lines("input")
var cache = make(map[string]int)
func key(cond string, nums []int) string {
strNums := make([]string, len(nums))
for i := 0; i < len(nums); i++ {
strNums[i] = strconv.Itoa(nums[i])
}
return cond + strings.Join(strNums, ",")
}
func count(cond string, nums []int) int {
key := key(cond, nums)
result, ok := cache[key]
if ok {
return result
}
if cond == "" {
if len(nums) == 0 {
return 1
}
return 0
}
if len(nums) == 0 {
if strings.ContainsRune(cond, '#') {
return 0
}
return 1
}
if cond[0] == '.' || cond[0] == '?' {
result += count(cond[1:], nums)
}
if (cond[0] == '#' || cond[0] == '?') &&
nums[0] <= len(cond) &&
!strings.ContainsRune(cond[:nums[0]], '.') &&
(nums[0] == len(cond) || cond[nums[0]] != '#') {
k := min(nums[0]+1, len(cond))
result += count(cond[k:], nums[1:])
}
cache[key] = result
return result
}
func solveWith(repeat int) {
sum := 0
for _, line := range lines {
fields := strings.Fields(line)
cond := fields[0]
rawNums := strings.Split(fields[1], ",")
n := len(rawNums)
nums := make([]int, n)
for i := 0; i < n; i++ {
nums[i] = aoc.Atoi(rawNums[i])
}
for i := 1; i < repeat; i++ {
cond += "?" + fields[0]
nums = append(nums, nums[:n]...)
}
sum += count(cond, nums)
}
fmt.Println(sum)
}
func main() {
solveWith(1) // 6935
solveWith(5) // 3920437278260
}