This is what I have so far.
package testproject;
public class Combinations{
public Combinations(){
String str_arr[]={"a","b","c"};
GenCombinations(str_arr);
}
public void GenCombinations(String[] str_arr){
System.out.println("Generating All possible Combinations for the following "+str_arr.length+" strings.");
for(int i=0;i<str_arr.length;i++)
{
System.out.print(str_arr[i]+" ");
}
System.out.println("\n------------------------------------------");
/*COMBINATIONS OF LENGTH ONE*/
for(int i=0;i<str_arr.length;i++)
System.out.println(str_arr[i]);
/*COMBINATIONS OF LENGTH TWO*/
for(int i=0;i<str_arr.length;i++)
{
for(int j=0;j<str_arr.length;j++)
{
System.out.println(str_arr[i]+""+str_arr[j]);
}
}
/*COMBINATIONS OF LENGTH THREE*/
for(int i=0;i<str_arr.length;i++)
{
for(int j=0;j<str_arr.length;j++)
{
for(int k=0;k<str_arr.length;k++)
{
System.out.println(str_arr[i]+""+str_arr[j]+""+str_arr[k]);
}
}
}
}
public static void main(String[] args){
new Combinations();
}
}
Any suggestions will be appreciated..
If you want to generate all possible substrings of length k from a given alphabet, then what you’re doing is pretty much optimal.
If you want to generate all possible combinations of length k from a given set (or alphabet) with n elements (
C(n, k)), then a classical solution is to use Rosen’s algorithm.For example, given a 5-letter alphabet, if you want to take 3 combinations at a time, the gist of it is to count like so:
Here’s my implementation of a
RosenIteratorin Java.