5 Replies Latest reply: Aug 8, 2010 5:04 AM by EJP

# Generate All Possible String Variations

How would you generate a list of all possible strings, say with a length of 3 for example the Characters of ABC would return:
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA...

and so on.

Thanks for replys in advance.
• ###### 1. Re: Generate All Possible String Variations
``````public class Main {
private static void voodoo(String s) {
for(int i=0;i<Math.pow(s.length(),s.length());i++)
for(char c:(String.format("%3s|", Integer.toString(i,s.length())).replace(" ", "0")).toCharArray())
System.out.print(c-'0'<s.length()?s.charAt(c-'0'):"\n");
}
public static void main(String[]args) {
voodoo("ABC");
}
}

/*
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
*/``````
• ###### 2. Re: Generate All Possible String Variations
Thanks for the response. The code is very helpfuly but i cant quite understand what is going on here. How would i adjust it for varying lenghts of string and also include different characters, (alpha-numeric)?

Cheers,

Josh.
• ###### 3. Re: Generate All Possible String Variations
Change:
``for(char c:(String.format("%3s|", Integer.toString(i,s.length())).replace(" ", "0")).toCharArray())``
into:
``for(char c:(String.format("%"+s.length()+"s|", Integer.toString(i,s.length())).replace(" ", "0")).toCharArray())``
• ###### 4. Re: Generate All Possible String Variations
It's just counting up to the maximum value in the appropriate radix.
• ###### 5. Re: Generate All Possible String Variations
voodoo was clever but I suspect it would have been more helpful for the OP to mention Cartesian Product.