I have strings of the form 000011122222
. That is, consecutive digits repeated random no. of times. Some other examples could be:
0011122223333
01222
00011234444
001122222
and so on. I know, say for a string 01222
, that a total of 5!/3!
permutations are possible. I need to generate all these permutations for each such string.
I have tried generating permutations by various methods. One is by generating all the possible permutations (just as for strings without repetition), but since the strings that I would be using can be very large this can waste time generating too many redundant permutations.
Secondly, I have tried placing the digits at random indices of a character array equal to the size of the string and terminating the loop when the count of digits is same as in the input string. However, this way I am wasting a lot of memory and also taking up a lot of time.
I need an efficient way to generate permutations for such strings. Just an algorithm or code, either is welcome. I am using Java.
Thanks!
One of the standard algorithms for generating permutations is an algorithm for listing them in lexicographically increasing order. This algorithm, which is used by most implementations of the C++ std::next_permutation
algorithm, generates permutations in at most O(n) time per permutation and skips over all permutations that are duplicates of one another. It's also extremely easy to code up.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With