Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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.



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 }

Replies are listed 'Best First'.
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 :-)



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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://89143]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2017-09-24 08:03 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (273 votes). Check out past polls.