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 – 10 years ago
May I assume, that the input doesn't consists of three identical digits like in 111 or 222? – FUZxxl – 15 years ago
Yes (second bullet: not all digits are the same). – steenslag – 15 years ago
1
Complete set of test cases: http://svn.lando.us/joey/Public/SO/CG1255/testcases.txt
– Joey – 15 years agoWarning: 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 – 15 years agoI 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 – 15 years ago
@J B Joey's test set has it as 0; I think he's right. – steenslag – 15 years ago
@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 – 15 years ago
@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 – 15 years ago
Even more interesting question is - why does it always converge to 495? – Tomas – 12 years ago
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 – 15 years ago
@Joey: OK. it's gone to the Golfscript solution. – steenslag – 15 years ago
I looked at the description and at the wikipedia page, what happens if its a negative number? Input:
123gives123-321=-198Will the next step simply be198-891? – Teun Pronk – 12 years ago@TeunPronk "subtract the smallest from the largest", so no negative numbers. – steenslag – 12 years ago