#!/usr/bin/env tclsh8.6 gets stdin polymer gets stdin line while {[gets stdin line] >= 0} { if {[scan $line {%2s -> %1s} pair ins] != 2} continue set rule($pair) \ [list "[string index $pair 0]$ins" "$ins[string index $pair 1]"] } for {set i 0} {$i <= [string length $polymer] - 2} {incr i} { set i1 [expr {$i + 1}] incr count([string range $polymer $i $i1]) } for {set step 1} {$step <= 40} {incr step} { array unset delta foreach pair [array names count] { lassign $rule($pair) a b incr delta($a) $count($pair) incr delta($b) $count($pair) incr delta($pair) -$count($pair) } foreach pair [array names delta] { incr count($pair) $delta($pair) } switch -- $step 10 - 40 { array unset cc set cc([string index $polymer 0]) 1 foreach {pair n} [array get count] { incr cc([string index $pair 1]) $n } set tmp {} foreach c [array names cc] {lappend tmp $cc($c)} set tmp [lsort -integer $tmp] puts "$step: [expr {[lindex $tmp end] - [lindex $tmp 0]}]" } }