-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay7.go
More file actions
114 lines (90 loc) · 2.27 KB
/
Day7.go
File metadata and controls
114 lines (90 loc) · 2.27 KB
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
package main
import (
"fmt"
"strconv"
"strings"
)
func (day *Day) Day7a() {
fmt.Printf("Part 1: %d\n", ComputeDay7a(day.input))
}
func (day *Day) Day7b() {
fmt.Printf("Part 2: %d\n", ComputeDay7b(day.input))
}
type Bag struct {
qualifier string
color string
}
type BagNode struct {
bag Bag
contains map[Bag]int
contained []Bag
}
var graph map[Bag]*BagNode
func ComputeDay7a(input string) int {
graph = make(map[Bag]*BagNode)
lines := strings.Split(input, "\n")
for _, line := range lines {
parseLine(line)
}
startBag := Bag { "shiny", "gold" }
parents := make(map[Bag]bool)
nodes := make([]Bag, 0)
nodes = append(nodes, startBag)
for len(nodes) != 0 {
bag := nodes[0]
nodes = nodes[1:]
for _, v := range graph[bag].contained {
_, ok := parents[v] ; if !ok {
nodes = append(nodes, v)
parents[v] = true
}
}
}
return len(parents)
}
func parseLine(line string) {
toks := strings.Split(line, " contain ")
bagtoks := strings.Split(toks[0], " ")
bag1 := Bag { bagtoks[0], bagtoks[1] }
var bag1Node * BagNode
var ok bool
if bag1Node, ok = graph[bag1]; !ok {
bag1Node = &BagNode { bag1, make(map[Bag]int), make([]Bag, 0)}
graph[bag1] = bag1Node
}
if toks[1] != "no other bags." {
containedBagsList := strings.Split(toks[1], ", ")
for _, containedBagElem := range containedBagsList {
containedBagToks := strings.Split(containedBagElem, " ")
containedBag := Bag{containedBagToks[1], containedBagToks[2]}
var containedBagNode *BagNode
if containedBagNode, ok = graph[containedBag]; !ok {
containedBagNode = &BagNode{containedBag, make(map[Bag]int), make([]Bag, 0)}
graph[containedBag] = containedBagNode
}
num, err := strconv.Atoi(containedBagToks[0])
if err != nil {
panic("Could not parse bag " + line)
}
bag1Node.contains[containedBag] = num
containedBagNode.contained = append(containedBagNode.contained, bag1)
}
}
}
func ComputeDay7b(input string) int {
graph = make(map[Bag]*BagNode)
lines := strings.Split(input, "\n")
for _, line := range lines {
parseLine(line)
}
startBag := Bag { "shiny", "gold" }
return numChildBags(startBag)
}
func numChildBags(bag Bag) int {
nodeBag := graph[bag]
res := 0
for k, v := range nodeBag.contains {
res = res + v * (1 + numChildBags(k))
}
return res
}