| Bytes | Lang | Time | Link |
|---|---|---|---|
| 037 | Vyxal j | 240525T171426Z | pacman25 |
| nan | Perl 5 | 240524T224602Z | Xcali |
| 156 | AWK | 240524T194313Z | C K |
| nan | Mathematica | 140112T203050Z | Chris De |
| 105 | Perl 6 n flag | 190322T031622Z | Jo King |
| 375 | Rust | 190322T022400Z | don brig |
| 160 | PHP | 190321T171607Z | 640KB |
| 122 | Ruby 1.9 | 110607T104013Z | Ventero |
| 104 | K | 121017T112001Z | tmartin |
| 179 | Ruby | 110702T200953Z | Joaquim |
| 152 | GAWK | 110623T154017Z | Dan Andr |
| 276 | Scala | 110608T124523Z | Lalith |
| 126 | Perl | 110607T052333Z | swilliam |
| nan | Haskell | 110609T165451Z | hammar |
| nan | JavaScript | 110610T084142Z | Casey Ch |
| 225 | CoffeeScript | 110616T114722Z | Jonas El |
| nan | PHP | 110614T205915Z | rintaun |
| nan | 110614T173846Z | Aman Zee | |
| 194 | Scala 2.9 | 110608T180504Z | Gareth |
| 308 | ><> | 110610T170148Z | swilliam |
| 125 | PowerShell | 110610T092939Z | Joey |
| 074 | Golfscript | 110610T100121Z | Ventero |
| 256 | Clojure | 110608T140122Z | kotarak |
| 141 | Python | 110607T202510Z | Martin U |
| 260 | JavaScript | 110607T091246Z | pimvdb |
Vyxal j, 296 bitsv2, 37 bytes
λtSsṘ⌊Ḃ~εWvS4∆Z‛-=Y;İ⁽tεvṄ₅`Itḟ¨₌ǎ: %.`%J
Bitstring:
00000011100011110100101010111100101011001100111001001111010100010110111100001101011110110100010101111111001110011011010001010010011111100001101011011001001000011111110000001100101001110111001000000010011010010111000111010101110111001001000111010010011000111101011111011011000101000101001111110100
Perl 5, 105 + 1 (-n) = 106 bytes
$c=reverse$d=join'',sort/./g;$t+=say"$c - $d = ",$_=sprintf'%04d',$c-$d;/6174/||redo;say"Iterations: $t."
AWK, 156 bytes
{x=$1;do{j++;split(x,a,"");asort(a);x=a[4]a[3]a[2]a[1];y=a[1]a[2]a[3]a[4];z=x-y;if(z<1e3)z=0z;print x" - "y" = "(x=z)}while(x!=6174)print"Iterations: "j"."}
Mathematica, 314 291 characters
This is the program, kaprekar.m :-
SetOptions[$Output,FormatType->OutputForm];
x=$ScriptCommandLine[[2]];
f[x_]:=(a=Characters@x;
b=Sort@ToExpression@a;
c=Sort[FromDigits/@{#,Reverse@#}&@b];
{c,{b,a}}=IntegerString[{#2-#&@@c,c},10,4];
Print[a," - ",b," = ",c];c)
x=f@x;
e=NestWhileList[f,x,#!="6174"&];
Print["Iterations: ",N@Length@e]
Setting the path prior to running :-
$ PATH=${PATH}:/Applications/Mathematica.app/Contents/MacOS ; export PATH
Running the program :-
$ MathematicaScript -script kaprekar.m 2607
7620 - 0267 = 7353
7533 - 3357 = 4176
7641 - 1467 = 6174
Iterations: 3.
$ MathematicaScript -script kaprekar.m 1211
2111 - 1112 = 0999
9990 - 0999 = 8991
9981 - 1899 = 8082
8820 - 0288 = 8532
8532 - 2358 = 6174
Iterations: 5.
$ MathematicaScript -script kaprekar.m 6174
7641 - 1467 = 6174
Iterations: 1.
Perl 6 -n flag, 105 bytes
say "Iterations: "~+.&{{{say $!=.flip~" - $_"," = ",($/=$!.EVAL.fmt("%04d"));$/}([~] .comb.sort)}...6174}
I finally got to use my {}...* trick, since we need to have at least one iteration for 6174. I'm not sure why I need the extra wrapping .&{ } around the sequence though, which kinda sucks.
Explanation:
.&{ } # Call a function on the input
{ }...6174 # Create a sequence that goes until 6174
{ }([~] .comb.sort) # Get the sorted digits of the number
say $!=.flip~" - $_"," = "~($/=$!.EVAL.fmt("%04d")) # Print the iteration
;$/ # Return the result
say "Iterations: "~+.&{ } # Print the number of iterations
Rust - 375 bytes
use std::io::{self,BufRead};fn main() {let mut x=io::stdin().lock().lines().next().unwrap().unwrap().parse::<i16>().unwrap();let mut n=0;println!("Iterations: {}.",loop {let mut v=[x/1000%10,x/100%10,x/10%10,x%10];v.sort();let j=v.iter().fold(0,|a,i|a*10+i);let k=v.iter().rev().fold(0,|a,i|a*10+i);x=k-j;n+=1;println!("{:04} - {:04} = {:04}",k,j,x);if x==6174{break n};});}
I present this as a possible "upper bound", I challenge anyone to find a language where a reasonable implementation of this is longer - as in there is nothing superfluous, but also nothing even remotely obvious that would shrink it significantly. The thing about Rust is that it takes about 120 characters just to read from stdin and parse into an integer. "Oh but then just use the string representation"... but im 99% confident that would be even longer
PHP, 160 bytes
function k($n,$d=1){$o=str_split($n);sort($o);echo$q=strrev($r=join($o))," - $r = ",$n=str_pad($q-$r,4,0,0),"
",$n==6174?"Iterations: $d.":k($n,++$d);}k($argn);
Complete program, input is STDIN, run with php -nF.
Output
> echo 2607|php -nF kap.php
7620 - 0267 = 7353
7533 - 3357 = 4176
7641 - 1467 = 6174
Iterations: 3.
> echo 1211|php -nF kap.php
2111 - 1112 = 0999
9990 - 0999 = 8991
9981 - 1899 = 8082
8820 - 0288 = 8532
8532 - 2358 = 6174
Iterations: 5.
> echo 6174|php -nF kap.php
7641 - 1467 = 6174
Iterations: 1.
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).
K, 104
{b::();{b,:,k," = ",r:"0"^(-:4)$$. k:(x@>x)," - ",x@<x;r}\[$x];-1'c,,"Iterations: ",$#c:$[1=#b;b;-1_b];}
Test cases
k){b::();{b,:,k," = ",r:"0"^(-:4)$$. k:(x@>x)," - ",x@<x;r}\[$x];-1'c,,"Iterations: ",$#c:$[1=#b;b;-1_b];}'2607 1211 6174;
7620 - 0267 = 7353
7533 - 3357 = 4176
7641 - 1467 = 6174
Iterations: 3
2111 - 1112 = 0999
9990 - 0999 = 8991
9981 - 1899 = 8082
8820 - 0288 = 8532
8532 - 2358 = 6174
Iterations: 5
7641 - 1467 = 6174
Iterations: 1
Ruby, 179 chars but posting anyway
s=gets.chomp
n=0
begin
s=s.to_s.chars.sort.reduce{|s,c|s+c}.rjust(4,'0')
a=s.reverse
puts"#{a} - #{s} = #{'%04d'%(s=a.to_i-s.to_i)}"
n+=1
end while s!=6174
puts"Iterations: #{n}."
GAWK - 152 chars
This is a GNU awk version. It may not work with other non-gnu versions.
{for(z=$1;z-6174+!c;++k){split(z,a,"");asort(a);for(b=c=i=0;i<4;z=c-b){c+=a[i+1]*10^i;b=b*10+a[++i]}printf c" - %.4d = "z"\n",b}print"Iterations: "k"."}
$ awk -f k.awk <<< 9992
2999 - 9992 = 6993
3699 - 9963 = 6264
2466 - 6642 = 4176
1467 - 7641 = 6174
Iterations: 4
Scala 276
object o{var i=0;def a(v:String){val c=v.toList.sortWith(_>_).mkString;val b=c.reverse;val d=c.toInt-b.toInt;val e="0"*(4-(d+"").length)+d;val p=c+" - "+b+" = "+e;if(d!=6174){println(p);i=i+1;a(e)}else{println(p+"\nIterations: "+(i+1)+".")}};def main(s:Array[String])=a(s(0))}
Scala 283
object o{var i=0;def a(v:String){val c=v.toList.sortWith(_>_).mkString;val b=c.reverse;val d=c.toInt-b.toInt;val e="0"*(4-(d+"").length)+d;val p=c+" - "+b+" = "+e;if(d!=6174){println(p);i=i+1;a(e)}else{println(p);println("Iterations: "+(i+1)+".")}};def main(s:Array[String])=a(s(0))}
diff:
else{println(p);println("Iterations: "+(i+1)+".")}};
// to
else{println(p+"\nIterations: "+(i+1)+".")}};
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
Haskell, 197 192 182 181 characters
import List
p=putStrLn.unwords
"6174"%k|k>0=p["Iterations:",shows k"."]
n%k=p[b,"-",a,"=",c]>>c%(k+1)where a=sort n;b=reverse a;c=take 4$shows(read b-read a)"0"
main=getLine>>=(%0)
JavaScript, 189 182 165 chars
Credit to DocMax:
for(n=prompt(i=o=e='');!i--|n-6174;o+=n+' - '+a+' = '+(n=(p=n-a+e)[3]?p:0+p)+'\n')
b=n.split(e).sort(),n=b.reverse(a=b.join(e)).join(e);
alert(o+"Iterations: "+~i+'.')
Original:
for(n=prompt(i=o=e='');n-6174;o+=(i++?n+"\n":e)+(n=(a=n.split(e).sort().join(e)).split(e).reverse().join(e))+' - '+a+' = ',n=n-a+e)while(!n[3])n=0+n
alert(o+n+"\nIterations: "+i+'.')
Ungolfed:
var i = 0;
var n = prompt();
var out = '';
while (n != 6174) {
while ((n=''+n).length<4) n='0'+n // pad number
if(i)out+=n+"\n"
a = n.split('').sort().join('');
n = a.split('').reverse().join('');
out += n + ' - ' + a + ' = '
n-=a
i++;
}
console.log(out + "6174\nIterations: " + i + '.');
CoffeeScript, 233 225 characters
o=e='';i=0;n=prompt()
while n!=6174
n=e+n;q=(n='0'+n if !n[3]) for x in [0..2];n?=q;o+=n+"\n" if i;a=n.split(e).sort().join(e);n=a.split(e).reverse().join(e);o+=n+' - '+a+' = ';n-=a;i++
alert(o+"6174\nIterations: "+i+'.')
PHP, 215 259 276 characters
<?php echo">";$n=str_split(str_pad(trim(fgets(STDIN)),4,0,0));for($k=0,$z=0;$k-6174;$z++){sort($n);$a=implode($n);$b=strrev($a);$k=str_pad($b-$a,4,0,0);echo"$b - $a = $k\n";$n=str_split($k);}echo"Iterations: $z\n";
Ungolfed:
<?php
echo ">";
$n = str_split(str_pad(trim(fgets(STDIN)),4,0,0));
for($k=0, $z=0; $k-6174; $z++) {
sort($n);
$a = implode($n);
$b = strrev($a);
$k = str_pad($b-$a,4,0,0);
echo "$b - $a = $k\n";
$n = str_split($k);
}
echo "Iterations: $z\n";
PERL
chomp($n=<STDIN>);
do{
$t++;
$desc=join('',reverse sort split(//,$n));
$asc=join('', sort split(//,$n));
$n=($desc - $asc);
for($i=4;$i>length $n;$i--){
$n="0".$n;
}
print $desc." - ".$asc." = ".$n."\n";
$n="6174" if $n eq "0000";
}while($n ne "6174");
print "Iterations: $t.\n";
Scala 2.9, 194 characters
object K extends App{var(c,s)=(0,args(0));do{var d=s.sorted;var e=d.reverse.toInt-d.toInt;s="%04d".format(e);println(d.reverse+" - "+d+" = "+s);c+=1}while(s!="6174");print("Iterations: "+c+".")}
Makes use of the App trait from Scala 2.9.
Edit: gives correct output for initial input of 6174.
><> - 268 308
</&4pff1
v>i86*-:n&1-:&?!
>ao& v
<v&0pff+1gff
>&1+:4= ?v&:a%:}-a,
v&8[4r::0}~<
>&1-:?!v&:@@:@(?$}&:&3%1=?}
v >~:}}:}@:}$:}
\:n}:n}:n}:n}' - 'ooo:n}:n}:n}:n}' = 'ooo
\a*+a*+a*+}a*+a*+a*+-:0&\
v? =4&:+1&,a-}:%a:<
/\&~~rnnnnao:29777****= ?v
voooooooooooo"Iterations: "/
\ffgna'.'oo;
Not much of a contender for golf, but it was fun to write. :)
Run with
./fish.py kaprekar.fish -v <number>
EDIT: Now takes input from STDIN.
PowerShell, 125 128 130 131
for($a,$OFS=$input+'';$b-6174;++$i){$a=$b=+($c=''+($x="$a 000"[0..4]|sort)[4..0])-"$x"
"$c-$x = {0:d4}"-f$a}"Iterations: $i."
Passes all test cases from the question.
Golfscript, 74 characters
);:|;{0):0;|$:§-1%" - "§" = ""0"4$~§~-+-4>:|n|6174`=!}do"Iterations: "0"."
Clojure, 256 characters
(let[i #(Integer/parseInt%)f #(format"%04d"%)a #(->>% f sort(apply str)i)d #(->>% f sort reverse(apply str)i)k #(let[u(d %)l(a %)n(- u l)](println(f u)"-"(f l)"="(f n))n)](while true(println"Iterations:"(count(take-while #(not=% 6174)(iterate k(read)))))))
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
JavaScript, 260 bytes
function z(c){for(u=c+y;u.length<4;)u=0+u;return u}for(p=prompt(i=0,r=y="");;)
if(s=(p+y).split(y).sort(),t=s.concat().reverse(),a=s.join(y),b=t.join(y),q=a<b?b:a,
w=a<b?a:b,p=z(q-w),i++,r+=z(q)+" - "+z(w)+" = "+p+"\n",p==6174)break;alert(r+
"Iterations: "+i+".")