Difference between revisions of "Solution 4"

From Lazarus wiki
(New page: 4Ga - Solution to Towers of Hanoi <font color="#000000"> 1:</font> <font color="#cc0000">(*</font><font color="#cc0000"> </font><font color="#cc0000">Author:</font><font color="#cc0000...)
 
Line 1: Line 1:
4Ga - Solution to Towers of Hanoi
+
4Ga - Solution to Towers of Hanoi (author: Tao Yue, state: unchanged)
  
 
  <font color="#000000">  1:</font> <font color="#cc0000">(*</font><font color="#cc0000"> </font><font color="#cc0000">Author:</font><font color="#cc0000"> </font><font color="#cc0000"> </font><font color="#cc0000"> </font><font color="#cc0000"> </font><font color="#cc0000">Tao</font><font color="#cc0000"> </font><font color="#cc0000">Yue</font>
 
  <font color="#000000">  1:</font> <font color="#cc0000">(*</font><font color="#cc0000"> </font><font color="#cc0000">Author:</font><font color="#cc0000"> </font><font color="#cc0000"> </font><font color="#cc0000"> </font><font color="#cc0000"> </font><font color="#cc0000">Tao</font><font color="#cc0000"> </font><font color="#cc0000">Yue</font>

Revision as of 22:04, 25 November 2007

4Ga - Solution to Towers of Hanoi (author: Tao Yue, state: unchanged)

   1: (* Author:    Tao Yue
   2:    Date:      13 July 2000
   3:    Description:
   4:       Solves the Towers of Hanoi
   5:    Version:
   6:       1.0 - original version
   7: *)
   8: 
   9: program TowersofHanoi;
  10: 
  11: var
  12:   numdiscs : integer;
  13: 
  14: (********************************************************)
  15: 
  16: procedure DoTowers (NumDiscs, OrigPeg, NewPeg, TempPeg : integer);
  17: (* Explanation of variables:
  18:       Number of discs -- number of discs on OrigPeg
  19:       OrigPeg -- peg number of the tower
  20:       NewPeg -- peg number to move the tower to
  21:       TempPeg -- peg to use for temporary storage
  22: *)
  23: 
  24: begin
  25:   (* Take care of the base case -- one disc *)
  26:   if NumDiscs = 1 then
  27:     writeln (OrigPeg, ' ---> ', NewPeg)
  28:   (* Take care of all other cases *)
  29:   else
  30:   begin
  31:     (* First, move all discs except the bottom disc
  32:        to TempPeg, using NewPeg as the temporary peg
  33:        for this transfer *)
  34:     DoTowers (NumDiscs-1, OrigPeg, TempPeg, NewPeg);
  35:     (* Now, move the bottommost disc from OrigPeg
  36:        to NewPeg *)
  37:     writeln (OrigPeg, ' ---> ', NewPeg);
  38:     (* Finally, move the discs which are currently on
  39:        TempPeg to NewPeg, using OrigPeg as the temporary
  40:        peg for this transfer *)
  41:     DoTowers (NumDiscs-1, TempPeg, NewPeg, OrigPeg)
  42:   end
  43: end;
  44: 
  45: (********************************************************)
  46: 
  47: 
  48: begin    (* Main *)
  49:   write ('Please enter the number of discs in the tower ===> ');
  50:   readln (numdiscs);
  51:   writeln;
  52:   DoTowers (numdiscs, 1, 3, 2)
  53: end.     (* Main *)
previous contents next