advent_of_code/2023/02/cubes.go

102 lines
1.9 KiB
Go
Raw Normal View History

2023-12-02 07:41:55 +00:00
package main
import (
"fmt"
"strconv"
"strings"
)
type Cube int
const (
RED Cube = iota
BLUE
GREEN
)
type CubeCount struct {
color Cube
count uint64
}
type Game struct {
id uint64
sets [][]CubeCount
maxRed uint64
maxBlue uint64
maxGreen uint64
}
func parseColor(color string) Cube {
if color == "red" {
return RED
}
if color == "green" {
return GREEN
}
return BLUE
}
func (g *Game) parseGame(input string) error {
initialSplit := strings.Split(input, ":")
setSplit := strings.Split(initialSplit[1], ";")
idString := initialSplit[0][5:]
var err error
g.id, err = strconv.ParseUint(idString, 10, 64)
if err != nil {
return err
}
for _, set := range setSplit {
cubes := strings.Split(set, ",")
var parsedSet []CubeCount
for _, cube := range cubes {
var count uint64
var color string
fmt.Sscanf(strings.TrimSpace(cube), "%d %s", &count, &color)
parsedSet = append(parsedSet, CubeCount{parseColor(color), count})
}
g.sets = append(g.sets, parsedSet)
}
g.maxBlue = 0
g.maxGreen = 0
g.maxRed = 0
return nil
}
func (g *Game) resolveGame() {
for _, set := range g.sets {
for _, cubeCount := range set {
if cubeCount.color == RED && cubeCount.count > g.maxRed {
g.maxRed = cubeCount.count
} else if cubeCount.color == GREEN && cubeCount.count > g.maxGreen {
g.maxGreen = cubeCount.count
} else if cubeCount.color == BLUE && cubeCount.count > g.maxBlue {
g.maxBlue = cubeCount.count
}
}
}
}
func (g *Game) canBePlayed(cubeSet [3]CubeCount) bool {
for _, cubeCount := range cubeSet {
if cubeCount.color == RED && cubeCount.count < g.maxRed {
return false
}
if cubeCount.color == GREEN && cubeCount.count < g.maxGreen {
return false
}
if cubeCount.color == BLUE && cubeCount.count < g.maxBlue {
return false
}
}
return true
}
func (g *Game) getGamePower() uint64 {
return g.maxBlue * g.maxGreen * g.maxRed
}