Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: (Golf) Kaprekar's Process

by srawls (Friar)
on Jun 16, 2001 at 23:19 UTC ( #89085=note: print w/ replies, xml ) Need Help??


in reply to (Golf) Kaprekar's Process

I've taken all the advice and improved my old one to this, 61 char solution (I counted manually this time : ). Oh, and it handles 0s in numbers correctly (well, I don't know if it's correct, but it doesn't freeze up like before). Here it is:

sub a { $_=pop;/495/&&$i||do{$_=join'',sort/./g;$i++;a(reverse()-$_)} #234567890123456789012345678901234567890123456789012345678901 }

Update:Changed code from 65 chars to 61.

The 15 year old, freshman programmer,
Stephen Rawls


Comment on Re: (Golf) Kaprekar's Process
Download Code
Re: Re: (Golf) Kaprekar's Process
by MeowChow (Vicar) on Jun 16, 2001 at 23:33 UTC
    ... it handles 0s in numbers correctly
    a(100)
    There are many such cases, though I misstated the problem somewhat. It isn't so much zeroed digits, as intermediate two-digit results. So far, all the solutions in this thread (except my own :) fail on many three-digit numbers.

    Also, in Golf, it may be ok to violate strict, but your subroutine should be re-runnable (ie. $i should be reset somewhere).

       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
      Oh, I see: 100 - 001 is 99; 99 - 99 is zero. Now we've got an infinite loop. Just out of curiosity, how would you solve that? Your solution gives 6 (which is most likely right), I just don't see how.

      The 15 year old, freshman programmer,
      Stephen Rawls

        That's what the sprintf is there for. It formats a two-digit result into a three-digit string, eg. 099. After sorting and reversal, you get 990 - 099.
           MeowChow                                   
                       s aamecha.s a..a\u$&owag.print

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://89085]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2015-07-03 06:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (48 votes), past polls