Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: (Golf) Kaprekar's Process

by tachyon (Chancellor)
on Jun 17, 2001 at 10:54 UTC ( #89143=note: print w/ replies, xml ) Need Help??


in reply to (Golf) Kaprekar's Process

Here's mine at 55.

cheers

tachyon

sub a { ++$a;$_=join"",sort pop=~/./g;$_!=459?a(-$_+reverse):$a }

Shave 1 for 54, and I'm out

sub a { ++$a;($_=join"",sort pop=~/./g)!=459?a(-$_+reverse):$a }


Comment on Re: (Golf) Kaprekar's Process
Select or Download Code
Re: Re: (Golf) Kaprekar's Process
by srawls (Friar) on Jun 17, 2001 at 19:19 UTC
    Nice... I can shave off four chars by taking off that $a variable. It still doesn't handle numbers like 100 correctly though; but so far only MeowChow's and mine, where I merely saved a few chars from MeowChow's solution, do. Here is your improved code, weighing in at a respectable 50 chars:
    sub a { ($_=join"",sort pop=~/./g)!=459?1+a(-$_+reverse):1 #2345678901234567890123456789012345678901234567890 }

    The 15 year old, freshman programmer,
    Stephen Rawls

Re: Re: (Golf) Kaprekar's Process
by sean (Beadle) on Jun 17, 2001 at 21:38 UTC
    This doesn't work for a lot of numbers, because you're checking AFTER the sort, for 459, which could've been 459,495,954,945,549, or 594 before the sort. your code gets the right answer when it was anything EXCEPT 495 before the sort.
    For example, 247:

    1: 742-247 = 495
    the answer is 1.

    your code produces 2.

      Good point, what can I say, seemed like a good idea at the time. The thinking was that any combination of 4,5,9 will sort to 954 and reverse to 459 so the timing of the sort was not important. As you note this breaks down in some cases. The QA was a bit suboptimal - I just bunged in the two examples and when they worked...

      Drat! I knew sneaking in a solution shorter than MeowChow was to good to be true :-)

      Cheers

      tachyon

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (12)
As of 2014-07-31 15:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (249 votes), past polls