I'm working on Permutations in Java. My program to is supposed to generate all possible permutations of an array with length n and arrange in r number of permutations.
Here is an example. For an array with these 12 elements
string Mywords[] =("love" ,"guy" ,"cow","hen","dog","antelope","cat" "rat",welcome","thank","you","all");
Where
n=12, r=7
7 of the 12 elements are selected to create 12 possible variations of the array.
=>> output may be in form (possible case)
- (love, guy, cow, hen, dog, antelope, cat)
- (love, cow, guy, hen, dog, antelope, cat)
- (love, hen, guy, cow, dog, antelope, cat)
- (love, dog, hen, guy, cow, antelope, cat)
- (love, thank, dog, hen, guy, cow, welcome)
- :
- :
- :
- :
- :
- :
- P(n,r)
How can I print all possible results?
The below code is adapted from the answer to this SO question.
print all possible permutations of r elements in a given integer array of size n in Java
That question uses a list of integers. In the below code I essentially only replaced
IntegerwithString.Note that the number of permutations of 7 elements from a list of 12 elements is close to 3.5 million which will take time. Hence in the below code I generate permutations of three elements from a five element list.
Running the above code produces the following output.