Skip to content

Commit c7246ed

Browse files
feat(day02): solve part01
1 parent 01ed446 commit c7246ed

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

2023-go/day02/day02.go

+98
Original file line numberDiff line numberDiff line change
@@ -1 +1,99 @@
11
package main
2+
3+
import (
4+
"github.com/maximiliantech/advent-of-code/2022-go/common"
5+
"log"
6+
"strconv"
7+
"strings"
8+
)
9+
10+
func main() {
11+
lines := common.ReadAllLines("../2023-go/day02/input.txt")
12+
log.Println("Day 02 Part 01")
13+
partOne(lines)
14+
log.Println("Day 02 Part 02")
15+
}
16+
17+
func partOne(lines []string) {
18+
games := readGames(lines)
19+
possibleGames := countPossibleGames(games)
20+
log.Println(possibleGames)
21+
}
22+
23+
func countPossibleGames(games []game) int {
24+
possibleGames := 0
25+
for _, game := range games {
26+
if isGamePossible(game) {
27+
possibleGames += game.id
28+
}
29+
}
30+
return possibleGames
31+
}
32+
33+
func isGamePossible(game game) bool {
34+
for _, subset := range game.subsets {
35+
if subset.red > 12 || subset.green > 13 || subset.blue > 14 {
36+
return false
37+
}
38+
}
39+
return true
40+
}
41+
42+
type game struct {
43+
id int
44+
subsets []subset
45+
}
46+
47+
type subset struct {
48+
red int
49+
green int
50+
blue int
51+
}
52+
53+
func readGames(lines []string) []game {
54+
var games []game
55+
for _, line := range lines {
56+
games = append(games, readGame(line))
57+
}
58+
return games
59+
}
60+
61+
func readGame(line string) game {
62+
g := game{}
63+
s := strings.Split(line, ": ")
64+
g.id = readGameId(s[0])
65+
g.subsets = readSubsets(s[1])
66+
return g
67+
}
68+
69+
func readGameId(s string) int {
70+
s = strings.TrimPrefix(s, "Game ")
71+
n, _ := strconv.Atoi(s)
72+
return n
73+
}
74+
75+
func readSubsets(subsetsRaw string) []subset {
76+
var subsets []subset
77+
sub := strings.Split(subsetsRaw, "; ")
78+
for _, subsetRaw := range sub {
79+
subsets = append(subsets, readSubset(subsetRaw))
80+
}
81+
return subsets
82+
}
83+
84+
func readSubset(subsetRaw string) subset {
85+
subset := subset{}
86+
s := strings.Split(subsetRaw, ", ")
87+
for _, color := range s {
88+
c := strings.Split(color, " ")
89+
switch c[1] {
90+
case "red":
91+
subset.red, _ = strconv.Atoi(c[0])
92+
case "green":
93+
subset.green, _ = strconv.Atoi(c[0])
94+
case "blue":
95+
subset.blue, _ = strconv.Atoi(c[0])
96+
}
97+
}
98+
return subset
99+
}

0 commit comments

Comments
 (0)