vendredi 4 octobre 2019

Is there a way to print the total number of steps from an if statement?

I'm writing some code for the Towers of Hanoi for a homework problem in my Intro to C class. I've got the actual program working but as an addendum, I'd like to have the code print out the number of steps taken i.e. "The total number of steps is 31". I then want to compare them to theoretical number of steps (e.g. steps = (2^n)-1 where n is the number of disks) and be able to verify the program is running correctly for larger values of n.

So far I have been able to implement code to print out the expected number of steps required but I am unsure how to proceed with getting to console to print the actual number of steps.

void towers(int, char, char, char);
int main()
{
int n;
    printf("Number of disks:");
scanf("%d", &n);
int result = (pow(2,n)-1);
printf("\nExpected number of moves required is %d", result);
towers(n, 'A', 'C', 'B'); //moving n disks from A to C using B as the intermediate
return 0;
}

result calls the power function from and returns to expected number of steps before the towers function runs.

void towers(int n, char from_peg, char to_peg, char other_peg)
{
    if (n == 1) //breaking condition
    {
    printf("\n Move disk 1 from peg %c to peg %c", from_peg, to_peg);
return;
    }
    towers(n-1, from_peg, other_peg, to_peg); //moving n-1 disks from A to B using C as the intermediate
    printf("\n Move disk %d from peg %c to peg %c", n, from_peg, to_peg);
    towers(n-1,other_peg,to_peg,from_peg); //moving n-1 disks from B to C using A as the intermediate
}

The loop returns the solution to the towers puzzle printing the move each time.

Ideally I would like to have some line run after the loop is completely stating "The total number of moves required is (number of steps)" and then compare the expected result to the actual result (i.e. expected step number == actual step number is True).

Aucun commentaire:

Enregistrer un commentaire