Skip to content

Instantly share code, notes, and snippets.

@aryan-gupta
Last active April 25, 2017 00:11
Show Gist options
  • Save aryan-gupta/9413ddb04aae157d86cb6feeeec9ed70 to your computer and use it in GitHub Desktop.
Save aryan-gupta/9413ddb04aae157d86cb6feeeec9ed70 to your computer and use it in GitHub Desktop.
This algorithm creates combinations of different lengths using a tree.
#include <vector>
#include <iostream>
using namespace std;
typedef vector<int> IV;
IV master; // master vector of ints (or whatever)
void func(int start, int depth, const int &fDepth, IV vec, vector<IV> &pos) {
vec.push_back(master[start]); // store the current node in vector
if(depth == fDepth) { // if we are at the depth we need to go to then ...
pos.push_back(vec); // ... add the accumulated nodes ...
return; // ... and exit
}
for(int i = start + 1; i < master.size(); ++i) // for each node below us ...
func(i, depth + 1, fDepth, vec, pos); // ... spawn a func
// if we reached an end node then exit
}
int main() {
master = {1, 2, 3, 4, 5};
vector<IV> pos; // stores all the combinations of master vector
IV vec; // stores the accumulated nodes
for(int maxDepth = 0; maxDepth < master.size(); ++maxDepth)
for(int start = 0; start < master.size(); ++start)
func(start, 0, maxDepth, vec, pos);
// output all the combinations of master
for(IV& tmpIV : pos) {
for(int tmpInt : tmpIV)
cout << tmpInt << " ";
cout << endl;
}
return 0;
}
@aryan-gupta
Copy link
Author

aryan-gupta commented Apr 25, 2017

For Example: for a master list of

1 2 3 4 5

It would create the following combinations:

1
2
3
4
5
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
1 2 3 4 5

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