1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
#include <list>
#include <fstream>
using namespace std;
using std::copy;
using std::cout;
using std::endl;
using std::vector;
using std::list;
list<char>prueba;
template<typename T>inline list<T>&operator<<(list<T>&prueba, const T &val)
{
prueba.push_back(val);
return prueba;
};
template<typename T>list<T> convierte(const vector<T>&elems,const vector<T>&poss,const T &val);
template<typename T>ostream &operator<<(ostream &o,const vector<T>&v);
template<typename T>ostream &operator<<(ostream &o,const list<T>&prueba);
void combinations_recursive(const vector<char> &elems, unsigned long req_len,
vector<unsigned long> &pos, unsigned long depth,
unsigned long margin)
{
// Have we selected the number of required elements?
if (depth >= req_len) {
for (unsigned long ii = 0; ii < pos.size(); ++ii)
/*cout << elems[pos[ii]];
cout << endl;*/
prueba=convierte(elems[pos[ii]]);
return;
}
//prueba=convierte(elems);
// Are there enough remaining elements to be selected?
// This test isn't required for the function to be correct, but
// it can save a good amount of futile function calls.
if ((elems.size() - margin) < (req_len - depth))
return;
// Try to select new elements to the right of the last selected one.
for (unsigned long ii = margin; ii < elems.size(); ++ii) {
pos[depth] = ii;
combinations_recursive(elems, req_len, pos, depth + 1, ii + 1);
}
return;
}
void combinations(const vector<char> &elems, unsigned long req_len)
{
assert(req_len > 0 && req_len <= elems.size());
vector<unsigned long> positions(req_len, 0);
combinations_recursive(elems, req_len, positions, 0, 0);
}
const unsigned long num_elements = 7;
const unsigned long comb_len = 6;
int main()
{
vector<char> elements(num_elements);
char elements_str[num_elements + 1] = "abcdefg";
copy(elements_str, elements_str + num_elements, elements.begin());
combinations(elements, comb_len);
cout<<prueba<<endl;
return 0;
}
template<typename T>list<T> convierte(const vector<T>&elems,const vector<T>&poss,const T &val)
{
list<T>prueba;
typename vector<T>::const_iterator i,j;
for(i= elems.begin();i !=elems.end();++i){
for(j=poss.begin(); j !=poss.end();++j)
prueba<< *i[j[val]];
}
return prueba;
}
template<typename T> ostream &operator<<(ostream &o, const vector<T>&v)
{
typename vector<T>::const_iterator i;
for (i=v.begin();i !=v.end(); ++i)
o<< *i <<' ';
return o;
}
template<typename T>ostream &operator<<(ostream &o, const list<T>&prueba)
{
typename list<T>::const_iterator i;
for(i=prueba.begin();i !=prueba.end();++i)
o<<*i<<' ';
return o;
}
|