Friday, May 21, 2010

Please help me to write a programming c to creat "hanoy Tower game"?

#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;limits.h%26gt;


#define FROM 1


#define TO 3


#define USING 2





void dohanoi(int N, int from, int to, int using)


{


if (N %26gt; 0)


{


dohanoi(N-1, from, using, to);


printf ("move %d --%26gt; %d\n", from, to);


dohanoi(N-1, using, to, from);


}


}





int main (int argc, char **argv)


{


long int N; if (argc != 2)


{


fprintf(stderr, "usage: %s N\n", argv[0]);


exit(1);


}





N = strtol(argv[1], (char **)NULL, 10);





/* a bit of error checking, LONG_XXX should be there in limits.h */





if (N == LONG_MIN || N == LONG_MAX || N %26lt;= 0) {


fprintf(stderr, "illegal value for number of disks\n");


exit(2);


}


dohanoi(N, FROM, TO, USING); exit(0);


}

Please help me to write a programming c to creat "hanoy Tower game"?
Recursive algorithm





* label the stands Source(Src),(intermediate)Intr,(destinat... Dest


* let n be the total number of discs


* number the discs from 1 (smallest, topmost) to n (largest, bottommost)





To move n discs from stand Src to stand Dest:





1. move n−1 plates from Src to Intr. This leaves plate #n alone on plate Src


2. move plate #n from Src to Dest


3. move n−1 plates from Intr to Dest so they sit on plate #n





The above is a recursive algorithm : to carry out steps 1 and 3, apply the same algorithm again for n−1. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1. This step, moving a single plate from stand Src to stand Dest , is trivial.





The Tower of Hanoi is a problem often used to teach beginning programming, in particular as an example of a simple recursive algorithm. It is also an example of an exponential time algorithm — for all but the smallest number of discs, it will take an impractically huge amount of time, even on the fastest computers in the world. There is no way to improve on this, because the minimum number of moves required to solve the puzzle is exponential in the number of plates ,which is 2n − 1, calculated by using recurrence relations,where n is the number of plates.


Code


SolveTowers()





// code for the recursive method


// count are number of plates,


// source stand,destination stand and intermediate stand


private void SolveTowers(int count, int source, int dest, int inter)


{


if (count == 1)


{


MoveFromTo(source, dest);//To Draw the action performed


TotalMoves++; //keep track of number of moves


}


else


{


//1- Move n-1 from source to intermediate stand using destination as a


//spare


solveTowers(count - 1, source, inter, dest);





//2-Move plate #n from Src to Dest


solveTowers(1, source, dest, inter);





//3-Move n−1 plates from intermediate to dest so they sit on plate #n


solveTowers(count - 1, inter, dest, source);


}


}


No comments:

Post a Comment