Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutation with repetition in Java (Strings are of the form: 00001112222)

Tags:

java

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!

like image 625
akaHuman Avatar asked Jul 04 '12 19:07

akaHuman


1 Answers

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!

like image 82
templatetypedef Avatar answered Sep 21 '22 22:09

templatetypedef