Towers of Hanoi Algorithm Error once i get to 3 disks??
Hi,
I'm working on a towers of hanoi java programming assignment where
there are 3 pegs(stacks) and <n> number of disks.
http://upload.wikimedia.org/wikipedi..._of_Hanoi.jpeg
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:
Code java:
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){}
}
Re: Towers of Hanoi Algorithm Error once i get to 3 disks??
What do you mean when you say "it doesn't work"? You have to be more specific than that.
Have you stepped through this with a debugger, or at least added some print statements, to figure out what's going on?
PS- I added highlight tags for you this time. Don't forget them in the future.
Re: Towers of Hanoi Algorithm Error once i get to 3 disks??
Thank you for your comments, I have managed to solve the issue in the meantime, it turns out I had messed up elsewhere in my Stack class. Instead of returning 0 when a stack was empty i had it returning a error which caused my if statements to fall over somehow.
Thanks for your tip about the tags, i did not know I could do that.