Created
October 12, 2016 19:54
-
-
Save fschr/7bbc65bc4ad2fddf2466d182f7a91144 to your computer and use it in GitHub Desktop.
kinda fast std::vector combinations function 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 <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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks mayne