-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain2.go
60 lines (45 loc) · 1.07 KB
/
main2.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
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
rules := parse()
fmt.Println(dfs("shiny gold", rules))
}
func dfs(item string, rules map[string]map[string]int) int {
count := 0
for k, v := range rules[item] {
count += v + v*dfs(k, rules)
}
return count
}
func parse() map[string]map[string]int {
ruleRegex := regexp.MustCompile("^([a-z ]+) bags contain (.+)\\.$")
contentRegex := regexp.MustCompile("^([0-9]+) ([a-z ]+) bag[s]?$")
rules := map[string]map[string]int{}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
arr := ruleRegex.FindStringSubmatch(scanner.Text())
subject, content := arr[1], arr[2]
rules[subject] = make(map[string]int, 0)
if content == "no other bags" {
continue
}
items := strings.Split(content, ", ")
for _, it := range items {
arr = contentRegex.FindStringSubmatch(it)
// create if not exist
if _, ok := rules[subject]; !ok {
rules[subject] = make(map[string]int)
}
num, _ := strconv.Atoi(arr[1])
rules[subject][arr[2]] = num
}
}
return rules
}