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.)
I solved the issue by modifying another combination method I found on this site.
Here's the code for it:
#include <iostream>
#include <vector>
using namespace std;
vector<int> people;
vector<int> combination;
void pretty_print(const vector<int>& v) {
static int count = 0;
cout << "combination no " << (++count) << ": [ ";
for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
cout << "] " << endl;
}
void go(int offset, int k, int end, bool outermost = true) {
if (k == 0) {
pretty_print(combination);
return;
}
for (int i = offset; i <= people.size() - k; ++i) {
combination.push_back(people[i]);
go(i+1, k-1, end, false);
combination.pop_back();
if(outermost && i == end) return;
}
}
int main() {
int k = 3, end = 1;
people = {1, 2, 3, 4, 5};
go(0, k, end);
return 0;
}
offset controls start and end controls the end. For loop going on at the outside most layer controls the first element selected for the combination and it progresses as the function recurses. If statement inside the for loop checks if the wanted line is reached and returns the function prematuraly as needed.