package main import ( "regexp" "strconv" "strings" ) var regex = map[string]*regexp.Regexp{ "red": regexp.MustCompile(`(?P\d+) red`), "green": regexp.MustCompile(`(?P\d+) green`), "blue": regexp.MustCompile(`(?P\d+) blue`), "game": regexp.MustCompile(`Game (?P\d+)`), } var limits = map[string]int{ "red": 12, "green": 13, "blue": 14, } // isValidGame calculates if a game was possible based on the limits of each cube colour func isValidGame(data string) (bool, error) { for _, colour := range []string{"red", "green", "blue"} { m := regex[colour].FindAllStringSubmatch(data, -1) for _, s := range m { n, err := strconv.Atoi(s[1]) if err != nil { return false, err } if n > limits[colour] { return false, nil } } } return true, nil } // one returns the sum of ids for all games that were possible func one(lines []string) (int, error) { sum := 0 for _, line := range lines { identifier, data := func() (string, string) { x := strings.Split(line, ":") return x[0], x[1] }() isValidGame, err := isValidGame(data) if err != nil { return 0, err } if isValidGame { id, err := getIdForGame(identifier) if err != nil { return 0, err } sum += id } } return sum, nil }