How can I generate permutations given the following conditions?
- There are two integers, for ex. 1 and 4.
- The two integers given will be part of the permutation where each integer will appear at most N times and the size of each permutation is K.
So let’s say for N = 3 and K = 5, so the correct result should be:
{1, 1, 1, 4, 4} , {1, 1, 4, 1, 4} , {4, 4, 4, 1, 1} , etc..
The following are example of invalid or incorrect results:
{1, 1, 1, 1, 4} -> 1 appear 4 times (1 should appear not greater than 3 times)
{1, 4, 4, 4, 1, 1} -> the size of the list is 6 (the size should be exactly 5)
Also, each permutation should be unique, meaning no duplicates.
I hope I can get the best solution or algorithm for this problem.
Thanks in advance. 🙂
See if this works for you
Note**
First create all possible combination possible with ‘1’ and ‘4’. Please note with the restriction of maximum N instances of particular integer, so in a set of K numbers if there are i instances of x then there is (K-i) instances of y for two numbers (x,y). In that case both i and x should be in the range [K-N,N].
Now the next step is to use a generator comprehension to create all possible iteration of all possible instances of the above set. I am using a set comprehension to remove any duplicate and also using generator to not store the intermediate duplicate results.