Possible Duplicate:
Generating all permutations of a given string
Given a length n=4,
and a set of characters -> {'a', 'b'},
how to write some java codes to produce all the possible string with that length n containing the characters in the set?
For the example above, the result should have 2^4=16 strings, which is:
aaaa
aaab
aabb
abbb
baaa
baab
babb
bbbb
bbaa
bbab
bbba
abaa
abab
abba
baba
aaba
here is my code snippet:
public void process(String result, String string)
{
if(string.length() == 0)
{
System.out.println(result);
}else{
for(int i = 0; i < string.length(); i++)
{
String newResult = new String(result+string.charAt(i));
String newString = new String(string.substring(0,i) + string.substring(i+1, string.length()));
process(newResult, newString);
}
}
}
That seems like only doing permutation, instead of what I want…….
Thank you in advance 🙂
Think of it in the same way you would counting. You’re technically “counting” from aaaa to bbbb, like binary.
Without seeing what you’ve tried, I can’t help you more than that, but essentially you need to enumerate all the “numbers” between your “lowest” element and your “highest” element by counting up through them.
For higher element counts, just treat your counting as counting in a higher base. For eight elements, Set = {a, b, c, d, e, f, g, h}, you would be counting up in what’s essentially octal:
It’s the same way you enumerate all the combinations of 0-9 with a length of 4, by counting from 0000 to 9999.
Edit:
Thank you for posting your code. You’re correct, you’re doing permutations. A better way would be to use a multi-combination (combination with repeated elements in the ordererd combination set) algorithm like the one discussed here.