#!ruby -pa s,_=$F gsub(/./){s[c=['I','J'].find{|c|!s[($_+s).count(c)]&&c>$&}||s.tr($&,'')[0,1]]='' c}