Is there an algorithm for listing all permutations with limited repetition? If there is an existing Java library, that would be so nice!
Say we have 3 elements {A, B, C} . We want a permutation of two elements. This will be 3 P 2 :
{A, B} {A, C} {B, A} {B, C} {C, A} {C, B}
But if we allow maximum repetition twice. How would that be? (I really do not know.)
I am trying to render, we get a permutation 2 from the set {A, A, B, B, C, C} . It will be 6 P 2 = 30. But we must select these duplicates. I did it manually, and it's 9. I don't know how to calculate 9 from math.
{A, A} {A, B} {A, C} {B, B} {B, A} {B, C} {C, C} {C, A} {C, B}
(Actually, 3 P 2 with repetition 2 is not a good example. This is because there are only 2 elements in permutations. No differences between unlimited repetition. 4 P 3 with repetition 2 would be a more pleasant example. But it would be difficult to list all the permutations .)
Best example to illustrate: 4 P 3 for the set {A, B, C, D} :
{A, B, C} {A, B, D} {A, C, B} {A, C, D} {A, D, B} {A, D, C} ... repeat for permutations starting from {B, ... } ... repeat for permutations starting from {C, ... } ... repeat for permutations starting from {D, ... }
And 4 P 3 from the set {A, B, C, D} with a repeat limit of 2:
{A, A, B} {A, A, C} {A, A, D} {A, B, A} {A, B, B} {A, B, C} {A, B, D} {A, C, A} {A, C, B} {A, C, C} {A, C, D} {A, D, A} {A, D, B} {A, D, C} {A, D, D} ... repeat for permutations starting from {B, ... } ... repeat for permutations starting from {C, ... } ... repeat for permutations starting from {D, ... }
Here is a web page about a similar thing. But it seems that this requires n P n (selection of all elements). In addition, I still need an algorithm for generating and listing permutations.
Thanks for the help!
There is actually a “non-smart” approach to implementing programming.
For the set {A, B, C, D} save an additional array int used[0, 0, 0, 0] , which is the number of times each element is used. Increase the counter each time an element is selected, and pass a copy of the array forward (down the call tree). Then, using the recursive approach inspired here , modify it to allow unlimited repetition (without deleting the selected one from the set of elements) and add the if (used[i] <= LIMIT) check if (used[i] <= LIMIT) after for .
This is “not reasonable” and not good enough, because we need an additional array and each time we need to check the number used.