Towers of Hanoi: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(revert spam)
Line 1: Line 1:
{{task}}
[http://kitmun.cn/yugi-oh.html yugi oh] [http://babychams.fast-road.cn/index.html baby chams] [http://berteinaltomare.clung.cn/index.html berte in alto mare] [http://quoits.cn/zombies.html zombies cranberries] [http://buchholzhotel.clung.cn/index.html buchholz hotel] [http://boschi.kittiss.cn/index.html boschi] [http://kitmun.cn/your-latest.html your latest trick] [http://quoits.cn/zia-forli.html zia forli] [http://quoits.cn/apocalisse.html apocalisse sul fiume giallo] [http://snailtail.cn/y-tu-que-has/index.html y tu que has hecho] [http://snailtail.cn/www-tg-com/index.html www tg com it] [http://kitmun.cn/zampogne.html zampogne] [http://quoits.cn/zelig-wav.html zelig wav] [http://bluespanisheyestestoinita.clung.cn/index.html blue spanish eyes testo in ita] [http://knock-knock.cn/www-trombare/index.html www trombare] [http://snailtail.cn/www-pioggia/index.html www pioggia dorata it] [http://bielovar.kittiss.cn/index.html bielovar] [http://kitmun.cn/yesterday.html yesterday paul mccartney] [http://quoits.cn/zadok-the.html zadok the priest of tony britten] [http://knock-knock.cn/winzip-italiano/index.html winzip italiano] [http://quoits.cn/zambrone.html zambrone] [http://basemusicalelagatta.kittiss.cn/index.html base musicale la gatta] [http://snailtail.cn/x-me-importante/index.html x me importante] [http://quoits.cn/andate.html andate al west] [http://bollettinoufficialedellaregioneumbri.clung.cn/index.html bollettino ufficiale della regione umbri] [http://wonted.cn/wwwferdinandofama/index.html wwwferdinandofama com] [http://wonted.cn/www-rofrano/index.html www rofrano it] [http://benassibrosfeatdhany.kittiss.cn/index.html benassi bros feat dhany] [http://kitmun.cn/zahouania.html zahouania] [http://wonted.cn/www-yau-it/index.html www yau it] [http://bsb.midways.cn/index.html bsb] [http://knock-knock.cn/www-gry/index.html www gry pl] [http://bindiyachamkegi.fast-road.cn/index.html bindiya chamkegi] [http://wonted.cn/www-algare/index.html www algare com] [http://snailtail.cn/www-gewiss-it/index.html www gewiss it] [http://quoits.cn/arrivano-i-carri.html arrivano i carri armati] [http://bakstagecalendari.fast-road.cn/index.html bakstage calendari] [http://bubbles.kittiss.cn/index.html bubbles] [http://barbatulideal.clung.cn/index.html barbatul ideal] [http://quoits.cn/anni-verdi.html anni verdi] [http://wonted.cn/www-gusanito/index.html www gusanito com mx] [http://borntobealivephernandez.clung.cn/index.html born to be alive p hernandez] [http://wonted.cn/www-aido/index.html www aido it] [http://kitmun.cn/zayon-y.html zayon y lenox] [http://ballafigliola.romanikki.cn/index.html balla figliola] [http://beatrizrico.kittiss.cn/index.html beatriz rico] [http://bigtitts.fast-road.cn/index.html big titts] [http://knock-knock.cn/www-symantic/index.html www symantic com] [http://bluedubblin.midways.cn/index.html blue dubblin] [http://knock-knock.cn/www-matildebrandi/index.html www matildebrandi it] [http://knock-knock.cn/www-max-rcs/index.html www max rcs] [http://blofcountingcrowsholidayinspain.fast-road.cn/index.html blof counting crows holiday in spain] [http://blackeyedshutup.midways.cn/index.html black eyed shut up] [http://brasilianiagenova.clung.cn/index.html brasiliani a genova] [http://quoits.cn/ziberna.html ziberna] [http://snailtail.cn/yin/index.html yin] [http://basilicatanet.clung.cn/index.html basilicatanet] [http://barbeepizzetti.midways.cn/index.html barbe e pizzetti] [http://bertolucci.midways.cn/index.html bertolucci] [http://brendacarvalo.midways.cn/index.html brenda carvalo] [http://kitmun.cn/yeu.html yeu] [http://wonted.cn/www-moby/index.html www moby it] [http://basikaraokedisalsa.clung.cn/index.html basi karaoke di salsa] [http://binbaubassachebassa.fast-road.cn/index.html bin bau bassa che bassa] [http://snailtail.cn/yamaha-r1/index.html yamaha r1] [http://begley.romanikki.cn/index.html begley] [http://knock-knock.cn/www-iata/index.html www iata org] [http://barbaradursosexsextopless.kittiss.cn/index.html barbara durso sex sex topless] [http://snailtail.cn/yhaoomessenger/index.html yhaoomessenger] [http://snailtail.cn/xxx-pron-anime/index.html xxx pron anime] [http://bicrunga.kittiss.cn/index.html bic runga] [http://bibbiapernokia.midways.cn/index.html bibbia per nokia] [http://bigliettiniaugurimatriomonio.fast-road.cn/index.html bigliettini auguri matriomonio] [http://bonnietylerandkareenantonn.clung.cn/index.html bonnie tyler and kareen antonn] [http://snailtail.cn/xxx-gay/index.html xxx gay] [http://knock-knock.cn/www-ornela/index.html www ornela vorpsi] [http://wonted.cn/www-quattroruote/index.html www quattroruote it] [http://quoits.cn/a-caccia-di-spie.html a caccia di spie] [http://knock-knock.cn/www-modelle/index.html www modelle it] [http://quoits.cn/zero-reticoli.html zero reticoli] [http://wonted.cn/www-joker/index.html www joker it] [http://snailtail.cn/x-win32/index.html x win32] [http://bia322y.romanikki.cn/index.html bia 322 y] [http://battagliaterme.romanikki.cn/index.html battagliaterme] [http://bluespartiti.clung.cn/index.html blue spartiti] [http://birckenstockheidiklum.kittiss.cn/index.html birckenstock heidi klum] [http://ballandoalbuoio.fast-road.cn/index.html ballando al buoio] [http://wonted.cn/www-kings-of/index.html www kings of convinience it] [http://britneyhomepage.fast-road.cn/index.html britney home page] [http://quoits.cn/assicurasi.html assicurasi vergine] [http://kitmun.cn/zeta-zero-alfa.html zeta zero alfa] [http://quoits.cn/amanti.html amanti in fuga] [http://snailtail.cn/www-sanpaolo/index.html www sanpaolo banco di napoli] [http://wonted.cn/wilkommen/index.html wilkommen] [http://wonted.cn/www-roadrunner/index.html www roadrunner com] [http://knock-knock.cn/www-bramkasms/index.html www bramkasms pl] [http://babyrastaygringosentenciado.fast-road.cn/index.html baby rasta y gringo sentenciado] [http://knock-knock.cn/w-w-w-mani/index.html w w w mani tese it] [http://knock-knock.cn/www-nido-hotel/index.html www nido hotel com] [http://quoits.cn/arizona-si.html arizona si scatenò... e li fece fuori tutti!] [http://kitmun.cn/yozo-kaka.html yozo kaka ritka] [http://bonytailor.clung.cn/index.html bony tailor] [http://quoits.cn/agenzia-matrimoniale.html agenzia matrimoniale "a"] [http://knock-knock.cn/www-luigi/index.html www luigi interfree it] [http://bonytaylor.midways.cn/index.html bony taylor] [http://quoits.cn/atto-d'amore.html atto d'amore - il magnifico disertore] [http://wonted.cn/www-makelovetome/index.html www makelovetome com] [http://biografytotti.midways.cn/index.html biografy totti] [http://wonted.cn/www-neuromed/index.html www neuromed] [http://benassimidi.fast-road.cn/index.html benassi midi] [http://knock-knock.cn/www-coscienza/index.html www coscienza org] [http://bellequarantenni.kittiss.cn/index.html belle quarantenni] [http://snailtail.cn/xatzigiann/index.html xatzigiann] [http://brazil.fast-road.cn/index.html brazil] [http://kitmun.cn/you-and-i.html you and i] [http://snailtail.cn/y-hubo-alguien/index.html y hubo alguien] [http://snailtail.cn/xcrypt/index.html xcrypt] [http://snailtail.cn/x-goe-give-to/index.html x goe give to ya] [http://wonted.cn/www-aol/index.html www aol] [http://bellezzedellatv.romanikki.cn/index.html bellezze della tv] [http://bailagigidalessio.midways.cn/index.html baila gigi d alessio] [http://bagnimojito.clung.cn/index.html bagnimojito] [http://bennatomediterraneo.midways.cn/index.html bennato mediterraneo] [http://barbarie21settenbre.kittiss.cn/index.html barbarie 21 settenbre] [http://basiremix.fast-road.cn/index.html basi remix] [http://knock-knock.cn/www-triangolo/index.html www triangolo delle bermuda it] [http://berlusconiconlabandana.clung.cn/index.html berlusconi con la bandana] [http://bahibakmoot.clung.cn/index.html bahibak moot] [http://snailtail.cn/xutos/index.html xutos] [http://boccadimagra.midways.cn/index.html bocca di magra] [http://bungalowcampania2persone.clung.cn/index.html bungalow campania 2 persone] [http://bayerserieh.romanikki.cn/index.html bayer serie h] [http://bigcocks.romanikki.cn/index.html big cocks] [http://kitmun.cn/ymne-a-l-amour.html ymne a l amour] [http://biografiacostantinovitigliano.kittiss.cn/index.html biografia costantino vitigliano] [http://wonted.cn/willy-denzer/index.html willy denzer] [http://kitmun.cn/yaouu.html yaouu] [http://borseburberry.clung.cn/index.html borse burberry] [http://bussicilia.midways.cn/index.html bus sicilia] [http://kitmun.cn/zir.html zir] [http://wonted.cn/www-strano/index.html www strano it] [http://bacioamezzanotte.romanikki.cn/index.html bacio a mezzanotte] [http://bulldozer.romanikki.cn/index.html bulldozer] [http://knock-knock.cn/www-istruzione/index.html www istruzione pg] [http://bluvacanze.fast-road.cn/index.html blu vacanze] [http://basimusicalifilm.clung.cn/index.html basi musicali film] [http://bestsellers.midways.cn/index.html best sellers] [http://wonted.cn/www-unpostoalsole/index.html www unpostoalsole org] [http://breathlessthecorrs.clung.cn/index.html breathless the corrs] [http://snailtail.cn/yo-necesito/index.html yo necesito estar contigo yo no quiero ser] {{task}}


In this task, the goal is to solve the Towers of Hanoi problem with recursivity.
In this task, the goal is to solve the Towers of Hanoi problem with recursivity.
Line 13: Line 13:
if Ndisks > 0 then
if Ndisks > 0 then
Hanoi(Ndisks - 1, Start_Peg, Via_Peg, End_Peg);
Hanoi(Ndisks - 1, Start_Peg, Via_Peg, End_Peg);
Put_Line("Move disk"
Put_Line("Move disk" & Natural'Image(Ndisks) & " from " & Pegs'Image(Start_Peg) & " to " &
Pegs'Image(End_Peg));
Hanoi(Ndisks - 1, Via_Peg, End_Peg, Start_Peg);
end if;
end Hanoi;
begin
Hanoi(4);
end Towers;


==[[AppleScript]]==
[[Category:AppleScript]]
global moves --this is so the handler 'hanoi' can see the 'moves' variable
set moves to ""
hanoi(4, "peg A", "peg C", "peg B")
on hanoi(ndisks, fromPeg, toPeg, withPeg)
if ndisks is greater than 0 then
hanoi(ndisks - 1, fromPeg, withPeg, toPeg)
set moves to moves & "Move disk " & ndisks & " from " & fromPeg & " to " & toPeg & return
hanoi(ndisks - 1, withPeg, toPeg, fromPeg)
end if
return moves
end hanoi


==[[C plus plus|C++]]==
[[Category:C plus plus]]
'''Compiler:''' [[GCC]]

void move(int n, int from, int to, int via) {
if (n == 1) {
std::cout << "Move disk from pole " << from << " to pole " << to << std::endl;
} else {
move(n - 1, from, via, to);
move(1, from, to, via);
move(n - 1, via, to, from);
}
}



==[[E]]==
[[Category:E]]

def move(out, n, fromPeg, toPeg, viaPeg) {
if (n.aboveZero()) {
move(out, n.previous(), fromPeg, viaPeg, toPeg)
out.println(`Move disk $n from $fromPeg to $toPeg.`)
move(out, n.previous(), viaPeg, toPeg, fromPeg)
}
}
move(stdout, 4, def left {}, def right {}, def middle {})

==[[Forth]]==
[[Category:Forth]]
With locals:

CREATE peg1 ," left "
CREATE peg2 ," middle "
CREATE peg3 ," right "
: .$ COUNT TYPE ;
: MOVE-DISK
LOCALS| via to from n |
n 1 =
IF CR ." Move disk from " from .$ ." to " to .$
ELSE n 1- from via to RECURSE
1 from to via RECURSE
n 1- via to from RECURSE
THEN ;

Without locals, executable pegs:

: left ." left" ;
: right ." right" ;
: middle ." middle" ;
: print ( t f -- )
CR ." Move disk from " execute ." to " execute ;
: move-disk ( v t f n -- v t f )
dup 1 = if drop 2dup print exit then
1- >R
rot swap R@ ( t v f n-1 ) recurse
rot swap 2dup print
swap rot R> ( f t v n-1 ) recurse
swap rot ;
: hanoi ( n -- )
1 max >R ['] right ['] middle ['] left R> move-disk drop drop drop ;

==[[Java]]==
[[Category:Java]]

public void move(int n, int from, int to, int via) {
if (n == 1) {
System.out.println("Move disk from pole " + from + " to pole " + to);
} else {
move(n - 1, from, via, to);
move(1, from, to, via);
move(n - 1, via, to, from);
}
}

==[[Perl]]==
[[Category:Perl]]
sub move {
my $n = shift;
my $from = shift;
my $to = shift;
my $via = shift;
if ($n == 1) {
print "Move disk from pole $from to pole $to.\n";
} else {
move($n - 1, $from, $via, $to);
move(1, $from, $to, $via);
move($n - 1, $via, $to, $from);
};
};

==[[Pop11]]==
[[Category:Pop11]]

define hanoi(n, src, dst, via);
if n > 0 then
hanoi(n - 1, src, via, dst);
printf('Move disk ' >< n >< ' from ' >< src >< ' to ' >< dst >< '.\n');
hanoi(n - 1, via, dst, src);
endif;
enddefine;

hanoi(4, "left", "middle", "right");

==[[Python]]==
[[Category:Python]]

<pre>
def hanoi(ndisks, startPeg=1, endPeg=3):
if ndisks:
hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)

hanoi(ndisks=4)
</pre>

==[[Seed7]]==
[[Category:Seed7]]

const proc: hanoi (in integer: disk, in string: source, in string: dest, in string: via) is func
begin
if disk > 0 then
hanoi(pred(disk), source, via, dest);
writeln("Move disk " <& disk <& " from " <& source <& " to " <& dest);
hanoi(pred(disk), via, dest, source);
end if;
end func;

==[[Toka]]==
[[Category:Toka]]

value| sa sb sc n |
[ to sc to sb to sa to n ] is vars!
[ ( num from to via -- )
vars!
n 0 <>
[
n sa sb sc
n 1- sa sc sb recurse
vars!
." Move a ring from " sa . ." to " sb . cr
n 1- sc sb sa recurse
] ifTrue
] is hanoi

Revision as of 14:07, 10 September 2007

Task
Towers of Hanoi
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the goal is to solve the Towers of Hanoi problem with recursivity.

Ada

with Ada.Text_Io; use Ada.Text_Io;

procedure Towers is
   type Pegs is (Left, Center, Right);
   procedure Hanoi (Ndisks : Natural; Start_Peg : Pegs := Left; Via_Peg : Pegs := Center; End_Peg : Pegs := Right) is
   begin
      if Ndisks > 0 then
         Hanoi(Ndisks - 1, Start_Peg, Via_Peg, End_Peg);
         Put_Line("Move disk" & Natural'Image(Ndisks) & " from " & Pegs'Image(Start_Peg) & " to " &
            Pegs'Image(End_Peg));
         Hanoi(Ndisks - 1, Via_Peg, End_Peg, Start_Peg);
      end if;
   end Hanoi;
begin
   Hanoi(4);
end Towers;


AppleScript

global moves --this is so the handler 'hanoi' can see the 'moves' variable
set moves to ""
hanoi(4, "peg A", "peg C", "peg B")

on hanoi(ndisks, fromPeg, toPeg, withPeg)
    if ndisks is greater than 0 then
        hanoi(ndisks - 1, fromPeg, withPeg, toPeg)
        set moves to moves & "Move disk " & ndisks & " from " & fromPeg & " to " & toPeg & return
        hanoi(ndisks - 1, withPeg, toPeg, fromPeg)
    end if
    return moves
end hanoi


C++

Compiler: GCC

void move(int n, int from, int to, int via) {
  if (n == 1) {
    std::cout << "Move disk from pole " << from << " to pole " << to << std::endl;
  } else {
    move(n - 1, from, via, to);
    move(1, from, to, via);
    move(n - 1, via, to, from);
  }
}


E

def move(out, n, fromPeg, toPeg, viaPeg) {
    if (n.aboveZero()) {
        move(out, n.previous(), fromPeg, viaPeg, toPeg)
        out.println(`Move disk $n from $fromPeg to $toPeg.`)
        move(out, n.previous(), viaPeg, toPeg, fromPeg)
    }
}

move(stdout, 4, def left {}, def right {}, def middle {})

Forth

With locals:

CREATE peg1 ," left "   
CREATE peg2 ," middle " 
CREATE peg3 ," right " 

: .$   COUNT TYPE ;
: MOVE-DISK 
  LOCALS| via to from n | 
  n 1 =
  IF   CR ." Move disk from " from .$ ." to " to .$ 
  ELSE n 1- from via to RECURSE 
       1    from to via RECURSE 
       n 1- via to from RECURSE 
  THEN ;

Without locals, executable pegs:

: left   ." left" ;
: right  ." right" ;
: middle ." middle" ;

: print ( t f -- )
  CR ." Move disk from " execute ."  to " execute  ;
: move-disk ( v t f n -- v t f )
  dup 1 = if drop 2dup print exit then
  1-       >R
  rot swap R@ ( t v f n-1 ) recurse
  rot swap        2dup print
  swap rot R> ( f t v n-1 ) recurse
  swap rot ;
: hanoi ( n -- )
  1 max >R ['] right ['] middle ['] left R> move-disk drop drop drop ;

Java

 public void move(int n, int from, int to, int via) {
   if (n == 1) {
     System.out.println("Move disk from pole " + from + " to pole " + to);
   } else {
     move(n - 1, from, via, to);
     move(1, from, to, via);
     move(n - 1, via, to, from);
   }
 }

Perl

sub move {
    my $n    = shift;
    my $from = shift;
    my $to   = shift;
    my $via  = shift;

    if ($n == 1) {
        print "Move disk from pole $from to pole $to.\n";
    } else {
        move($n - 1, $from, $via, $to);
        move(1, $from, $to, $via);
        move($n - 1, $via, $to, $from);
    };
};

Pop11

define hanoi(n, src, dst, via);
if n > 0 then
    hanoi(n - 1, src, via, dst);
    printf('Move disk ' >< n >< ' from ' >< src >< ' to ' >< dst >< '.\n');
    hanoi(n - 1, via, dst, src);
endif;
enddefine;
hanoi(4, "left", "middle", "right");

Python

def hanoi(ndisks, startPeg=1, endPeg=3):
    if ndisks:
        hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
        print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
        hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)

hanoi(ndisks=4)

Seed7

const proc: hanoi (in integer: disk, in string: source, in string: dest, in string: via) is func
  begin
    if disk > 0 then
      hanoi(pred(disk), source, via, dest);
      writeln("Move disk " <& disk <& " from " <& source <& " to " <& dest);
      hanoi(pred(disk), via, dest, source);
    end if;
  end func;

Toka

value| sa sb sc n |
[ to sc to sb to sa to n ] is vars!
[ ( num from to via -- )
  vars!
  n 0 <>
  [
    n sa sb sc 
    n 1- sa sc sb recurse
    vars!
    ." Move a ring from " sa . ." to " sb . cr
    n 1- sc sb sa recurse
  ] ifTrue
] is hanoi