Home
IT Knowledge
Inspiration
Languages
EN

# Java - get all possible combinations of 2D array (each sub-array can have different size)

2 points
Created by:
92090

Quick solution:

public class CombinationsUtil {

public static void printCombinations(int[][] mx, int position, String result) {
if (position == mx.length) {
System.out.println(result.substring(2));
return;
}
for (int i = 0; i < mx[position].length; i++) {
String newResult = result + ", " + mx[position][i];
printCombinations(mx, position + 1, newResult);
}
}

public static void main(String[] args) {
int[][] mx = {
{10, 20},
{30, 40, 50}
};
printCombinations(mx, 0, "");
}
}

Result:

10, 30
10, 40
10, 50
20, 30
20, 40
20, 50

Example 2

public class CombinationsUtilTest2 {

public static void main(String[] args) {
int[][] mx = {
{10, 20, 30},
{40, 50},
{70, 80, 90}
};
CombinationsUtil.printCombinations(mx, 0, "");
}
}

Result:

10, 40, 70
10, 40, 80
10, 40, 90
10, 50, 70
10, 50, 80
10, 50, 90
20, 40, 70
20, 40, 80
20, 40, 90
20, 50, 70
20, 50, 80
20, 50, 90
30, 40, 70
30, 40, 80
30, 40, 90
30, 50, 70
30, 50, 80
30, 50, 90