 Rings Tower Stack | 2007-02-02

Portfolio » Application Programming

Rings Movement between towers stack

// Written by [email protected]
#include <iostream>
using namespace std;

int print( int* t[], int nTower, int nRow){
const int TOP = nRow + 1; // TOP is nRow+1
for (int i = 0; i < nTower; i++){
cout << "Tower " << (char)t[i] <<" : "; // print the name of tower
for ( int j = 1; j <= t[i][TOP]; ++j)
cout << t[i][j] << " "; //print the rings in the tower
cout << endl;
}
return 0;
}
int main(){
int n; // number of rings
int* t; // declare array of pointers to int
int* s, *d, *i; // declare 3 pointers

cout << "Enter number of rings: ";
cin >> n;

t = new int[n + 2]; //
t = new int[n + 2]; // use 'new' to create array of size n+2
t = new int[n + 2]; //

*t = (int)'a'; //
*t = (int)'b'; // other three pointers point to the memories those store 'a','b','c'
*t = (int)'c'; //

s = t; //
d = t; // s/d/i is an array of n+2 ints
i = t; //

for (int i = 1; i <= n; i++){
s[i] = n - i + 1;
} // put n rings in the first array(t or we can call it tower 'a')

const int TOP = n + 1; // declare a const integer TOP
s[TOP] = n; // declare an array s of size TOP, and initialize the value of all elements

d[TOP] = i[TOP] = 0;

int* from, fromI, *to, toI; // declare two new pointers
from = s;                  // pointer f point to array s(t, tower a)
fromI = 0;                  // initialize fI
if (n % 2 == 1){      // if n is an odd number
to = d;              // pointer to point to array d(t, tower b)
toI = 1;          // initialize toI
}
else {                  // if n is a even number
to = i;              // pointer to point to array i(t, tower c)
toI = 2;
}
int can = 1; // declare and initialize integer can

int mCount = 1; // declare and initialize integer mCount

cout << "move # 1" << endl;
print(t, 3, n); // call function print
//main algorithm
while ( d[TOP] != n ){
cout << "move #" << ++mCount << " : transfer ring "<<can<< "from Tower " <<
(char)from<<" to Tower "<<(char)to<<endl;
to[ ++to[TOP] ] = from[ from[TOP]-- ];

print(t, 3, n);

int toPOI, toPTI;
if ( n % 2 == 1 ){
toPOI = (toI + 1) % 3;
****************************
}

else{
toPOI = toI - 1;
toPTI = toI - 2;
if (toPTI < 0){
toPTI += 3;
if (toPOI < 0)
toPOI += 3;
}
}

int* toPO = t[toPOI];
int* toPT = t[toPTI];
if (toPO[ toPO[TOP] ]  < toPT[ toPT[TOP] ]){
from = toPO;
fromI = toPOI;
}
else{
from = toPT;
fromI = toPTI;
}

int fromPOI, fromPTI;
if ( n % 2 == 1 ){
fromPOI = (fromI + 1) % 3;
fromPTI = (fromI + 2) % 3;
}
else{
fromPOI = fromI - 1;
fromPTI = fromI - 2;
if (fromPTI < 0){
fromPTI += 3;
if (fromPOI < 0)
fromPOI += 3;
}
}

int* fromPO = t[fromPOI];
if (fromPO[ fromPO[TOP] ] **************************** from[ from[TOP] ]){
to = fromPO;
toI = fromPOI;
}
else{
to = t[fromPTI];
toI = fromPTI;
}
can = from[ from[TOP] ];
}
for (int i = 0; i < 3; ++i)
delete t[i];
}

*** indicated that some partial codes has been removed