Code Golf: 6174 - Kaprekar's mythical constant

Ruby 1.9, 122 characters

puts"Iterations: #{(1..7).find{s=$_.chars.sort*"";puts [r=s.reverse,?-,s,?=,$_="%04d"%(r.to_i-s.to_i)]*" ";~/6174/}}."

Example invocation:

$ echo 1211 | ruby -ln kaprekar.rb

I've counted the -ln flag as 4 characters (difference between the normal invocation ruby kaprekar.rb and ruby -ln kaprekar.rb).


Perl - 147 143 134 130 129 126 129 128 126

for($_=<>;$_-6174+!$c;$c++){$_=reverse$d=join'',sort split//,"$_"
|$|x4;printf"$_ - $d = %04d\n",$_-=$d}die"Iterations: $c.\n"

EDIT: Now complies with 6174 case, at the cost of a few chars... run with echo -n <number> | perl kaprekar.pl

EDIT: Finally back to where I was before :D


Python, 141 chars

n=input()
i=0
while n-6174:a=''.join(sorted("%04d"%n));b=a[::-1];n=int(b)-int(a);print"%s - %s = %04d"%(b,a,n);i+=1
print"Iterations: %d."%i