code:
/*************************************************************
Permuation Assignment
Take an input string N of ABC...XYZ
and print out every permutation
of that input string.
Blayne Bradley
0463737
*************************************************************/
#include <iostream>
#include <cstring>
using namespace std;
//Globals, constants, arrays
const int MAX = 27;
char Beta[MAX];
char Alpha[MAX] = { "ABCDEFGHIJKLMNOPQRSTUWVXYZ" };
char App[MAX] = "\0";
int N = 0;
//Functions
void Perm( char Beta[MAX], char append[MAX] );
void main()
{
int in = 0;
cout << "Please select how many letters you wish to"
<< " permute N: ";
cin >> in; // N
// Error checking
while ( in < 0 || in > 26 )
{
cout << "Invalid Input: Please select how many letters you wish to"
<< " permute N: ";
cin >> in;
}
cout << " N Letters are: ";
// copying the selected N letters into the
// array passed to the Perm function.
for ( int counter = 0; counter < in; counter++)
{
Beta[counter] = Alpha[counter];
// to show the original string
cout << Beta[counter];
}
cout << endl;
cout << "********************************" << endl << endl;
//the Permutation function
Perm(Beta, App);
cout << endl;
cout << N << " Permuations: " << in << " Letters Chosen" << endl << endl;
system("pause");
}
/*
recursively do permutations.
*/
void Perm( char StringB[MAX], char To_App[MAX] )
{
// find the length of the string passed
int len = strlen(StringB);
if ( len > 0 )
{
for ( int count = 0; count < len; count++ )
{
// create a pointer array because length at runtime
// isnt definable so it is more efficient to create
// a pointer array dynamically with a more specific
// size.
char* string1 = new char[len+1];
int counter;
int next;
/* within this loop for the length of the loop
assign letters from StringB -> String1
*/
for ( counter = 0, next = 0; counter < len; counter++, next++ )
{
if ( counter == count )
{
string1[counter] = StringB[++next];
continue;
}
else
{
string1[counter] = StringB[next];
}
}
string1[counter] = '\0'; //appending null value to end of array
int length = strlen(To_App);
char* To_App1 = new char [length+2]; //creating the append pointer array
//dynamically
// copy the passed Append string to the
// new Append string at length size.
strncpy(To_App1, To_App, length );
To_App1[length] = StringB[count];
To_App1[length+1] = '\0';
// Perm calls Perm recursively here
Perm( string1, To_App1 );
// delete the used pointer arrays as you pop off the stack.
delete []string1;
delete []To_App1;
}
}
else
{
// Cout each completed
// Permuation when size is zero.
cout << To_App << endl;
N++;
}
}