]> fbox.kageds.com Git - adventofcode.git/blob - 2023/go/day02/day02.go
day06
[adventofcode.git] / 2023 / go / day02 / day02.go
1 package day02
2
3 import (
4 "fmt"
5 "regexp"
6 _ "strconv"
7 "strings"
8
9 "adventofcode2023/utils"
10 )
11
12 type Set struct {
13 Red int
14 Blue int
15 Green int
16 }
17
18 type Game struct {
19 ID int
20 Sets []Set
21 }
22
23 func Part1(input string) int {
24 sum := 0
25 games := []Game{}
26
27 lines := strings.Split(input, "\n")
28 for _, line := range lines {
29 game, err := parseGame(line)
30 if err != nil {
31 fmt.Println("Error:", err)
32 return -1
33 }
34 // Print the parsed Game struct
35 fmt.Printf("Parsed Game: %+v\n", game)
36 games = append(games, game)
37 }
38 for _, game := range games {
39 result := true
40 for _, set := range game.Sets {
41 if set.Red > 12 || set.Green > 13 || set.Blue > 14 {
42 result = false
43 }
44 }
45 if result == true {
46 sum += game.ID
47 }
48 }
49 return sum
50 }
51
52 func Part2(input string) int {
53 sum := 0
54 games := []Game{}
55
56 lines := strings.Split(input, "\n")
57 for _, line := range lines {
58 game, err := parseGame(line)
59 if err != nil {
60 fmt.Println("Error:", err)
61 return -1
62 }
63 // Print the parsed Game struct
64 fmt.Printf("Parsed Game: %+v\n", game)
65 games = append(games, game)
66 }
67 for _, game := range games {
68 maxRed := 0
69 maxBlue := 0
70 maxGreen := 0
71 for _, set := range game.Sets {
72 if set.Red > maxRed {
73 maxRed = set.Red
74 }
75 if set.Blue > maxBlue {
76 maxBlue = set.Blue
77 }
78 if set.Green > maxGreen {
79 maxGreen = set.Green
80 }
81 }
82 sum += maxRed * maxBlue * maxGreen
83 }
84 return sum
85 }
86
87 func parseGame(input string) (Game, error) {
88 var game Game
89
90 // Extract ID
91 reID := regexp.MustCompile(`Game (\d+):(.*)`)
92 matchID := reID.FindStringSubmatch(input)
93 if len(matchID) != 3 {
94 return game, fmt.Errorf("unable to extract game ID")
95 }
96 game.ID = utils.MustAtoi(matchID[1])
97 setsString := strings.Split(matchID[2], ";")
98 for _, setString := range setsString {
99 var set Set
100 // Extract colors and quantities
101 reColors := regexp.MustCompile(`(\d+) (\w+)`)
102 matches := reColors.FindAllStringSubmatch(setString, -1)
103 for _, match := range matches {
104 color := strings.ToLower(match[2])
105 switch color {
106 case "red":
107 set.Red = utils.MustAtoi(match[1])
108 case "blue":
109 set.Blue = utils.MustAtoi(match[1])
110 case "green":
111 set.Green = utils.MustAtoi(match[1])
112 default:
113 return game, fmt.Errorf("unknown color: %s", color)
114 }
115 }
116 game.Sets = append(game.Sets, set)
117 }
118 return game, nil
119 }