Java recursion with multiple arrays regardless of array size

I have three arrays:

{} {a, b, c} {d, e} 

I am trying to combine them to get the following arrays:

 {a, d} {a, e} {b, d} {b, e} {c, d} {c, e} 

The problem I am facing is the first empty array, because of which the cycle of nested loops does not start at all - logically makes sense. i.e:

  for (int i = 0; i < bL.size(); i++) { for (int j = 0; j < dL.size(); j++) { for (int k = 0; k < oL.size(); k++) { 

What I'm trying to find is the most efficient way to combine three arrays regardless of their size. In most cases, all three have elements, but there are times when you can create an empty set.

Any help was appreciated.

EDIT: adding output for all three arrays

Entrance - {A, b} {CD} {E, e}

The output is {A, c, e} {A, c, e} {A, d, e} {A, d, e} {b, c, e} {b, s, e}

EDIT: only for the first or third array is an empty set possible

+4
source share
2 answers

Assuming you are going through arrays of int values, here is what you can do:

 void printCombination(int[][] data, List<int> partial) { if (partial.size() == data.Length) { for (int i : partial) { if (i != -1) { System.out.writeln(" " + i); } } return; } if (data[partial.size()].length == 0) { partial.add(-1); printCombination(data, partial); partial.remove(partial.size()-1); return; } for (int i = 0 ; i != data[partial.size()].length; i++) { partial.add(data[partial.size()][i]); printCombination(data, partial); partial.remove(partial.size()-1); } } 

The initial call is as follows:

 List<int> partial = new ArrayList(); int[][] data = new int[][] {new int[] {}, new int[] {1,2}, new int[] {3, 4, 5}}; printCombination(data, partial); 
0
source

Here is a simple recursive approach that returns the result as a 2D ArrayList instead of printing it. A.

 import java.util.ArrayList; public class Program { public static void main(String[] args) { String[][] x = { {}, {"a", "b", "c"}, {"d", "e"} }; System.out.println(cartProd(x)); } public static ArrayList< ArrayList<String> > cartProd(String[][] x) { return cartProd(x, new ArrayList<String>(), 0); } public static ArrayList< ArrayList<String> > cartProd(String[][] x, ArrayList<String> current, int index) { ArrayList< ArrayList<String> > result = new ArrayList< ArrayList<String> >(); while (index < x.length && x[index].length == 0) { index++; } if (index == x.length) { result.add(new ArrayList<String>(current)); } else { for (int i = 0; i < x[index].length; i++) { current.add(x[index][i]); result.addAll(cartProd(x, current, index + 1)); current.remove(current.size() - 1); } } return result; } } 
0
source

Source: https://habr.com/ru/post/1396083/


All Articles