PDA

View Full Version : Towers of Hanoi with 2 args


kuber
10-25-2002, 07:35 PM
I have seen this problem solved with an algorithm as such:

void hanoi(int n, int start, int finish, int extra) {
if(n != 0) {
hanoi(n-1,start,extra,finish);
printf("move disk %d from peg %d to peg %d\n",n,start,finish);
hanoi(n-1,extra,finish,start);
}
}

'move n discs from start to finish using extra'
I was wondering if anyone knew how to do this with just int n, int
start, and int finish.
void hanoi(int n, int start, int finish) {

???
}

Thanks,
kuber

bwkaz
10-26-2002, 10:03 AM
Well I'm not sure, but the first thing that comes to mind is, you know that start, finish, and extra all have to be 1, 2, or 3, and they all have to be different. So you could just create a local variable named extra, and set it to whatever start and end aren't. That's probably not right, but it would work. Something like:

void hanoi(int n, int start, int finish) {
int extra;

if(start != 1 && finish != 1)
extra = 1;
else if(start != 2 && finish != 2)
extra = 2;
else
extra = 3;

// Now use the other version of the code
}

kuber
10-28-2002, 02:41 PM
bwkaz-

Thanks, I don't think there is any other way to do it and that works, though perhaps not elegantly ;)