http://www.perlmonks.org?node_id=89143


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 }

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 :-)

      Cheers

      tachyon

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