aoc2023/day-2/one.go

65 lines
1.3 KiB
Go
Raw Normal View History

2023-12-02 20:13:42 +00:00
package main
import (
"regexp"
"strconv"
"strings"
)
var regex = map[string]*regexp.Regexp{
"red": regexp.MustCompile(`(?P<red>\d+) red`),
"green": regexp.MustCompile(`(?P<green>\d+) green`),
"blue": regexp.MustCompile(`(?P<blue>\d+) blue`),
"game": regexp.MustCompile(`Game (?P<game>\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
2023-12-02 20:13:42 +00:00
}
}
}
return true, nil
2023-12-02 20:13:42 +00:00
}
// 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
}