I have a multi dimensional array whose size is dynamic.
String[][] array=new String[][]{{"1","2","3"},{"4","5","6"},{"7","8","9"},{"10","11","12"} };
I need to generate combinations such like that every combination length must lies between 1-array.length and every combination can have maximum one element from a row. if a column from a row is used then no other column from that row can be used in that combination.
for example combinations with length 1 are :
1
2
3
4
5
6
7
8
9
10
11
12
combination with length 2 are :
1,4
1,5
1,6
1,7
1,8
1,9
1,10
1,11
1,12
Currently i am only been able to get combination with length = array.length but i need length from 1 to array.length
private String[][] generateCombinations(String[]... arrays) throws Throwable {
if (arrays.length == 0) {
return new String[][]{{}};
}
int num = 1;
for (int i = 0; i < arrays.length; i++) {
num *= arrays[i].length;
}
String[][] result = new String[num][arrays.length];
// array containing the indices of the Strings
int[] combination = new int[arrays.length];
for (int i = 0; i < num; i++) {
String[] comb = result[i];
// fill array
for (int j = 0; j < arrays.length; j++) {
comb[j] = arrays[j][combination[j]];
}
// generate next combination
for (int j = 0; j < arrays.length; j++) {
int n = ++combination[j];
if (n >= arrays[j].length) {
// "digit" exceeded valid range -> back to 0 and continue incrementing
combination[j] = 0;
} else {
// "digit" still in valid range -> stop
break;
}
}
}
return result;
}
Do you like 1 letter variable names...? :D I don't even know how it works now. It uses bit masks to find every combination of subarrays of length n; then it uses some mod math to find every combination of 1 from each subarray; then it spits out that number. Sort order isn't ideal.