Untitled

 avatar
unknown
plain_text
6 months ago
1.7 kB
3
Indexable
void TowersOfHanoi::moveDisks(int N, Stackt<int>& source, Stackt<int>& target, Stackt<int>& auxiliary) {
    // Student Task: Implement the moveDisks function
    // - This is a recursive function that moves N disks from the source peg to the target peg using the auxiliary peg.
    // - Base case: If N is 1, move a disk directly from the source to the target.
    // - Recursive case:
    //   1. Move N-1 disks from the source to the auxiliary peg using the target peg.
    //   2. Move the Nth disk from the source to the target peg.
    //   3. Move the N-1 disks from the auxiliary peg to the target peg using the source peg.
    // - After each move, increment moveCount and call displayPegs to show the current state of pegs.
    if (N == 1) {
        // Move one disk directly from source to target
        target.push(source.pop()); // since we have a stack i noticed we only need to move two elements so why not pop and push
        moveCount++;
        displayPegs();
       return;
    } else {

        // Note: since asked to output after each move, code might be repeated! If the opposite is ned remove 2 of the display and moveCount++.

        // Move N-1 disks from source to auxiliary peg using target peg
        moveDisks(N - 1, source, auxiliary, target);
        moveCount++;
        displayPegs();

        // Move the Nth disk from source to target peg
        target.push(source.pop());
        moveCount++;
        displayPegs();

        // Move N-1 disks from auxiliary to target peg using source peg
        moveDisks(N - 1, auxiliary, target, source);
        moveCount++;
        displayPegs();
    }
}
Editor is loading...
Leave a Comment