Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 4/Solution: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Basic Pascal Tutorial/Chapter 4/Solution

OldNewLine
1+4Ga - Solution to Towers of Hanoi (author: Tao Yue, state: unchanged)
2+
3+``` pascal
4+(* Author: Tao Yue
5+ Date: 13 July 2000
6+ Description:
7+ Solves the Towers of Hanoi
8+ Version:
9+ 1.0 - original version
10+*)
11+
12+program TowersofHanoi;
13+
14+var
15+ numdiscs : integer;
16+
17+(********************************************************)
18+
19+procedure DoTowers (NumDiscs, OrigPeg, NewPeg, TempPeg : integer);
20+(* Explanation of variables:
21+ Number of discs -- number of discs on OrigPeg
22+ OrigPeg -- peg number of the tower
23+ NewPeg -- peg number to move the tower to
24+ TempPeg -- peg to use for temporary storage
25+*)
26+
27+begin
28+ (* Take care of the base case -- one disc *)
29+ if NumDiscs = 1 then
30+ writeln (OrigPeg, ' ---> ', NewPeg)
31+ (* Take care of all other cases *)
32+ else
33+ begin
34+ (* First, move all discs except the bottom disc
35+ to TempPeg, using NewPeg as the temporary peg
36+ for this transfer *)
37+ DoTowers (NumDiscs-1, OrigPeg, TempPeg, NewPeg);
38+ (* Now, move the bottommost disc from OrigPeg
39+ to NewPeg *)
40+ writeln (OrigPeg, ' ---> ', NewPeg);
41+ (* Finally, move the discs which are currently on
42+ TempPeg to NewPeg, using OrigPeg as the temporary
43+ peg for this transfer *)
44+ DoTowers (NumDiscs-1, TempPeg, NewPeg, OrigPeg)
45+ end
46+end;
47+
48+(********************************************************)
49+
50+begin (* Main *)
51+ write ('Please enter the number of discs in the tower ===> ');
52+ readln (numdiscs);
53+ writeln;
54+ DoTowers (numdiscs, 1, 3, 2)
55+end. (* Main *)
56+```
57+
58+---
59+*From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 4/Solution", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history