Tutorial 5: Notes

Tower of Hanoi with disk positions

We modified the Tower of Hanoi program to write out the positions of the disks at each step:

{$mode delphi}
{$r+}

uses strutils, sysutils;

var
  n: integer;
  pegs: array[1..3] of string;

procedure draw;
var
  p: integer;
begin
  for p := 1 to 3 do
    write(ifThen(pegs[p] = '', '-', pegs[p]):n, ' ');
  writeln;
end;

procedure move(n: integer; fromPeg: integer; toPeg: integer);
begin
  if n = 0 then exit;
  
  move(n - 1, fromPeg, 6 - fromPeg - toPeg);
  
  // move disk n from fromPeg to toPeg
  pegs[fromPeg] := rightStr(pegs[fromPeg], length(pegs[fromPeg]) - 1);
  pegs[toPeg] := intToStr(n) + pegs[toPeg];
  draw;
  
  move(n - 1, 6 - fromPeg - toPeg, toPeg);
end;

var
  i: integer;

begin
  readln(n);
  writeln;
  
  for i := 1 to n do
    pegs[1] := pegs[1] + intToStr(i);
  pegs[2] := '';
  pegs[3] := '';
  draw;
  
  move(n, 1, 3);
end.