-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.go
86 lines (79 loc) · 2.21 KB
/
day7.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
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
func main() {
i, err := ioutil.ReadFile("input.txt")
if err != nil {
os.Exit(1)
}
fmt.Printf("Part 1: %v\n", SolveDay7Part1(stringListToSlice(string(i))))
fmt.Printf("Part 2: %v\n", SolveDay7Part2(stringListToSlice(string(i))))
}
//SolveDay7Part1 counts the colors that can contain a shiny gold bag
func SolveDay7Part1(i []string) (c int) {
bags := exportBags(i)
colorsToCheck := []string{"shiny gold"}
checkedColors := make(map[string]bool)
for {
var newColorsToCheck []string
for _, checkColor := range colorsToCheck {
for color, bag := range bags {
if bag[checkColor] > 0 && !checkedColors[color] {
newColorsToCheck = append(newColorsToCheck, color)
checkedColors[color] = true
c++
}
}
}
if len(newColorsToCheck) == 0 {
return
}
colorsToCheck = newColorsToCheck
}
}
//SolveDay7Part2 counts the bags that are contained in one shiny gold
func SolveDay7Part2(i []string) int {
bags := exportBags(i)
return countBags("shiny gold", 1, bags) - 1
}
// count the bags that are contained in a bag (incl. the initial bag)
func countBags(color string, i int, bags map[string]map[string]int) int {
s := i
for nextColor, num := range bags[color] {
s += i * countBags(nextColor, num, bags)
}
return s
}
//exportBags export all bags that contains other bags in a map that contains a map with all contained bags and the number of contained bags
func exportBags(i []string) (bags map[string]map[string]int) {
bags = make(map[string]map[string]int)
for _, line := range i {
if !strings.HasSuffix(line, "bags contain no other bags.") {
split := strings.Split(line, " bags contain ")
bag := make(map[string]int)
for _, c := range strings.Split(split[1], ", ") {
t := strings.Split(c, " ")
containInt, err := strconv.Atoi(t[0])
if err != nil {
return nil
}
bag[t[1]+" "+t[2]] = containInt
}
bags[split[0]] = bag
}
}
return
}
//Helper functions
//stringListToSlice converts the list of strings (each string one row) to a slice
func stringListToSlice(list string) (s []string) {
for _, line := range strings.Split(strings.TrimSuffix(list, "\n"), "\n") {
s = append(s, line)
}
return
}