Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Recursion: the Towers of Hanoi problem

by abitkin (Monk)
on Oct 20, 2004 at 16:52 UTC ( #400916=note: print w/replies, xml ) Need Help??

in reply to Recursion: The Towers of Hanoi problem

My own code, for a class I had
#!/usr/bin/perl -w use strict; han('A','B','C',$ARGV[0]); sub han{ return if $_[3] <= 0; han($_[0],$_[2],$_[1],$_[3]-1); print "Move disc $_[3] from $_[0] to $_[2]\n"; han($_[1],$_[0],$_[2],$_[3]-1); }
Number of discs is supplied as $ARGV[0] so, yeah. You could continue to play with this to see how much more it will compress. (I really didn't like the TA's for this class and eventually started using map and grep in all the programs.)

made it shorter.

Kwyjibo. A big, dumb, balding North American ape. With no chin.

Replies are listed 'Best First'.
Re^2: Recursion: the Towers of Hanoi problem
by Jasper (Chaplain) on Oct 21, 2004 at 14:02 UTC
    sub han { if (my $l = pop) { han(@_[0,2,1],$l-1); print "Move disc $l from $_[0] to $_[2]\n"; han(@_[1,0,2],$l-1); } }

    little shorter
      Try this on:
      sub a{my$l=pop;a(@_[0,2,1],--$l)."Move disc $l from $_[0] to $_[2] ".a(@_[1,0,2],$l)if$l>0;}print a 'A'..'C',shift;
      Now trying for the least number of chars. 116 in this solution.
      New rules, no #! needed.

      Kwyjibo. A big, dumb, balding North American ape. With no chin.
        In real terms, this is slightly longer than the previous version, isn't it? you need a space between print and the argument, I don't. Apart from that, this is different to the requirements. This prints out $l - 1, which is incorrect, or at least different to the 1-3 based original solution.

        Trimming whitespace from the solution in my last post, and giving it a one character sub name makes it 112 characters, 107 if you take the quotes and braces around a A..C,pop.

        Strangely, using my $l=$_[3]-- and using a(@_[0,2,1,3]) etc. doesn't work at all. @_ is not localised ($_3 ends up very negative and the solution becomes deeply recursive), which makes me wonder if the above solution works. I haven't compared the output to the original solution's output.
Re^2: Recursion: the Towers of Hanoi problem
by SpanishInquisition (Pilgrim) on Oct 20, 2004 at 17:47 UTC
    Ironically that's the way I feel about work...

    It's not about obfuscation, it's about coding 9 planes of existance higher than them because you can, and they don't want to learn...

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2020-10-22 09:07 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (225 votes). Check out past polls.