summaryrefslogtreecommitdiff
path: root/go/2023/internal/day_02/part_02/part_02.go
blob: ffb96911a798810cfd83bcf48812fe53847a1cf4 (plain)
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
package part_02

import (
	"os"
	"regexp"
	"strconv"
	"strings"
)

type cubes struct {
	red   int
	blue  int
	green int
}

func Solve() {
	contents, err := os.ReadFile("../_input/day_02.txt")
	if err != nil {
		panic(err)
	}

	lines := strings.Split(string(contents), "\n")
	answer := processLines(lines)

	println(answer)
}

func processLines(lines []string) int {
	var answer int

	for _, line := range lines {
		if line == "" || line == "\n" {
			continue
		}

		shownCubes := convertLineToCubes(line)

		maxCubes := getMaximumCubes(shownCubes)
		power := getPower(maxCubes)
		answer += power
	}

	return answer
}

func convertLineToCubes(line string) []cubes {
	var shownCubes []cubes

	redRegex := regexp.MustCompile(`(\d+) red`)
	blueRegex := regexp.MustCompile(`(\d+) blue`)
	greenRegex := regexp.MustCompile(`(\d+) green`)

	for _, round := range strings.Split(line, ";") {
		var cubes cubes

		redMatches := redRegex.FindStringSubmatch(round)
		if redMatches != nil {
			red, err := strconv.Atoi(redMatches[1])
			if err != nil {
				panic("Could not convert red to int: " + redMatches[1])
			} else {
				cubes.red = red
			}
		}

		blueMatches := blueRegex.FindStringSubmatch(round)
		if blueMatches != nil {
			blue, err := strconv.Atoi(blueMatches[1])
			if err != nil {
				panic("Could not convert green to int: " + blueMatches[1])
			} else {
				cubes.blue = blue
			}
		}

		greenMatches := greenRegex.FindStringSubmatch(round)
		if greenMatches != nil {
			green, err := strconv.Atoi(greenMatches[1])
			if err != nil {
				panic("Could not convert green to int: " + greenMatches[1])
			} else {
				cubes.green = green
			}
		}

		shownCubes = append(shownCubes, cubes)
	}

	return shownCubes
}

func getMaximumCubes(shownCubes []cubes) cubes {
	var maxCubes cubes

	for _, cubes := range shownCubes {
		if cubes.red > maxCubes.red {
			maxCubes.red = cubes.red
		}

		if cubes.blue > maxCubes.blue {
			maxCubes.blue = cubes.blue
		}

		if cubes.green > maxCubes.green {
			maxCubes.green = cubes.green
		}
	}

	return maxCubes
}

func getPower(maxCubes cubes) int {
	return maxCubes.red * maxCubes.blue * maxCubes.green
}