#!/usr/bin/env tclsh9.0 proc score {line} { global rules # Scan the list of pages left to right. Keep track of what's been printed. # A violation occurs if we try to print a page which has a rule pointing # to an already-printed page. set printed [list] foreach curr $line { foreach prev $printed { set key "$curr|$prev" if {[dict exists $rules $key]} {return 0} } lappend printed $curr } # If we make it here, the update is OK, so return the middle page number. set n [llength $line] return [lindex $line [expr {($n - 1) / 2}]] } # No point splitting these rules. Just store them as read. set rules [dict create] while {[gets stdin line] >= 0} { if {$line eq ""} break dict set rules $line 1 } set total 0 while {[gets stdin line] >= 0} { if {$line eq ""} continue incr total [score [split $line ,]] } puts $total