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

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.