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
|
proc max {a b} {
return [expr {$a > $b ? $a : $b}]
}
set txt [read -nonewline stdin]
set lines [split $txt "\n"]
set maxes [dict create \
red 12 \
green 13 \
blue 14]
set tot 0
set notpossible 0
set part2 0
foreach line $lines {
set fields [split $line ":;"]
set stop 0
set m [dict create red 0 green 0 blue 0]
for {set i 0} {$i < [llength $fields]} {incr i} {
set words [split [lindex $fields $i] { ,}]
# first field is "Game N"
if {$i == 0} {
set game [lindex $words 1]
incr tot $game
continue
}
# All remaining fields are like " X color"
# (there is an initial space hence _)
foreach {_ n col} $words {
# Part 1
if {! $stop && $n > [dict get $maxes $col]} {
incr notpossible $game
set stop 1 ;# no need to continue with the rest of the line
}
# Part 2
dict set m $col [max [dict get $m $col] $n]
}
}
# Calculate "power"
set power 1
dict map {k v} $m {
set power [expr {$power * $v}]
}
incr part2 $power
}
puts "Part 1: [expr {$tot - $notpossible}]"
puts "Part 2: $part2"
|