I'm trying to solve the Hanoi problem using an iterative method. I try to do this by using two for nested loops, so as to repeat n - 1 steps in each loop, where n is the number of moves. I think I have well posed the problem by using two for, but I don't understand how to change the order of the towers at each pass. Can anyone help me with this task?
inizio is start, fine is end and supp is support
#include <stdlib.h>
#include <stdio.h>
void tower_Organizer(int *inizio, int *fine, int *supp);
void hanoi_Iter(int n, int inizio, int fine, int supp);
int main(void){
int n;
printf("%s\n" ,"inserisci un nuero positivo");
scanf("%d", &n);
hanoi_Iter(n, 1, 2, 3);
return 0;
}
void hanoi_Iter(int n, int inizio, int fine, int supp){
for(int i = 1 ; i <= n ; i ){
for(int j = 1 ; j <= i - 1 ; j ){
printf("%d -> %d\n", inizio, fine);
tower_Organizer(&inizio, &fine, &supp);
}
printf("%d -> %d\n", inizio, fine);
tower_Organizer(&inizio, &fine, &supp);
}
}
void tower_Organizer(int *inizio, int *fine, int *supp){
static int count = 1;
int c = count % 6;
switch( c ){
case 0:
*inizio = 1;
*fine = 2;
*supp = 3;
break;
case 1:
*inizio = 1;
*fine = 3;
*supp = 2;
break;
case 2:
*inizio = 2;
*fine = 3;
*supp = 1;
break;
case 3:
*inizio = 1;
*fine = 2;
*supp = 3;
break;
case 4:
*inizio = 3;
*fine = 1;
*supp = 2;
break;
case 5:
*inizio = 3;
*fine = 2;
*supp = 1;
break;
}
count ;
}
CodePudding user response:
The number of moves is 2