I modified a code I've found on the internet to fit my needs. It calculates and prints all possible combinations of r elements in an array given size of N. Here's the code:
#include <iostream>
#include <vector>
void combinationUtil(std::vector<int> arr, std::vector<int> data, int start, int end, int index, int r);
void printCombination(std::vector<int> arr, int n, int r)
{
std::vector<int> data;
data.assign(r, 0);
combinationUtil(arr, data, 0, n-1, 0, r);
}
void combinationUtil(std::vector<int> arr, std::vector<int> data, int start, int end, int index, int r)
{
if (index == r)
{
for (int j = 0; j < r; j++)
std::cout << data.at(j) << " ";
std::cout << std::endl;
return;
}
for (int i = start; i <= end && end - i + 1 >= r - index; i++)
{
data.at(index) = arr.at(i);
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
int main()
{
std::vector<int> arr = {1, 2, 3, 4, 5};
int r = 3;
int n = arr.size();
printCombination(arr, n, r);
}
The output of it is:
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
I can modify the start value to 1 so the output can start from value 2 like so:
2 3 4
2 3 5
2 4 5
3 4 5
How can I achieve a similar effect for the end. For example if I wanted it to end before calculating combinations starting with value 2. I want to see a result like:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
I want to do this so I can utilize parallelizations for a larger scale function. I hope I could relay the idea clear enough. Thanks in advance. (Code compiles with some casting warnings. I just left it like this for an easier read for the reader.)