Created
March 26, 2019 12:42
-
-
Save miquelramirez/6b5ecb8286f495597ef5fb303ae32ef4 to your computer and use it in GitHub Desktop.
Fast Combinations in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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