Skip to content

Instantly share code, notes, and snippets.

@miquelramirez
Created March 26, 2019 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miquelramirez/6b5ecb8286f495597ef5fb303ae32ef4 to your computer and use it in GitHub Desktop.
Save miquelramirez/6b5ecb8286f495597ef5fb303ae32ef4 to your computer and use it in GitHub Desktop.
Fast Combinations in C++
#include <algorithm>
#include <iostream>
#include <vector>
// Another incredible bit of C++ code
// https://stackoverflow.com/a/28698654/338107
//
// change std::vector<bool> for std::array<bool, N> to
// make your compiler work hard
void comb(int N, int K)
{
std::vector<bool> bitmask(K, 1); // K leading 1's
bitmask.resize(N, 0); // N-K trailing 0's
// print integers and permute bitmask
do {
for (int i = 0; i < N; ++i) // [0..N-1] integers
{
if (bitmask[i]) std::cout << " " << i;
}
std::cout << std::endl;
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}
int main()
{
comb(5, 1);
comb(5, 2);
comb(5, 3);
comb(5, 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment