mirror of
https://github.com/onyx-and-iris/aoc2023.git
synced 2024-11-24 19:30:48 +00:00
65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
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
|
|
}
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|