#!/usr/bin/env tclsh9.0 proc input {} { global towels patterns cache gets stdin line set towels [split [string map {{ } {}} $line] ,] set patterns [list] while {[gets stdin line] >= 0} { if {$line eq ""} continue lappend patterns $line } set cache [dict create] } proc show {} { global towels patterns puts "Towels: [join $towels { }]" puts "" puts [join $patterns \n] } proc find {pattern start} { global towels global cache if {$start eq $pattern} {return 1} set need [string range $pattern [string length $start] end] if {[dict exists $cache $need]} { return [dict get $cache $need] } set count 0 foreach t $towels { if {[string match $t* $need]} { # puts " recurse with $t" incr count [find $pattern $start$t] } } dict set cache $need $count return $count } proc count {} { global patterns set total 0 foreach p $patterns { # puts -nonewline .; flush stdout # puts "seeking $p" set n [find $p ""] # puts "$n $p" incr total $n } # puts "" puts $total } input # show count