Skip to content

Instantly share code, notes, and snippets.

@fschr
Created October 12, 2016 19:54
Show Gist options
  • Save fschr/7bbc65bc4ad2fddf2466d182f7a91144 to your computer and use it in GitHub Desktop.
Save fschr/7bbc65bc4ad2fddf2466d182f7a91144 to your computer and use it in GitHub Desktop.
kinda fast std::vector combinations function c++
#include <stdint.h>
#include <stdlib.h>
#include <vector>
#define uint32 uint32_t
std::vector<std::vector<uint32>> combinations(std::vector<uint32> src, uint32 r) {
std::vector<std::vector<uint32>> cs;
if (r == 1) {
for (auto i = 0; i < src.size(); i++) {
std::vector<uint32> c;
c.push_back(src[i]);
cs.push_back(c);
}
return cs;
}
uint32* places = (uint32*)malloc(sizeof(uint32) * r);
for (auto i = 0; i < r; i++) places[i] = i;
while (true) {
// push_back another combination
std::vector<uint32> c; c.reserve(r);
for (auto i = 0; i < r; i++) {
c.push_back(src[places[i]]);
}
cs.push_back(c);
// update places
for (auto i = 0; i < r-1; i++) {
places[i]++;
if (places[i+1] == places[i]) {
places[i] = i;
if (i == r-2) places[r-1]++;
continue;
}
break;
}
if (places[r-1] == src.size()) break;
}
free(places);
return cs;
}
@wesboyt
Copy link

wesboyt commented Feb 21, 2020

I think its about 30% slower than https://github.com/HowardHinnant/combinations/blob/master/combinations.h but I found it way simpler/easier to use.

@fschr
Copy link
Author

fschr commented Feb 21, 2020

thanks mayne

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment