# Solution 4

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

4Ga - Solution to Towers of Hanoi

```   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 ===> ');