-
Notifications
You must be signed in to change notification settings - Fork 0
/
day.go
140 lines (113 loc) · 2.26 KB
/
day.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"embed"
"fmt"
"regexp"
"slices"
"strings"
"github.com/drudge/go-advent-of-code/pkg/aoc"
)
//go:embed input.txt
var inputFile embed.FS
type CubesConfig struct {
Red int
Blue int
Green int
}
type CubeSets struct {
Red []int
Blue []int
Green []int
}
func (c CubesConfig) String() string {
return fmt.Sprintf("Red: %v, Blue: %v, Green: %v", c.Red, c.Blue, c.Green)
}
type Game struct {
ID int
Sets CubeSets
}
func (g Game) String() string {
return fmt.Sprintf("Game %v: %v", g.ID, g.Sets)
}
func (g Game) GetMinPower() int {
red := slices.Max(g.Sets.Red)
blue := slices.Max(g.Sets.Blue)
green := slices.Max(g.Sets.Green)
return red * blue * green
}
func (g Game) IsPossibleWithCubes(cubes CubesConfig) bool {
for _, red := range g.Sets.Red {
if red > cubes.Red {
return false
}
}
for _, blue := range g.Sets.Blue {
if blue > cubes.Blue {
return false
}
}
for _, green := range g.Sets.Green {
if green > cubes.Green {
return false
}
}
return true
}
func parseColorSets(color string, line string) []int {
var sets []int
rolls := strings.Split(line, ";")
pattern := regexp.MustCompile(`(\d+) ` + color)
for _, roll := range rolls {
total := 0
matches := pattern.FindAllStringSubmatch(roll, -1)
if len(matches) > 0 {
for _, match := range matches {
total += aoc.ToInt(match[1])
}
}
sets = append(sets, total)
}
return sets
}
func parseGame(line string) Game {
g := Game{}
if strings.HasPrefix(line, "Game ") {
matches := regexp.MustCompile(`Game (\d+)`).FindStringSubmatch(line)
if len(matches) > 0 {
g.ID = aoc.ToInt(matches[1])
}
}
if g.ID > 0 {
g.Sets.Red = parseColorSets("red", line)
g.Sets.Blue = parseColorSets("blue", line)
g.Sets.Green = parseColorSets("green", line)
}
return g
}
func partOne(lines []string) int {
cubes := CubesConfig{
Red: 12,
Green: 13,
Blue: 14,
}
sum := 0
for _, line := range lines {
game := parseGame(line)
if game.IsPossibleWithCubes(cubes) {
sum += game.ID
}
}
return sum
}
func partTwo(lines []string) int {
sum := 0
for _, line := range lines {
game := parseGame(line)
sum += game.GetMinPower()
}
return sum
}
func main() {
lines := aoc.GetDayInput(inputFile)
aoc.RunSolution(lines, partOne, partTwo)
}