Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
We don't bite newbies here... much
 
PerlMonks  

Re: Recursion: the Towers of Hanoi problem

by Anonymous Monk
on Oct 19, 2004 at 12:53 UTC ( #400495=note: print w/ replies, xml ) Need Help??


in reply to Recursion: The Towers of Hanoi problem

Too bad people introduce the Towers of Hanoi, and then stop when they have introduced recursion. Because there's much more to discover. For instance that disks move in simple cycles, with half the disks moving in one direction, the other half in another. And that given the move number, one can calculate which disk needs to be moved based on the binary respresentation of the move number. Here's an interative solution based on those facts:

$*=shift; for($_=1;$_<=$*;$_++){$_[$_]=[split$,,(($*%2)xor($_%2))?ABC:ACB]} for($_=1;$_<2**$*;$_++){ $-=1+length((sprintf("%b",$_)=~/(0*)$/)[0]); printf"Move disk %d from pole %s to pole %s\n",$-,@{$_[$-]}[0,1]; push@{$_[$-]},shift@{$_[$-]} }


Comment on Re: Recursion: the Towers of Hanoi problem
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (16)
As of 2014-04-16 20:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (434 votes), past polls