I want to create a C++ function that takes a vector and makes a all possible combinations, but no word is used more than once in one combination with defined length:
std::vector<std::string> words = {"random", "test", "word", "hello", "world"};
Output for 3words would be:
randomtestword
randomtesthello
randomtestworld
randomwordtest
randomwordhello
ranodmwordworld
...
For 4 words it would be:
randomtestwordhello
randomtestwordworld
...
I have this, which allows having one that one occurrence of the word in one combination:
void Generate::generate_combinations_with_repetition(int combination_length,
std::vector<std::string> words,
std::string combination,
int current) {
if (current == combination_length){
std::cout << combination << '\n';
return;
}
for (std::string word : words){
std::string current_combination = combination;
current_combination += word;
}
for (std::string word : words){
generate_combinations_with_repetition(combination_length, words, combination + word, current + 1);
}
}
and this is in for loop:
for (int i = 1; i <= combinations.size(); i++){
generate_combinations_with_repetition(i, combinations, "", 0);
}
But I need generate_combinations_without_repetition(...){...}
.
Related: stackoverflow.com/q/56768195/3966456
en.cppreference.com/w/cpp/algorithm/next_permutation
You can achieve this with only minor modifications. Instead of looping through all the words to perform the recursion, you should only loop through the remaining words. Change your end condition to print when
combination_length
is zero. When calling recursively, reducecombination_length
by 1 and pass the index of the next word ascurrent
.“I want” and “I need” are no questions. Often its just about phrasing things differently, and it always helps to have an actual question in your question
If I wanted or needed to generate all combinations of k elements from a set of size N, I would probably implement an iterable generator of combinations and then iterate over it. Because the number of combinations can be significant, it is reasonable to have a “streaming” implementation instead of one that stores the whole result. As already mentioned by others, stackoverflow is for questions; it is not a free coding service. As a side note, I would not want to work with a fellow engineer who hasn’t done this homework assignment (and many more).