Hello, I'm trying to make a program that prints all the possible permutations of some strings, where order matters and so following the formula: C= n!/(n-k)!.
Now, I have this code with which I can have all the permutations, but not for "n" different from "k", what instead I'm actually looking for.
Here is the code:
Code:
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort
#include <string> // std::string
#include <vector> // std::vector
int main () {
std::string sentence1 = " A Sentence number one ";
std::string sentence2 = " B Sentence number two ";
std::string sentence3 = " C Sentence number three ";
std::string sentence4 = " D Sentence number four ";
// Store all the elements in a container ( here a std::vector)
std::vector<std::string> myVectorOfStrings;
// In the vector we add all the sentences.
// Note : It is possible to do myVectorOfStrings.push_back("Some sentence");
myVectorOfStrings.push_back(sentence1);
myVectorOfStrings.push_back(sentence2);
myVectorOfStrings.push_back(sentence3);
myVectorOfStrings.push_back(sentence4);
// The elements must be sorted to output all the combinations
std::sort (myVectorOfStrings.begin(),myVectorOfStrings.end());
std::cout << "The 4! possible permutations with 4 elements:\n";
do {
//This printing can be improved to handle any number of sentences, not only four.
std::cout << myVectorOfStrings[0] << ' ' << myVectorOfStrings[1] << ' ' << myVectorOfStrings[2] << ' ' << myVectorOfStrings[3] << '\n';
} while ( std::next_permutation(myVectorOfStrings.begin(),myVectorOfStrings.end()) );
std::cout << "After loop: " << myVectorOfStrings[0] << ' ' << myVectorOfStrings[1] << ' ' << myVectorOfStrings[2] << ' ' << myVectorOfStrings[3] << '\n';
return 0;
}
Sorry if I make this message even longer, but just to clarify, that is an example of what I'm having:
Code:
1) string1 string2 string3 string4 string5 string6 string7 string8 string9 string10
2) string1 string2 string3 string4 string5 string6 string7 string8 string10 string9
3) string1 string2 string3 string4 string5 string6 string7 string9 string8 string10
4) string1 string2 string3 string4 string5 string6 string7 string9 string10 string8 ....
while that is the kind of thing I'm trying to obtain:
Code:
1) string1 string2 string3 string4 string5
2) string1 string2 string3 string4 string6
3) string1 string2 string3 string4 string7
4) string1 string2 string3 string4 string8
5) string1 string2 string3 string4 string9
6) string1 string2 string3 string4 string10
7) string1 string2 string3 string5 string4
8) string1 string2 string3 string5 string6
9) string1 string2 string3 string5 string7
10) string1 string2 string3 string5 string8
11) string1 string2 string3 string5 string9
12) string1 string2 string3 string5 string10....
As you can see, in the first one n=10 and k=10; in the second, n=10 but k=5 (5 "spaces").
Thank you in advance!