Skip to content

Instantly share code, notes, and snippets.

@fmela
Created February 18, 2014 00:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmela/9061864 to your computer and use it in GitHub Desktop.
Save fmela/9061864 to your computer and use it in GitHub Desktop.
Enumerate every length-K combination of { 1, 2, ..., N } in ascending lexicographic order.
#include <vector>
#include <cassert>
// Call |f| with every length-K combination of { 1, 2, ..., N }, in ascending
// lexicographic order.
template<typename F>
void enumerate_combinations(size_t N, size_t K, const F& f) {
assert(K <= N);
std::vector<size_t> position;
// Initialize with initial position.
position.reserve(K);
for (size_t i = 1; i <= K; ++i) {
position.push_back(i);
}
for (;;) {
assert(position.size() == K);
for (size_t i = 0; i < K; ++i) {
assert(position[i] >= 1);
assert(position[i] <= N);
}
f(position);
// Update to next position.
while (!position.empty()) {
size_t limit = N + position.size() - K + 1;
if (++position.back() < limit) {
break;
}
position.pop_back();
}
if (position.empty())
break;
while (position.size() < K) {
position.push_back(position.back() + 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment