I am working with large number of integer permutations. The number of elements in each permutation is K. The element size is 1 byte. I need to generate N unique random permutations.
Constraints: K <= 144, N <= 1,000,000.
I came up with the following straightforward algorithm:
- Generate list of N random permutations. Store all permutations in RAM.
- Sort the list and delete all duplicates (if any). The number of duplicates will be relatively small.
- If there were any duplicates, add random permutations to the list until there are N permutations and return to step 2.
Is there a better way to do this? Especially, is there a way to not store all permutations in RAM (write them on disk while generating)?
Edit: In the end, the generated permutations need to be accessed sequentially (one-by-one, no need for random access). The RAM is more crucial factor (I would prefer to not store all permutations at once in RAM).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…