Hi,
I'm working on a towers of hanoi java programming assignment where
there are 3 pegs(stacks) and <n> number of disks.
When my gui calls moveDisks() it moves the disks between the pegs.
When i say there is 1 disk, the game completes as normal, the same with 2 disks.
But when i say there are 3 disks my algorithm doesnt work, im not sure what im doing wrong.
If anyone can help me with my algorithm that would be greatly appreciated.
See below for my moveDisks and legal move methods:
public void moveDisks() throws Exception { int even =0; if (Peg1.size%2 ==0) { //checks if the number of disks is even even = 1; if(Peg1.top() == smallest.top()){ smallest = smallest.right(); move(Peg1, Peg2); } } else if(Peg1.size%2>0) { //checks if the number of disks is odd even = 0; if(Peg1.top() == smallest.top()){ smallest = smallest.left(); move(Peg1, Peg3); } } if (!done()) { BoardString(); } while(!done()) { legalMove(); BoardString(); if (even == 1) { if(Peg1.top() == smallest.top()){ smallest = smallest.right(); move(Peg1, Peg2); } else if(Peg2.top() == smallest.top()) { smallest = smallest.right(); move(Peg2, Peg3); } else if(Peg3.top() == smallest.top()) { smallest = smallest.right(); move(Peg3, Peg1); } } else if(even == 0) { if(Peg1.top() == smallest.top()) { smallest = smallest.left(); move(Peg1, Peg3); } else if(Peg2.top() == smallest.top()) { smallest = smallest.left(); move(Peg2, Peg1); } else if(Peg3.top() == smallest.top()) { smallest = smallest.left(); move(Peg3, Peg2); } } } System.out.println("****** Game Complete ******"); } public void legalMove() throws Exception { // make the only other legal move try{ if (Peg1.top() == smallest.top()) { if (Peg2.top() > Peg3.top()) { move(Peg3, Peg2); } else if(Peg2.top() <Peg3.top()){ move(Peg2, Peg3); } } else if(Peg2.top() == smallest.top()) { if (Peg3.top() > Peg1.top()) { move(Peg1, Peg3); } else if(Peg3.top() < Peg1.top()) { move(Peg3, Peg1); } } else if(Peg3.top() == smallest.top()) { if (Peg1.top() > Peg2.top()) { move(Peg2, Peg1); } else if(Peg1.top()<Peg2.top()){ move(Peg1, Peg2); } } }catch(Exception e){} }