11.03.2015 Views

Unicon Book

Unicon Book

Unicon Book

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1.10. PROCEDURES 27<br />

Now move the n-1 disks from needle1 to other, move the biggest disk, and then move<br />

the n-1 again. The needles are passed as additional parameters into the recursive calls.<br />

They are always two distinct values out of the set {1, 2, 3}.<br />

hanoi(n-1, needle1, other)<br />

write("Move disk from ", needle1, " to ", needle2)<br />

hanoi(n-1, other, needle2)<br />

That’s it! You’re done. Listing 1-2 contains the complete program for you to try:<br />

Listing 1-2 Towers of Hanoi<br />

procedure main()<br />

write("How many disks are on the towers of Hanoi?")<br />

hanoi(read())<br />

end<br />

procedure hanoi(n:integer, needle1:1, needle2:2)<br />

local other<br />

if n = 1 then write("Move disk from ", needle1, " to ", needle2)<br />

else {<br />

other := 6 - needle1 - needle2<br />

hanoi(n-1, needle1, other)<br />

write("Move disk from ", needle1, " to ", needle2)<br />

hanoi(n-1, other, needle2)<br />

}<br />

end<br />

Turn on tracing see how this program works. To enable tracing, compile your program<br />

with a -t option, or assign the keyword &trace a non-zero number giving the depth of calls<br />

to trace. Setting &trace to -1 will turn on tracing to an infinite depth.<br />

To move n disks, 2 n - 1 individual disk movements will be required. If the monks move<br />

one disk a second, it will take 2 64 - 1 seconds, or about 60 trillion years. Wikipedia has<br />

listed the age of the universe at around 13.75 billion years. It seems unlikely that we need<br />

worry about the monks finishing their task!<br />

Summary<br />

In this chapter you have learned:<br />

• <strong>Unicon</strong> is an expression-based language organized as a set of procedures starting from<br />

a procedure called main().<br />

• <strong>Unicon</strong> has four atomic types: arbitrary precision integers, real numbers, arbitrary<br />

length strings of characters, and character sets.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!