Observe the following code:
#include <vector>
#include <iostream>
#include <string>
template <typename T>
void print_2d_vector(std::vector<std::vector<T>>& v)
{
for(int i = 0; i < v.size(); i++)
{
std::cout << "{";
for(int j = 0; j < v[i].size(); j++)
{
std::cout << v[i][j];
if(j != v[i].size() - 1)
{
std::cout << ", ";
}
}
std::cout << "}\n";
}
}
template <typename T>
struct permcomb2
{
std::vector<std::vector<T>> end_set;
std::vector<T>* data;
permcomb2(std::vector<T>& param) : data(¶m) {}
void helpfunc(std::vector<T>& seen, int depth)
{
if(depth == 0)
{
end_set.push_back(seen);
}
else
{
for(int i = 0; i < (*data).size(); i++)
{
seen.push_back((*data)[i]);
helpfunc(seen, depth - 1);
seen.pop_back();
}
}
}
};
template <typename T>
std::vector<std::vector<T>> permtest(std::vector<T>& data, int subset_size)
{
permcomb2<T> helpstruct(data);
std::vector<T> empty {};
helpstruct.helpfunc(empty, subset_size);
return helpstruct.end_set;
}
using namespace std;
int main()
{
std::vector<std::string> flavors {"Vanilla", "Chocolate", "Strawberry"};
auto a1 = permtest(flavors, 2);
cout << "Return all combinations with repetition\n";
print_2d_vector(a1);
return 0;
}
Running this code leads to the following output:
Return all combinations with repetition
{Vanilla, Vanilla}
{Vanilla, Chocolate}
{Vanilla, Strawberry}
{Chocolate, Vanilla}
{Chocolate, Chocolate}
{Chocolate, Strawberry}
{Strawberry, Vanilla}
{Strawberry, Chocolate}
{Strawberry, Strawberry}
Notice how this code DOES NOT what it claims! Instead of returning all combinations repeating the given size of the subset (target), it instead returns all permutations repeating the given size of the subset. Of course, a way to get combinations would be to generate all the permutations, as I did, and then scroll to delete all but one of them, which are each other's permutations. But I am sure that this is absolutely NOT the most effective way to do this.
, , . , . , , "helpfunc", .
, :
Return all combinations with repetition
{Vanilla, Vanilla}
{Vanilla, Chocolate}
{Vanilla, Strawberry}
{Chocolate, Chocolate}
{Chocolate, Strawberry}
{Strawberry, Strawberry}
, , ?