Difference between revisions of "Basic Pascal Tutorial/Chapter 4/Solution"
From Free Pascal wiki
Jump to navigationJump to searchm (Text replace - "delphi>" to "syntaxhighlight>") |
m (bypass language bar/categorization template redirect [cf. discussion]) |
||
(5 intermediate revisions by 4 users not shown) | |||
Line 1: | Line 1: | ||
+ | {{Basic Pascal Tutorial/Chapter 4/Solution}} | ||
+ | {{TYNavigator|Chapter 4/Programming Assignment|Chapter 5/Enumerated types}} | ||
+ | |||
4Ga - Solution to Towers of Hanoi (author: Tao Yue, state: unchanged) | 4Ga - Solution to Towers of Hanoi (author: Tao Yue, state: unchanged) | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang=pascal> |
(* Author: Tao Yue | (* Author: Tao Yue | ||
Date: 13 July 2000 | Date: 13 July 2000 | ||
Line 56: | Line 59: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | {| | + | {{TYNavigator|Chapter 4/Programming Assignment|Chapter 5/Enumerated types}} |
− | |||
− | |||
− | |||
− | |} |
Latest revision as of 16:20, 20 August 2022
│
български (bg) │
English (en) │
français (fr) │
日本語 (ja) │
中文(中国大陆) (zh_CN) │
4Ga - Solution to Towers of Hanoi (author: Tao Yue, state: unchanged)
(* Author: Tao Yue
Date: 13 July 2000
Description:
Solves the Towers of Hanoi
Version:
1.0 - original version
*)
program TowersofHanoi;
var
numdiscs : integer;
(********************************************************)
procedure DoTowers (NumDiscs, OrigPeg, NewPeg, TempPeg : integer);
(* Explanation of variables:
Number of discs -- number of discs on OrigPeg
OrigPeg -- peg number of the tower
NewPeg -- peg number to move the tower to
TempPeg -- peg to use for temporary storage
*)
begin
(* Take care of the base case -- one disc *)
if NumDiscs = 1 then
writeln (OrigPeg, ' ---> ', NewPeg)
(* Take care of all other cases *)
else
begin
(* First, move all discs except the bottom disc
to TempPeg, using NewPeg as the temporary peg
for this transfer *)
DoTowers (NumDiscs-1, OrigPeg, TempPeg, NewPeg);
(* Now, move the bottommost disc from OrigPeg
to NewPeg *)
writeln (OrigPeg, ' ---> ', NewPeg);
(* Finally, move the discs which are currently on
TempPeg to NewPeg, using OrigPeg as the temporary
peg for this transfer *)
DoTowers (NumDiscs-1, TempPeg, NewPeg, OrigPeg)
end
end;
(********************************************************)
begin (* Main *)
write ('Please enter the number of discs in the tower ===> ');
readln (numdiscs);
writeln;
DoTowers (numdiscs, 1, 3, 2)
end. (* Main *)