M3xr - 4 months ago 30

C Question

I need to write a hanoi recursion algorithm with 3 parameters. This is what I got:

`#include <stdio.h> #include <stdio.h>`

void hanoi(int m, int i, int j);

void move(int start, int end);

int main(){

int n = 0;

int i = 1;

int j = 3;

printf("Enter how many disks you want to move: ");

scanf("%d", &n);

int m = n;

hanoi(m,i,j);

}

void hanoi(int m, int i, int j){

if (m==1)

{

move(i,j);

return;

}

hanoi(m-1,i,2);

move(i,j);

hanoi(m-1,2,j);

}

void move(int start, int end){

printf("A disk moves from position %d. to %d.\n", start,end);

}

The output for n=3 is the following:

`Enter how many disks you want to move: 3`

A disk moves from position 1. to 2.

A disk moves from position 1. to 2.

A disk moves from position 2. to 2.

A disk moves from position 1. to 3.

A disk moves from position 2. to 2.

A disk moves from position 2. to 3.

A disk moves from position 2. to 3.

I looked at other algorithms, I know there is tons of those for solving the goold old hanoi problem. However, they all have 4 parameters and use characters, whereas I would like to only use numbers and leave out the auxiliary tower parameter in my function. How can I fix it? For n=1 and n=2 the algorithm works fine.

Answer

Code needs to use the *other* peg, rather than `2`

as commented by @Karoly Horvath

```
void hanoi(int m, int i, int j){
if (m==1) {
move(i,j);
return;
}
int Other_peg = (1+2+3) - i - j;
hanoi(m-1,i,Other_peg);
move(i,j);
hanoi(m-1,Other_peg,j);
}
```