Tower of Hanoi
|
Team Size: Solo
Language: MATLAB A simple but effective MATLAB implementation for solving the famous Tower of Hanoi puzzle. (This is a recursive solution.) Individual steps are outputted to the console. Any number of discs for solving the puzzle are accepted, though as might be expected, large problem sets take an exponential amount of time to solve. Check out the video for a demonstration. |
Source Code
|
%Program by Ryan O'Hara
%CREATE AND SOLVE A PUZZLE HERE! %CHANGE THE VALUE PASSED TO THIS CREATE PUZZLE FUNCTION TO THE DESIRED NUMBER OF RINGS, THEN RUN THE PROGRAM. CreatePuzzle(3); function CreatePuzzle(size) %THIS FUNCTION CREATES 2 MOCKUP ARRAYS TO SHOW THE INITIAL AND FINAL BOARD STATE. %THERE IS NO LOGIC ASSOCIATED WITH THEM, THEY ARE JUST DIAGRAMS FOR CLARITY. % Variables c = newline; increment = 1; % Create puzzle diagram with defined size pegs = zeros(size,3); % Fill puzzle diagram with correct sizes of rings for a = 0:size-1 pegs(increment,1) = increment; increment = increment + 1; end %Reset increment counter to generate the second array increment = 1; % Create 'final' state of the board diagram pegsFinished = zeros(size,3); % Fill final state diagram with correct sizes of rings for a = 0:size-1 pegsFinished(increment,3) = increment; increment = increment + 1; end %Display initial board state disp(c); disp('----------------------------------------------------------'); disp(' PegA PegB PegC'); disp(pegs); disp('Starting position of the board.'); disp('----------------------------------------------------------'); %Launch our solving function SolvePuzzle(size,'A','C','B'); %Display final board state disp('----------------------------------------------------------'); disp(' PegA PegB PegC'); disp(pegsFinished); disp('Final position of the board.'); disp('----------------------------------------------------------'); end function SolvePuzzle(n,source,destination,auxillary) %THIS FUNCTION WILL SOLVE ANY GIVEN TOWER OF HANOI PROBLEM BY OUTPUTTING INCREMENTAL MOVES. % Break out of the loop if recursion depth reaches 0 if(n == 0) return; else % Recursively solve the puzzle by relaunching this function while % subtracting 1 from the max possible recursion depth. SolvePuzzle(n-1,source,auxillary,destination); disp(['Moved disk ', num2str(n),' from [Peg ',source,'] to [Peg ', destination,']']); end SolvePuzzle(n-1,auxillary,destination,source); end |
|