#!/usr/bin/env tclsh8.6 gets stdin polymer gets stdin _ while {[gets stdin line] >= 0} { if {[scan $line {%2s -> %1s} pair ins] != 2} continue set rule($pair) $ins } for {set i 1} {$i <= 10} {incr i} { set new [string index $polymer 0] for {set j 0} {$j <= [string length $polymer] - 2} {incr j} { set j1 [expr {$j+1}] set pair [string range $polymer $j $j1] if {[info exists rule($pair)]} {append new $rule($pair)} append new [string index $polymer $j1] } set polymer $new } foreach c [split $polymer {}] { incr count($c) } foreach {key val} [array get count] { lappend counts $val } set counts [lsort -integer $counts] set most [lindex $counts end] set least [lindex $counts 0] puts [expr {$most - $least}]