java from for loop to recursion in finding combination
how can i change this for loop to recursive in the event that if groupSize=3, n=6 will print 123 124 125 126 134 135 136 145 146 156 234 235 236 245 246 345 346 356 456
public static void printCombinations(int groupSize, int n){
if (groupSize <=n && groupSize>0 && n>0){
for (int i=1; i<=n; i++){
for (int j=1; j<=i-1; j++){
for (int k=1; k<=j-1; k++){
开发者_JAVA技巧 int first = k;
int second = j;
int third = i;
if (i!=j && i!=k && j!=k){
System.out.println(first +" " + second +" "+ third);
}
}
}
}
}
}
Probably going to be rough around the edges; I'm just learning Java.
class comboMaker {
public static void main(String args[]){
String[] test1 = startCombo(3,6);
prnt(test1);
}
private static String[] startCombo(int len,int digits){
return combos(len,digits,"",0);
}
private static String[] combos(int len,int digits,String cur,int lastdig){
if (len>digits){
return null;
}
if (cur.length()==len){
return new String[]{cur};
}
String tmp = cur;
String[] rtn = {};
for(int i = lastdig+1;i<=digits;i++){
tmp=cur+Integer.toString(i);
rtn=concat(rtn,combos(len,digits,tmp,i));
}
return rtn;
}
private static String[] concat(String[] A, String[] B) {
String[] C= new String[A.length+B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
private static void prnt(String[] str){
if(str==null){
System.out.println("Invalid string array");
return;
}
for(int i =0;i<str.length;i++ ){
System.out.println(str[i]);
}
}
}
I included a method to concatenate arrays that I found here: How can I concatenate two arrays in Java?
Also a method to print your string array generated with the combo maker.
Create a method that will produce the suffix to a particular value with x digits and return a list of all possible suffixes. Might be something like:
List<String> generateSuffixes(int prefix, int suffixSize, int maxDigitValue);
The method would iterate from prefix + 1
to maxDigitValue
. It would then call itself with the iterate value and suffixSize - 1
. It would append the iterate to each suffix generated to create the list to return.
精彩评论