CSCI 150, Spring 2003

Home | | Course Schedule | | Assignments | | Lecture Notes

Homework 6 solution

{Author: Brenda Student
Section: CSCI 150, Section 1
Date:   October 18, 2001
Assignment: Homework 6
Purpose: Print out instructions to solve the Tower of Hanoi Puzzle}

program puzzle;

{Procedure moveRing() moves a ring from one peg to another }
procedure moveRing(ring : integer; fromPeg : char; toPeg : char);
begin
	writeln('Move ring ', ring, ' from peg ', fromPeg, ' to peg ', toPeg, '.');
end; {end moveRing}

{Procedure Hanoi() recursively solves the Tower of Hanoi puzzle for n rings}
procedure Hanoi(number: integer; source : char; dest : char; spare : char);
begin
	if number = 1 then
	begin
		moveRing(1, source, dest);
	end
	else
	begin
		Hanoi(number - 1, source, spare, dest);
		moveRing(number, source, dest);
		Hanoi(number - 1, spare, dest, source);
	end;
end; {end of Hanoi }

var
	numberOfRings : integer;	{number of rings in Tower}
begin
	writeln('How many rings in the tower?');
	readln(numberOfRings);
	Hanoi(numberOfRings, 'A', 'B', 'C');
end. {end of puzzle program}