tower of hanoi in matlab

Below is an implementation of the Tower of Hanoi problem in MATLAB using recursion:

main.m
function towerOfHanoi(n, source, destination, auxiliary)

% Recursive function to solve the Tower of Hanoi problem
% n - number of disks
% source - the source peg
% destination - the destination peg
% auxiliary - the auxiliary peg

if n == 1
    fprintf('Move disk 1 from %s to %s\n', source, destination);
else
    towerOfHanoi(n-1, source, auxiliary, destination);
    fprintf('Move disk %d from %s to %s\n', n, source, destination);
    towerOfHanoi(n-1, auxiliary, destination, source);
end
end
499 chars
17 lines

This function takes four arguments: "n" specifies the number of disks, "source" is the source peg, "destination" is the destination peg, and "auxiliary" is the auxiliary peg.

If there is only one disk, it moves directly from the source to the destination. If there are more than one disk, it recursively moves the upper n-1 disks from the source to the auxiliary peg, then moves the largest disk from the source to the destination, and finally, it recursively moves the n-1 disks from the auxiliary to the destination peg.

You can call this function from the MATLAB command window as follows:

main.m
>> towerOfHanoi(3, 'A', 'C', 'B')
34 chars
2 lines

This command will solve the Tower of Hanoi problem with three disks, where the initial source peg is 'A', the final destination peg is 'C', and the auxiliary peg is 'B'. The output will show the necessary steps for the solution.

gistlibby LogSnag