-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
107 lines (80 loc) · 1.87 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
103
104
105
106
107
package main
import (
"bufio"
"fmt"
"io"
"os"
"path"
"regexp"
"strconv"
"strings"
)
func input() *os.File {
input, err := os.Open(path.Join("2020", "7", "input.txt"))
if err != nil {
panic(err)
}
return input
}
const (
targetBag = "shiny gold"
noContents = "no other bags"
)
var (
innerBag = regexp.MustCompile(`(\d+?) (.+?) bags?`)
ruleRegex = regexp.MustCompile(`^(.+?) bags contain (.+?)\.$`)
)
func parse(r io.Reader) map[string]map[string]int {
scanner := bufio.NewScanner(r)
rules := make(map[string]map[string]int)
for scanner.Scan() {
row := scanner.Text()
outer, inner := parseRule(row)
rules[outer] = inner
}
if scanner.Err() != nil {
panic(scanner.Err())
}
return rules
}
func parseRule(raw string) (string, map[string]int) {
ruleMatches := ruleRegex.FindStringSubmatch(raw)
if ruleMatches == nil {
panic(fmt.Sprintf("don't know how to parse rule %s", raw))
}
outer := ruleMatches[1]
if ruleMatches[2] == noContents {
return outer, nil
}
inner := make(map[string]int)
rawContents := strings.Split(ruleMatches[2], ",")
for _, rawBag := range rawContents {
innerBagMatches := innerBag.FindStringSubmatch(rawBag)
if innerBagMatches == nil {
panic(fmt.Sprintf("don't know how to parse inner bag %s", rawBag))
}
numInner, err := strconv.Atoi(innerBagMatches[1])
if err != nil {
panic(err)
}
inner[innerBagMatches[2]] = numInner
}
return outer, inner
}
func numContents(color string, cache map[string]int, rules map[string]map[string]int) int {
if num, ok := cache[color]; ok {
return num
}
sum := 1
for newColor, amount := range rules[color] {
sum += amount * numContents(newColor, cache, rules)
}
cache[color] = sum
return sum
}
func solve(rules map[string]map[string]int) int {
return numContents(targetBag, make(map[string]int), rules) - 1
}
func main() {
fmt.Println(solve(parse(input())))
}