-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday_two.go
More file actions
86 lines (74 loc) · 1.62 KB
/
day_two.go
File metadata and controls
86 lines (74 loc) · 1.62 KB
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
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"strconv"
)
func main() {
power, total := 0, 0
f, err := os.Open("day_two.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
games := make(map[string][]map[string]int)
for scanner.Scan() {
line := strings.Split(scanner.Text(), ":")
key := strings.TrimSpace(line[0])
colorBallsPairs := strings.Split(line[1], ";")
var colorBallsMaps []map[string]int
for _, pair := range colorBallsPairs {
values := strings.Split(pair, ",")
colorBallsMap := make(map[string]int)
for _, value := range values {
parts := strings.Split(strings.TrimSpace(value), " ")
color := parts[1]
numBalls, err := strconv.Atoi(parts[0])
if err != nil {
log.Fatal(err)
}
colorBallsMap[color] = numBalls
}
colorBallsMaps = append(colorBallsMaps, colorBallsMap)
}
games[key] = colorBallsMaps
}
for gameno, subgames := range games {
isvalid := true
for _, colors := range subgames {
if colors["red"] > 12 || colors["green"] > 13 || colors["blue"] > 14 {
isvalid = false
break
}
}
if isvalid {
gameNumber, err := strconv.Atoi(strings.Split(gameno, " ")[1])
if err != nil {
log.Fatal(err)
}
total += gameNumber
}
}
fmt.Println("total : ", total)
// Part 2
for _, subgames := range games {
r, g, b := 0, 0, 0
for _, colors := range subgames {
if colors["red"] > r {
r = colors["red"]
}
if colors["green"] > g {
g = colors["green"]
}
if colors["blue"] > b {
b = colors["blue"]
}
}
power += r * g * b
}
fmt.Println("total : ", power)
}