Skip to content

Instantly share code, notes, and snippets.

@c650
Created June 26, 2016 17:52
Show Gist options
  • Save c650/a29575840cb67adcaab1907155466dc7 to your computer and use it in GitHub Desktop.
Save c650/a29575840cb67adcaab1907155466dc7 to your computer and use it in GitHub Desktop.
makes combinations of vector elements
#include <iostream>
#include <vector>
#include <cstdio>
template <typename T>
void combination(std::vector<T>& vec, std::vector<T>& tmp, int start, int end, int idx, int r);
int main() {
std::vector<unsigned int> vec = {1,2,3,4,5};
std::vector<unsigned int> tmp(vec.size());
combination(vec, tmp, 0, vec.size() - 1, 0, 2);
return 0;
}
template <typename T>
void combination(std::vector<T>& vec, std::vector<T>& tmp, int start, int end, int idx, int r) {
if (r == idx) {
for (int i = 0; i < r; i++) {
std::cout << tmp[i] << " ";
}
std::cout << std::endl;
return;
}
for (int i = start; i <= end && end-i+1 >= r - idx; i++) {
tmp[idx] = vec[i];
combination( vec , tmp , i+1 , end , idx+1 , r );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment