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

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Here's my solution.

It's surely not optimal, but it's a very basic extension to the 3-peg solution, so the code is very short. It uses O(d1/(p-3)) moves O(2d/(p-2)) moves for the solution with d disks and p pegs (I'm too lazy to calculate the exact numbers).

(Updated fomula again. The O sign is meant if p is constant but d->inf)

Update: this is probably very suboptimal for more than 4 pegs.

#!/usr/local/bin/perl use warnings; use strict; $ARGV[0] =~ /(\d+)/ or die; my $pegs = $1; $ARGV[1] =~ /(\d+)/ or die; my $disks = $1; { my @pegnames = "A" .. "Z"; sub printmove { my($d, $f, $t) = @_; print $d, ": ", $pegnames[$f], " -> ", $pegnames[$t], "\n" } } sub rec { my($n, $s, $d, $t, @o) = @_; $n > 0 or return; my $k = @o < $n - 1 ? @o : $n - 1; #warn "[($n:${\($n-$k)} $s->$d]\n"; rec($n - $k - 1, $s, $t, $d, @o); printmove($n - $k + $_, $s, $o[$_]) for 0 .. $k - 1; printmove($n, $s, $d); printmove($n - $k + $_, $o[$_], $d) for reverse(0 .. $k - 1); rec($n - $k - 1, $t, $d, $s, @o); #warn "[)]\n" } rec($disks, 0, 1, 2 .. $pegs - 1); __END__

In reply to Re: Hanoi Challenge by ambrus
in thread Hanoi Challenge by tilly

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2022-05-25 16:37 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (90 votes). Check out past polls.