Rudimentary Combination Generator

January 10, 2005

Just a simple example to combinate sequences given a character set.

#include <iostream>
#include <string>
#include <vector>
using namespace std;
 
void combinatePrint(vector<char>& working)
{
	for (int x = 0; x < working.size();x++)
	{
		cout << working[x];
	}
	cout << endl;
}
 
 
template <class Type>
void combinate(vector<Type>& set,int& size,vector<Type>& working)
{
	if (working.size() == size)
	{
		combinatePrint(working);
	}
	else
	{
		for (int x = 0; x < set.size();x++)
		{
			working.push_back(set[x]);
			combinate(set,size,working);
			working.erase(working.end()-1);
		}
	}
}
 
int main()
{
	// create the set of possible values for each column
	vector<char> set;
	set.push_back('a');
	set.push_back('b');
	set.push_back('c');
	set.push_back('d');
	set.push_back('e');
	set.push_back('f');
	set.push_back('g');
 
	// the working variable
	vector<char> word;
 
	// the size of words we want
	int size = 4;
 
	// generate every possible combination
	combinate(set,size,word);
}

Related Posts

2 Comments

Comment March 29, 2005 by anonymous
combinations are not the same a permutations. This code demonstrates combinations.
Comment December 17, 2005 by digitalpeer
You are entirely correct. I misused the word permute and changed it to "combinate."