perlmeditation
srawls
We haven't had a golf in a while, so here it goes:
<p>
The problem is to write a perl golf (a solution in the fewest characters) to solve Kaprekar's Process. Kaprekar's Process basically states: "Take any number and arrange its digits in descending order and in ascending order and subtract. Repeat with the result. Ad Infinitum." Eventually, all 3 digit numbers (except when all digits are the same, like 333) will end up as 495. This is called Kaprekar's Constant. The program will return the number of steps it takes to get to 495.
<p>
Here is an example series:<p>
<pre>
Input: 213
1: 321 - 123 = 198
2: 981 - 189 = 792
3: 972 - 279 = 693
4: 963 - 369 = 594
5: 954 - 459 = 495
</pre>
<p>
<b>Input:</b>
<p>
Your subrutine will recieve a 3 digit number; you may assume it is positive and that all the digits are not the same (i.e. you do not have to worry about error handling).
<p>
<b>Output:</b>
<p>
The return value will merely be the number of steps it took to reach 495; in the example above, it was 5. Here are a few sample calls: (assume sub name is a, it really doesn't matter what you name yours though)
<p>
<pre>
print a(213) #prints 5
print a(258) #prints 2
</pre>
<p>
Here is my attempt, weighing in at a bloated 60 chars:
<code>
sub a {
return$i if$_[0]==495;
$a=join'',sort{$a<=>$b}split//,pop;
$i++;
a((reverse$a)-$a)
}
</code>
<p>
P.S. If it is still unclear to you, visit <a href="http://www.gecdsb.on.ca/d&g/nov98/web2.htm">this website</a> and look for Kaprekar's Process on it.
<p>The 15 year old, freshman programmer,<BR>
Stephen Rawls