Skip to content

Instantly share code, notes, and snippets.

@msulima
Created October 26, 2013 13:54
Show Gist options
  • Save msulima/7169728 to your computer and use it in GitHub Desktop.
Save msulima/7169728 to your computer and use it in GitHub Desktop.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void ShowCollection(vector<char> &v);
void ShowCollection(int arr[], int size);
void testOnArrayOfInts();
void testOnVectorOfChars();
template<class BidirectionalIterator>
bool next_combination(BidirectionalIterator allRangeBegin,
BidirectionalIterator allRangeEnd,
BidirectionalIterator combinationRangeBegin,
BidirectionalIterator combinationRangeEnd);
int main() {
testOnArrayOfInts();
testOnVectorOfChars();
return 0;
}
void testOnVectorOfChars() {
char tab[10] = { 'A', 'B', 'C', 'E', 'G', 'I', 'M', 'O', 'P', 'Y' };
vector<char> vc(tab, tab + 3);
vector<char> vi(tab, tab + 6);
do {
ShowCollection(vc);
} while (next_combination(vi.begin(), vi.end(), vc.begin(), vc.end()));
}
void testOnArrayOfInts() {
int tab[6] = { 1, 2, 3, 4, 5, 6 };
int comb[3] = { 1, 2, 3 };
do {
ShowCollection(comb, 3);
} while (next_combination(tab, tab + 6, comb, comb + 3));
}
template<class BidirectionalIterator>
bool next_combination(BidirectionalIterator allRangeBegin,
BidirectionalIterator allRangeEnd,
BidirectionalIterator combinationRangeBegin,
BidirectionalIterator combinationRangeEnd) {
for (BidirectionalIterator lastInCombination = combinationRangeEnd - 1,
lastInRange = allRangeEnd - 1;
lastInCombination >= combinationRangeBegin;
--lastInCombination, --lastInRange) {
if (*lastInCombination < *lastInRange) {
BidirectionalIterator nextValue = find(allRangeBegin, allRangeEnd, *lastInCombination) + 1;
while (lastInCombination != combinationRangeEnd) {
*lastInCombination++ = *nextValue++;
}
return true;
}
}
return false;
}
void ShowCollection(vector<char> &v) {
for (vector<char>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it;
}
cout << " " << endl;
}
void ShowCollection(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i];
}
cout << " " << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment