12
4
Input:
A three digit number
- from stdin or as an argument
- not all digits are the same
- may start with one or two zero's
Process
Order the input-digits ascending and descending to form two new numbers. Subtract the smallest from the largest. Use the difference as new input. NB: This process needs 3 digits, so 10 has to be returned, or taken care of, as 010.
Repeat this process (Kaprekar transformation) until you hit 495.
Output:
The number of steps it took to reach 495.
Example:
Input: 211
211 – 112 = 099
990 – 099 = 891 (rather than 99 - 99 = 0)
981 – 189 = 792
972 – 279 = 693
963 – 369 = 594
954 − 459 = 495
Output: 6
1@MartinBüttner how is this question about three-digit numbers a duplicate of the four-digit version? – Paŭlo Ebermann – 2016-02-09T22:25:56.250
May I assume, that the input doesn't consists of three identical digits like in 111 or 222? – FUZxxl – 2011-03-05T12:33:56.840
Yes (second bullet: not all digits are the same). – steenslag – 2011-03-05T13:06:04.800
1
Complete set of test cases: http://svn.lando.us/joey/Public/SO/CG1255/testcases.txt
– Joey – 2011-03-05T19:36:26.150Warning: in some programming languages (e.g. JavaScript), numbers starting with zeros (e.g.
077
) are parsed as octals if you're not careful. – Joey Adams – 2011-03-06T03:06:45.003I realize this question might come in a bit late in the game, but... what are we expected to return for 495 itself? 0, 1, any? – J B – 2011-03-07T21:10:53.587
@J B Joey's test set has it as 0; I think he's right. – steenslag – 2011-03-07T21:27:55.427
@JB: I interpreted »the number of steps it took to reach 495« in that way that if you start with 495 you are already there without executing the algorithm. Might be debatable but arguably it makes the task more interesting since you have to handle one special case. – Joey – 2011-03-08T12:56:19.540
@Joey: well it's only a special case for the pattern lookup family of algorithms ;) But originally that's precisely why I asked, seing many "495"s pop up in the answers. I'd go for 0 spontaneously myself as well. – J B – 2011-03-08T13:38:41.203
Even more interesting question is - why does it always converge to 495? – Tomas – 2013-08-09T17:22:34.920
steenslag: Again, I do appreciate the accepted answer, but I consider it ill-placed. Since this is a code golf there exists an objective measure of a winning answer and that should be the accepted one. I cannot move the checkmark, though. – Joey – 2011-03-11T16:30:53.240
@Joey: OK. it's gone to the Golfscript solution. – steenslag – 2011-03-11T17:11:11.303
I looked at the description and at the wikipedia page, what happens if its a negative number? Input:
123
gives123-321=-198
Will the next step simply be198-891
? – Teun Pronk – 2014-02-03T10:48:35.140@TeunPronk "subtract the smallest from the largest", so no negative numbers. – steenslag – 2014-02-03T13:20:36.250