You are on page 1of 3

MATLAB files for towers of Hanoi

The MATLAB scripts for this and other examples used in this work were prepared mainly by Dr Leigh Johnston and Dr Manik Attygale, whose contribution is kindly acknowledged. We need to create two M files: hanoi.m and towers.m Use File, New, M-file to move to the MATLAB editor window. Create and save the two files listed below. You can then run hanoi.m from the MATLAB command window or from the editor. For the second option you will have to return to the command window to enter the number of disks. hanoi.m asks you to input the number of disks to be moved and calls on the function towers to solve the problem. We need another file, towers.m to define the function towers. The hanoi.m file is
% Script to do Towers of Hanoi in Matlab num = input('Towers of Hanoi: How many disks?\n'); fprintf('\n\n'); towers(num,'a','c','b'); fprintf('\n\n');

fprintf writes to the screen, \t is a horizontal tab, \n a new line, %c is for single character output and %d for decimal notation (see below). We are moving the tower of disks from peg a to peg c, using peg b. The towers.m file is
% Function used in "hanoi.m" for Towers of Hanoi demo
function[] = towers(n,frompeg,topeg,auxpeg); if (n == 1) else towers(n-1, frompeg,auxpeg,topeg); fprintf('\t move disk %d from peg %c to peg %c \n', n,frompeg,topeg); towers(n-1,auxpeg,topeg,frompeg); end; fprintf('\t move disk 1 from peg %c to peg %c \n',frompeg,topeg);

We now run hanoi.m and enter the number of disks to be moved. If n = 3, say, then: move disk 1 from peg a to peg c move disk 2 from peg a to peg b move disk 1 from peg c to peg b move disk 3 from peg a to peg c move disk 1 from peg b to peg a move disk 2 from peg b to peg c move disk 1 from peg a to peg c The following very short program hanoicount.m counts the number of moves required. %counts number of moves for towers of hanoi function y=hanoicount(n); if (n==1); y=1; else y=2*hanoicount(n-1)+1; end; So, in the command window we obtain, for example: >> hanoicount(20) ans = 1048575

You might also like