Using guava 12 Collections2.permutations(), I’m wondering if it’s possible to limit the size of the permutations ?
More precisely, I would like to get a list of k-sized permutations within a list of n elements, instead of getting a list of all n-sized permutations.
Currently, if I pass a list of 4 fruits, permutations() will currently return a list of 24 4-sized permutations although I’m only interested in retrieving, say, the 4 unique size 3 permutations.
Say I have a list of 4 fruits :
["Banana", "Apple", "Orange", "Peach"]
If I’m only interested in size 3 permutations, I’d like the following returned :
["Banana", "Apple", "Orange"]
["Banana", "Apple", "Peach"]
["Banana", "Orange", "Peach"]
["Apple", "Orange", "Peach"]
Could anyone please provide any hints to a solution ? Thanks !
This code works out the variations, then runs the permutations on each unique set of 3.
i.e. for “A”, “B”, “C”, “D” the possibilities are [[A, B, C], [A, B, D], [A, C, D], [B, C, D]]. We then calculate the permutations on each threesome (or n-some) and append the possibilities to a list.
PermutationsOfN.processSubsets( List set, int k ) returns:
[[A, B, C], [A, B, D], [A, C, D], [B, C, D]]
Taking it a bit further PermutationsOfN.permutations( List list, int size ) returns:
[[A, B, C], [A, C, B], [C, A, B], [C, B, A], [B, C, A], [B, A, C], [A, B, D], [A, D, B], [D, A, B], [D, B, A], [B, D, A], [B, A, D], [A, C, D], [A, D, C], [D, A, C], [D, C, A], [C, D, A], [C, A, D], [B, C, D], [B, D, C], [D, B, C], [D, C, B], [C, D, B], [C, B, D]]
A special mention goes to meriton whose answer here helped me work it out.