advent-of-code

Perserverance, or the lack thereof

git clone git://git.shimmy1996.com/advent-of-code.git

main.go (1644B)

    1 package main
    2 
    3 import (
    4 	"bufio"
    5 	"fmt"
    6 	"os"
    7 	"regexp"
    8 	"strconv"
    9 	"strings"
   10 )
   11 
   12 func readInput(filename string) (in_out, out_in map[string]map[string]int) {
   13 	file, _ := os.Open(filename)
   14 	defer file.Close()
   15 
   16 	in_out = make(map[string]map[string]int)
   17 	out_in = make(map[string]map[string]int)
   18 	inner_matcher := regexp.MustCompile(`([0-9]+) (\w+ \w+) bags?[\.,]`)
   19 	scanner := bufio.NewScanner(file)
   20 	for scanner.Scan() {
   21 		rule := strings.Split(scanner.Text(), " bags contain ")
   22 		inner_match := inner_matcher.FindAllStringSubmatch(rule[1], -1)
   23 		for _, inner := range inner_match {
   24 			count, _ := strconv.Atoi(inner[1])
   25 			if out_in[rule[0]] == nil {
   26 				out_in[rule[0]] = make(map[string]int)
   27 			}
   28 			out_in[rule[0]][inner[2]] = count
   29 			if in_out[inner[2]] == nil {
   30 				in_out[inner[2]] = make(map[string]int)
   31 			}
   32 			in_out[inner[2]][rule[0]] = count
   33 		}
   34 	}
   35 	return
   36 }
   37 
   38 func main() {
   39 	in_out, out_in := readInput("./input.txt")
   40 	// 348
   41 	fmt.Println(part1(in_out))
   42 	// 18885
   43 	fmt.Println(part2(out_in))
   44 }
   45 
   46 func part1(input map[string]map[string]int) int {
   47 	contain_colors := make(map[string]bool)
   48 	queue := []string{"shiny gold"}
   49 	for len(queue) > 0 {
   50 		curr := queue[0]
   51 		queue = queue[1:]
   52 		for k, _ := range input[curr] {
   53 			queue = append(queue, k)
   54 			contain_colors[k] = true
   55 		}
   56 	}
   57 	return len(contain_colors)
   58 }
   59 
   60 func part2(input map[string]map[string]int) (count_tot int) {
   61 	queue := []string{"shiny gold"}
   62 	count := []int{1}
   63 	for len(queue) > 0 {
   64 		for k, v := range input[queue[0]] {
   65 			queue = append(queue, k)
   66 			count = append(count, count[0]*v)
   67 			count_tot += count[0] * v
   68 		}
   69 		queue = queue[1:]
   70 		count = count[1:]
   71 	}
   72 	return
   73 }