-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
116 lines (82 loc) · 2 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
108
109
110
111
112
113
114
115
116
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
}
var innerRegex = regexp.MustCompile(`(\d+?) (.+?) bags?`)
var ruleRegex = regexp.MustCompile(`^(.+?) bags contain (.+?).$`)
var noneRegex = regexp.MustCompile(`(.+) bags contain no other bags.`)
type rule struct {
outer string
inner map[string]int
}
func parseRule(def string) rule {
if noneRegex.MatchString(def) {
matches := noneRegex.FindAllStringSubmatch(def, -1)
return rule{
outer: matches[0][1],
}
}
matches := ruleRegex.FindAllStringSubmatch(def, -1)
rule := rule{
inner: make(map[string]int),
}
rule.outer = matches[0][1]
rawInner := strings.Split(matches[0][2], ",")
for _, item := range rawInner {
items := innerRegex.FindStringSubmatch(item)
numInner, _ := strconv.Atoi(items[1])
rule.inner[items[2]] = numInner
}
return rule
}
func containsShinyGold(color string, rules map[string]map[string]int) bool {
contents := rules[color]
for newColor, _ := range contents {
if newColor == "shiny gold" {
return true
}
if containsShinyGold(newColor, rules) {
return true
}
}
return false
}
func solve(r io.Reader) int {
scanner := bufio.NewScanner(r)
rules := make(map[string]map[string]int)
for scanner.Scan() {
row := scanner.Text()
parsed := parseRule(row)
rules[parsed.outer] = parsed.inner
}
if scanner.Err() != nil {
panic(scanner.Err())
}
hasShiny := make(map[string]bool)
for color := range rules {
if containsShinyGold(color, rules) {
hasShiny[color] = true
}
}
return len(hasShiny)
}
func main() {
fmt.Println(parseRule("muted white bags contain 3 muted tomato bags, 5 light black bags, 4 pale black bags, 5 shiny gold bags."))
fmt.Println(parseRule("light black bags contain 1 striped yellow bag."))
fmt.Println(parseRule("dotted tomato bags contain no other bags."))
fmt.Println(solve(input()))
}