day 4 tcl solution

main
magical 2023-12-06 01:11:46 -08:00
parent 0fb7b77afe
commit f58ed8eb97
1 changed files with 28 additions and 0 deletions

28
day04/sol.tcl 100755
View File

@ -0,0 +1,28 @@
#!/usr/bin/env tclsh
source ../prelude.tcl
package require struct::set
set input stdin
set part1 0
while {[gets $input line] >= 0} {
regexp {^Card +(\d+): ([\d ]*) \| ([\d ]*)$} $line _ card winners numbers
set matches [struct::set intersect $winners $numbers]
set score [expr {1 << [llength $matches] >> 1}]
incr part1 $score
incr copies($card)
for {set i 0} {$i < [llength $matches]} {incr i} {
incr copies([expr {$card+$i+1}]) $copies($card)
}
}
puts "-"
puts $part1
foreach {c n} [array get copies] {
if {$c > $card} {
error "should not have any copies of card $c > $card"
}
}
set part2 [ladd [lmap {card n} [array get copies] {list $n}]]
puts $part2