void TowerOfHanoi::solve(unsigned int n, Peg from, Peg to, Peg aux) { if (n == 1) { moveDisk(from, to); return; } solve(n-1, from, aux, to); moveDisk(from, to); solve(n-1, aux, to, from); }
void hanoi( int N, Tower *source, Tower *dest,Tower *aux ) { if (N > 0 ) { hanoi(N - 1, source, aux, dest); moveDisk(source,dest); hanoi(N - 1, aux, dest, source); } }
// Recursive resolution of the towers of hanoi // // inputs: // - orgPeg: origin peg of the disks, // - destPeg: destination peg of the disks, // - tempPeg: the last peg serves as an intermediate for moving // disks from the origin to the destination, // - N: number of disks to move from the origin void TowersOfHanoi::playNDisks(char orgPeg, char destPeg, char tempPeg, int N) { #ifdef RAW_PROFILING RawProfiling::RawProfiling::TowersOfHanoi_playNDisks_counter++; RawProfiling::RawProfiling theProfiling(RawProfiling::RawProfiling::TowersOfHanoi_playNDisks_chronograph); #endif // we should isolate the test (N == 1) to move the only disk from the // origin to the destination, but we don't care about too much calls. if (N >= 1) { // Move (N - 1) disks from the origin to the temporary location playNDisks(orgPeg, tempPeg, destPeg, N - 1); // The top disk of the origin is moved to the destination moveDisk(orgPeg, destPeg); // Move the (N - 1) disks we have just put at the temporary location // to the destination playNDisks(tempPeg, destPeg, orgPeg, N - 1 ); } }
void runIt(){ //declare the number of disks for tower of Hanoi int numDisks; printf("Enter the number of Disks: "); scanf("%d",&numDisks); int source[numDisks], spare[numDisks], dest[numDisks]; //initialize pegs for (int i = 0; i < numDisks; i++) { source[i] = i+1; //Smallest element is 1 and largest is N dest[i] = spare[i] = 0; //Empty } //This formulaSteps counts the minimum number of steps //needed for tower of hanoi problem int steps = formulaSteps(numDisks); //This variable is used to check //the move needed from one peg to other int mvPegs = -1; //used for printMove function bool isEven; if (numDisks%2 == 0) isEven = true; else isEven = false; //These variable will keep track of the head of the peg int head1 = 0, head2 = numDisks-1, head3 = numDisks - 1; for (int step = 1; step <= steps; step++) { mvPegs = step%3; // Result = 1, 2, 0; 1, 2, 0 ... //I am using simple array; Just a small check if (inBound(head1, numDisks) && inBound(head2, numDisks) && inBound(head3, numDisks)){ if (mvPegs == 1) //Peg 1 -> Peg 3 or Peg 3 -> Peg 1 { moveDisk(numDisks, & head1, & head3, source, dest); printMove(source, spare, dest, numDisks, isEven); } else if (mvPegs == 2) // Peg 1 -> Peg 2 or Peg 2 -> Peg 1 { moveDisk(numDisks, & head1, & head2, source, spare); printMove(source, spare, dest, numDisks, isEven); } else if (mvPegs == 0) // Peg 2 -> Peg 3 or Peg 3 -> Peg 2 { moveDisk(numDisks, & head2, & head3, spare, dest); printMove(source, spare, dest, numDisks, isEven); }else { cout << "CODE 1111" << endl; } } else { break; } } }