Basic Pascal Tutorial/Chapter 4/Solution/zh CN

From Lazarus wiki
(Redirected from Solution 4/zh CN)
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

български (bg) English (en) français (fr) 日本語 (ja) 中文(中国大陆)‎ (zh_CN)

4Ga - 汉诺塔参考答案 (原作者: Tao Yue, 状态: 英文部分为原文/中文部分有适当增删)

(* 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/NumDiscs -- 初始塔高
      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 *)
上一页 目录 下一页