Question

In: Computer Science

Tower of Hanoi problem please use this code #pragma once #include #include #include #include using namespace...

Tower of Hanoi problem

please use this code

#pragma once

#include

#include

#include

#include

using namespace std;

class TowersOfHanoi

{

friend ostream& operator<<(ostream& sink, const TowersOfHanoi& towers);

public:

//constructor

TowersOfHanoi();

//custom methods

unsigned move(unsigned new_n_disks = 6, ostream& new_sink = cout);

private:

//custom methods

void move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux);

//temporary variable

unsigned _n_moves;

//data

const unsigned _n_towers;

stack* _tower;

};

#include "TowersOfHanoi.h"

//

ostream& operator<<(ostream& sink, const TowersOfHanoi& hanoi)

{

for (unsigned index = 0; index < hanoi._n_towers; index++)

{

sink << index + 1 << ": ";

stack temp;

while (!hanoi._tower[index].empty())

{

unsigned top = hanoi._tower[index].top();

hanoi._tower[index].pop();

temp.push(top);

}

while (!temp.empty())

{

unsigned top = temp.top();

temp.pop();

hanoi._tower[index].push(top);

sink << top << ' ';

}

sink << endl;

}

sink << "---" << endl;

return sink;

}

TowersOfHanoi::TowersOfHanoi(void)

:_n_towers(3)

{

_tower = NULL;

_n_moves = 0;

}

unsigned TowersOfHanoi::move(unsigned n_disks, ostream& sink)

{

if(n_disks < 1)

throw string("TowersOfHanoi:move - new-n-disks is 0 or negative");

_tower = new stack[_n_towers];

for(unsigned disk = n_disks; disk > 0; disk--)

_tower[0].push(disk);

  

_n_moves = 0;

sink << *this << endl;

move_aux(sink, n_disks, 0, 2, 1);

delete [] _tower;

return _n_moves;

}

void TowersOfHanoi::move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux)

{

if(n_disks > 1)

{

//move n -1 disks from source to auxilliary

//move_ 1 disk from source to destination

//mov n -1 disks from axuilliary to destination

}

else

{

unsigned top = _tower[srce].top();

_tower[srce].pop();

_tower[dest].push(top);

_n_moves++;

sink << *this << endl;

}

}

// testTowersOfHanoi.cpp : Defines the entry point for the console application.

//

#include

#include

#include "towersofhanoi.h"

using namespace std;

int main()

{

try

{

TowersOfHanoi towers;

for (unsigned n_disks = 1; n_disks <= 10; n_disks++)

{

cout << towers.move(n_disks) << " moves " << endl;

system("pause");

cout << endl << endl;

}

}

catch(string message)

{

cout << message << endl;

}

catch(...)

{

cout << "something is dreadfully wrong" << endl;

}

system("pause");

return 0;

}


that's all

Solutions

Expert Solution

// this is a C Program

#include <stdio.h>

#include <math.h>

#include <stdlib.h>

#include <limits.h>

struct Stack

{

unsigned capacity;

int top;

int *array;

};

// function to create a stack of given capacity.

struct Stack* createStack(unsigned capacity)

{

    struct Stack* stack =

        (struct Stack*) malloc(sizeof(struct Stack));

    stack -> capacity = capacity;

    stack -> top = -1;

    stack -> array =

        (int*) malloc(stack -> capacity * sizeof(int));

    return stack;

}

// Stack is full when top is equal to the last index

int isFull(struct Stack* stack)

{

return (stack->top == stack->capacity - 1);

}

// Stack is empty when top is equal to -1

int isEmpty(struct Stack* stack)

{

return (stack->top == -1);

}

// Function to add an item to stack. It increases

// top by 1

void push(struct Stack *stack, int item)

{

    if (isFull(stack))

        return;

    stack -> array[++stack -> top] = item;

}

// Function to remove an item from stack. It

// decreases top by 1

int pop(struct Stack* stack)

{

    if (isEmpty(stack))

        return INT_MIN;

    return stack -> array[stack -> top--];

}

//Function to show the movement of disks

void moveDisk(char fromPeg, char toPeg, int disk)

{

    printf("Move the disk %d from \'%c\' to \'%c\'\n",

        disk, fromPeg, toPeg);

}

// Function to implement legal movement between

// two poles

void moveDisksBetweenTwoPoles(struct Stack *src,

            struct Stack *dest, char s, char d)

{

    int pole1TopDisk = pop(src);

    int pole2TopDisk = pop(dest);

    // When pole 1 is empty

    if (pole1TopDisk == INT_MIN)

    {

        push(src, pole2TopDisk);

        moveDisk(d, s, pole2TopDisk);

    }

    // When pole2 pole is empty

    else if (pole2TopDisk == INT_MIN)

    {

        push(dest, pole1TopDisk);

        moveDisk(s, d, pole1TopDisk);

    }

    // When top disk of pole1 > top disk of pole2

    else if (pole1TopDisk > pole2TopDisk)

    {

        push(src, pole1TopDisk);

        push(src, pole2TopDisk);

        moveDisk(d, s, pole2TopDisk);

    }

    // When top disk of pole1 < top disk of pole2

    else

    {

        push(dest, pole2TopDisk);

        push(dest, pole1TopDisk);

        moveDisk(s, d, pole1TopDisk);

    }

}

//Function to implement TOH puzzle

void tohIterative(int num_of_disks, struct Stack

            *src, struct Stack *aux,

            struct Stack *dest)

{

    int i, total_num_of_moves;

    char s = 'S', d = 'D', a = 'A';

    //If number of disks is even, then interchange

    //destination pole and auxiliary pole

    if (num_of_disks % 2 == 0)

