|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "regexp" |
| 8 | + "strconv" |
| 9 | +) |
| 10 | + |
| 11 | +type pair struct { |
| 12 | + amount int |
| 13 | + color string |
| 14 | +} |
| 15 | + |
| 16 | +func main() { |
| 17 | + scanner := bufio.NewScanner(os.Stdin) |
| 18 | + |
| 19 | + rules := make(map[string][]pair) |
| 20 | + |
| 21 | + for scanner.Scan() { |
| 22 | + ruleString := scanner.Text() |
| 23 | + color, contained := parseRule(ruleString) |
| 24 | + rules[color] = contained |
| 25 | + } |
| 26 | + |
| 27 | + sum := 0 |
| 28 | + |
| 29 | + for key := range rules { |
| 30 | + if contains(rules, key, "shiny gold") { |
| 31 | + sum++ |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + fmt.Println(sum) |
| 36 | + |
| 37 | + // subtract one cost as we care about the cost of the bags **within** the |
| 38 | + // initial bag |
| 39 | + fmt.Println(colorCost(rules, "shiny gold") - 1) |
| 40 | +} |
| 41 | + |
| 42 | +func parseRule(s string) (color string, contained []pair) { |
| 43 | + reBagColor := regexp.MustCompile(`^([\w ]*) bags contain`) |
| 44 | + reBagColorMatches := reBagColor.FindStringSubmatch(s) |
| 45 | + color = reBagColorMatches[1] |
| 46 | + reNoOther := regexp.MustCompile(`no other bags`) |
| 47 | + |
| 48 | + if reNoOther.MatchString(s) { |
| 49 | + // No bags are contained, return early |
| 50 | + return color, make([]pair, 0) |
| 51 | + } |
| 52 | + |
| 53 | + reBagContains := regexp.MustCompile(`(,? (\d+) ([\w ]*) bags?)`) |
| 54 | + reBagContainsMatches := reBagContains.FindAllStringSubmatch(s, -1) |
| 55 | + contained = make([]pair, len(reBagContainsMatches)) |
| 56 | + |
| 57 | + for i, matches := range reBagContainsMatches { |
| 58 | + amount, err := strconv.Atoi(matches[2]) |
| 59 | + |
| 60 | + if err != nil { |
| 61 | + panic("misbehaving number string >:(") |
| 62 | + } |
| 63 | + |
| 64 | + contained[i] = pair{ |
| 65 | + amount: amount, // don't care about this one |
| 66 | + color: matches[3], |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return color, contained |
| 71 | +} |
| 72 | + |
| 73 | +// does 'color' contain 'target'? |
| 74 | +// assume X can't contain X |
| 75 | +func contains(rules map[string][]pair, color, target string) bool { |
| 76 | + for _, contained := range rules[color] { |
| 77 | + if contained.color == target { |
| 78 | + return true |
| 79 | + } |
| 80 | + |
| 81 | + if contains(rules, contained.color, target) { |
| 82 | + return true |
| 83 | + } |
| 84 | + } |
| 85 | + return false |
| 86 | +} |
| 87 | + |
| 88 | +// what's the total cost of 'color'? |
| 89 | +func colorCost(rules map[string][]pair, color string) int { |
| 90 | + // myself |
| 91 | + cost := 1 |
| 92 | + |
| 93 | + for _, contained := range rules[color] { |
| 94 | + // + the cost of each of my bags |
| 95 | + cost += contained.amount * colorCost(rules, contained.color) |
| 96 | + } |
| 97 | + |
| 98 | + return cost |
| 99 | +} |
0 commit comments