Please finish the NON-RECURSIVE TOWER OF HANOI c++ code for the parts signalled
ID: 3775124 • Letter: P
Question
Please finish the NON-RECURSIVE TOWER OF HANOI c++ code for the parts signalled by //
#include <iostream>
#include<vector>
// NOTE: This program uses the vector container from the stl.
using namespace std;
void main(){
vector<int> t[3]; // three towers A,B,C represented as an array of 3 vectors
int n, candidate,to, from, move=0; // move counts the move number
cout<<"Please enter an ODD number of rings to move: ";
cin>>n;
cout<<endl;
//intitialize the 3 towers
for(int i=n+1;i>=1;i--)
t[0].push_back(i);
t[1].push_back(n+1);
t[2].push_back(n+1);
// initialize towers and candidate
from=0;
to=1;
candidate=1;
while( t[1].size()<n+1){ // there are still rings to transfer to tower B = t[1]
//write it
cout<<"move number "<<++move<<": Transfer ring <<candidate<<
" from tower "<< char(from+65)<<" to tower "<<char(to+65)<<endl;
//do it: move the disks around
1. Push the top of the “from” tower to the “to” tower
2. Remove the ring from the “from” tower
//get next “from tower” It’s not the most recent “to” – so which is it?
if( )
from= ; //
else
from= ; //
// get next “to tower”
if( ) //
to= ; //
else
to= ; //
//get next candidate
candidate= ; // it’s on the top of the current “from tower”
}
}
Explanation / Answer
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> t[3]; // three towers A,B,C represented as an array of 3 vectors
int n, candidate,to, from, move=0; // move counts the move number
cout<<"Please enter an ODD number of rings to move: ";
cin>>n;
cout<<endl;
//intitialize the 3 towers
for(int i=n+1;i>=1;i--)
t[0].push_back(i);
t[1].push_back(n+1);
t[2].push_back(n+1);
// initialize towers and candidate
from=0;
to=1;
candidate=1;
while(t[1].size()<n+1){ // there are still rings to transfer to tower B = t[1]
//write it
cout<<"move number "<<++move<<": Transfer ring "<<candidate<<" from tower "<< char(from+65)<<" to tower "<<char(to+65)<<endl;
t[from].pop_back();
t[to].push_back(candidate);
//do it: move the disks around
//get next “from tower” It’s not the most recent “to” – so which is it?
int A1, A2, x[5]={2,0,1,2,0};
for(int i=1;i<4;i++)
{ if(to==x[i])
{ A1= x[i-1];
A2= x[i+1];
}
}// To find A1 and A2 and hence "from"
if(t[A1].back() < t[A2].back() )
from=A1;
else
from=A2;
// get next “to tower”
for(int i=1;i<4;i++)
{ if(n%2!=0){
if(from==x[i])
{ if(t[from].back() < t[x[i+1]].back() )
to=x[i+1] ;
else
to= x[i-1] ;
}
}
else {
if(from==x[i])
{ if(t[from].back() < t[x[i-1]].back() )
to=x[i-1] ;
else
to= x[i+1] ;
}
}
}
//get next candidate
candidate= t[from].back() ;
}
}