    {

        char temp = d;

        d = a;

        a = temp;

    }

    total_num_of_moves = pow(2, num_of_disks) - 1;

    //Larger disks will be pushed first

    for (i = num_of_disks; i >= 1; i--)

        push(src, i);

    for (i = 1; i <= total_num_of_moves; i++)

    {

        if (i % 3 == 1)

        moveDisksBetweenTwoPoles(src, dest, s, d);

        else if (i % 3 == 2)

        moveDisksBetweenTwoPoles(src, aux, s, a);

        else if (i % 3 == 0)

        moveDisksBetweenTwoPoles(aux, dest, a, d);

    }

}

// Driver Program

int main()

{

    // Input: number of disks

    unsigned num_of_disks = 3;

    struct Stack *src, *dest, *aux;

    // Create three stacks of size 'num_of_disks'

    // to hold the disks

    src = createStack(num_of_disks);

    aux = createStack(num_of_disks);

    dest = createStack(num_of_disks);

    tohIterative(num_of_disks, src, aux, dest);

    return 0;

}



Related Solutions

Tower of Hanoi problem complete the problems please use this code #pragma once #include <iostream> #include...
Tower of Hanoi problem complete the problems please use this code #pragma once #include <iostream> #include <stack> #include <string> #include <vector> using namespace std; class TowersOfHanoi { friend ostream& operator<<(ostream& sink, const TowersOfHanoi& towers); public: //constructor TowersOfHanoi(); //custom methods unsigned move(unsigned new_n_disks = 6, ostream& new_sink = cout); private: //custom methods void move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux); //temporary variable unsigned _n_moves; //data const unsigned _n_towers; stack<unsigned>* _tower; }; #include "TowersOfHanoi.h" // ostream& operator<<(ostream& sink, const...
Tower of Hanoi - Java Code Use three rods labeled A, B, and C Use three...
Tower of Hanoi - Java Code Use three rods labeled A, B, and C Use three discs labels 1 (smallest), 2 (medium size), and 3 (largest disc) The program prompts you to enter the starting rod (A, B, or C) The program prompts you to enter the ending rod (A, B, or C, but cannot be same rod as entered as starting rod) The starting rod has discs 1, 2, 3, where 1 is on top of 2 is on...
Write two Java programs ( Iterative and Recursive programs ) that solves Tower of Hanoi problem?use...
Write two Java programs ( Iterative and Recursive programs ) that solves Tower of Hanoi problem?use 4 disks and 3 bars
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; // constants const int FINAL_POSITION = 43; const int INITIAL_POSITION = -1; const int NUM_PLAYERS = 2; const string BLUE = "BLUE"; const string GREEN = "GREEN"; const string ORANGE = "ORANGE"; const string PURPLE = "PURPLE"; const string RED = "RED"; const string YELLOW = "YELLOW"; const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW}; const int NUM_COLORS = 6; // names...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std;...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std; void leapYear(int x); int main() { int x; cout << "Enter a year: "; cin >> x; leapYear (x);   return 0; } void leapYear(int x ) {    if (x % 400 == 0)    {    cout << "This is a leap Year";}    else if    ((x % 4 == 0) && (x % 100 != 0))    {    cout <<...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace std; AVLTree::AVLTree() { root = NULL; } AVLTree::~AVLTree() { delete root; root = NULL; } // insert finds a position for x in the tree and places it there, rebalancing // as necessary. void AVLTree::insert(const string& x) { // YOUR IMPLEMENTATION GOES HERE } // remove finds x's position in the tree and removes it, rebalancing as // necessary. void AVLTree::remove(const string& x) {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell { int val; Cell *next; }; int main() { int MAX = 10; Cell *c = NULL; Cell *HEAD = NULL; srand (time(NULL)); for (int i=0; i<MAX; i++) { // Use dynamic memory allocation to create a new Cell then initialize the // cell value (val) to rand(). Set the next pointer to the HEAD and // then update HEAD. } print_cells(HEAD); }
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char plain[50], cipher[50]="", decrypt[50]=""; int subkeys[50], len;       cout<<"Enter the plain text:"<<endl; cin>>plain;    cout<<"Enter the first subkey:"<<endl; cin>>subkeys[0];    _strupr(plain);    len = strlen(plain);    /**********Find the subkeys**************/    for(int i=1; i<len; i++) { if ((plain[i-1]>='A') && (plain[i-1]<='Z')) { subkeys[i] = plain[i-1]-65; } }    /****************ENCRYPTION***************/       for(int i=0; i<len; i++) { if ((plain[i]>='A') && (plain[i]<='Z')) {    cipher[i] = (((plain[i]-65)+subkeys[i])%26)+65; }...
In Lecture 5, we discussed how to solve the Tower of Hanoi problem (Exercise 5.36 in...
In Lecture 5, we discussed how to solve the Tower of Hanoi problem (Exercise 5.36 in the textbook). Consider the following problem variant in which one extra constraint has been added: There are three pegs and n disks of different sizes. Initially, all disks are on the leftmost peg and arranged in order of decreasing size, with the smallest disk on top. The task is to move all the disks to the rightmost peg, under the constraints that: • Only...
What is the flowchart for this code. Thank You! #include<iostream> #include<iomanip> #include<string> #include<cmath> using namespace std;...
What is the flowchart for this code. Thank You! #include<iostream> #include<iomanip> #include<string> #include<cmath> using namespace std; float series(float r[], int n) {    float sum = 0;    int i;    for (i = 0; i < n; i++)        sum += r[i];    return sum; } float parallel(float r[], int n) {    float sum = 0;    int i;    for (i = 0; i < n; i++)        sum = sum + (1 / r[i]);...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT