......................

Program to Generate Possible Unique Combinations of Specific Length for a Given Input

Posted by Unknown On Sunday, May 29, 2011 0 comments

/**************************************************************************
APPLICATION  : Program to Generate Possible Unique Combinations of Specific Length for a Given Input
CODED BY       : Ankit Pokhrel
COMPILED ON : Borland C++ Ver 5.02
DATE             : 2011 - April - 20
**************************************************************************/

#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <fstream.h>

char originalString[15]; //Holds Original String
int n,length;
ofstream outFile; //Output File Pointer

long power(int x,int y) //Function to calculate the Power
{
long retValue = 1;
for(int i = 0;i < y;i++)
   retValue = retValue * x;
return retValue;
}

void Compute(char *str,int pos) //Function to Compute the Possible Unique Combinations
{
static int level = -1; //Current Level or Depth of Recursion
int preLevel; //Previous Level
if(pos >= length) //If the Value of Position(pos) is >= length then Return
  return;

level++; //Increase Level
preLevel = level; //Update Previous Level
for(int i = 0;i < n;i++)
   {
    str[pos] = originalString[i];
    Compute(str,pos+1); //Compute Next Position
    if(preLevel == level)
     {
      cout << str << '\t'; //Print Output
      outFile << str << '\n'; //Save Output to File
     }
   }
}

int main()
{
char temp[15],tempStr[15],fileName[15];
cout << "Enter Characters: ";
cin >> originalString;
cout << "Enter Length: ";
cin >> length; //Length of the String
cout << "\nEnter Filename to Save : ";
cin >> fileName;
outFile.open(fileName); //Open File

n = strlen(originalString); //Find the Length of Original String

cout << endl << "The Number of Possible Unique Combinations : ";
cout << power(length,n) << endl; //Call Functon power()
getch();
int i;
for(i = 0;i < length;i++)
  temp[i] = originalString[0]; //If Input is abc,Start with aaa and Proceed
temp[i] = '\0';

strcpy(tempStr,temp);
cout << endl;
Compute(temp,0); //Find and Print all Unique Combinations
outFile.close(); //Close the File

cout << "\n\n\n\n";
cout.width(38);
cout << "Output saved to : \\" << fileName << endl;
cout.width(45);
cout << "Press any key to halt...";
getch();
return 0;
}

OUTPUT

Lets check this program to generate unique combinations of length 3 for character ABC

Recursion Tree

Output

Download Original File

Unique Combinations

No comments:

Post a Comment

Leave Feedback about this BLOG