This program checks every combination of inputArray and prints it -
Checker.java -
package testpj;
import java.util.ArrayList;
public class Checker {
public static void main(String[] args) {
String[] subarrayA = {"A0","A1","A2"};
String[] subarrayB = {"B0","B1"};
String[] subarrayC = {"C0","C1","C2","C3"};
String[][] inputArray = {subarrayA, subarrayB, subarrayC};
ArrayList<String> output = new ArrayList<String>();
String output1 = permute(inputArray, 0, output);
System.out.println("the output1: "+output1);
}
public static String permute(String array[][], int index, ArrayList<String> output){
if(index == array.length){
System.out.println(output.toString());
}
else{
for(int i=0 ; i<array[index].length ; i++){
output.add(array[index][i]);
permute(array,index+1,output);
output.remove(output.size() - 1);
}
}
return output.toString();
}
}
OUTPUT:
[A0, B0, C0]
[A0, B0, C1]
[A0, B0, C2]
[A0, B0, C3]
[A0, B1, C0]
[A0, B1, C1]
[A0, B1, C2]
[A0, B1, C3]
[A1, B0, C0]
[A1, B0, C1]
[A1, B0, C2]
[A1, B0, C3]
[A1, B1, C0]
[A1, B1, C1]
[A1, B1, C2]
[A1, B1, C3]
[A2, B0, C0]
[A2, B0, C1]
[A2, B0, C2]
[A2, B0, C3]
[A2, B1, C0]
[A2, B1, C1]
[A2, B1, C2]
[A2, B1, C3]
the output1: []
Why is output1 contains no element ?
The correct answer is when I call permute recursively then it re-initializes the value of output again and so we end up having no value in the output variable. I added one more variable to the permute method and added the output to it instead of adding the output to output itself and it worked.
Solution:
public ArrayList<String> permute(String array[][],
int index, ArrayList<String> output, ArrayList<String> comb){
if(index == array.length){
comb.add(output.toString());
}
else{
for(int i=0 ; i<array[index].length ; i++){
output.add(array[index][i]);
permute(array,index+1,output, comb);
output.remove(output.size() - 1);
}
}
return comb;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다