Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intersecting each element of a list<string[]> with one another

Tags:

java

algorithm

I am trying to intersect each element in a list containing String [] with one another. Each element (String[]) in the input list will be of length 3 or 4

Input: [{'J', 'K', 'L'}, {'G', 'H', 'I'}]
Output: ["JG", "JH", "JI", 
         "KG", "KH", "KI", 
         "LG", "LH", "LI"]

Input: [{'J', 'K', 'L'}, {'G', 'H', 'I'}, {'A', 'B', 'C'}]
Output: ["JGA", "JGB", "JGC", 
         "KGA", "KGB", "KGC", 
         "LGA", "LGB", "LGC", 
         "JHA", "JHB", "JHC",
         "KHA", "KHB", "KHC", 
         "LHA", "LHB", "LHC", 
         "JIA", "JIB", "JIC",
         "KIA", "KIB", "KIC",
         "LIA", "LIB", "LIC"]

The size of each element in the output is equal to the total elements in the input list.

I've done the following but am not getting the correct results.

ArrayList<String> output = new ArrayList();
for (String [] s : InputList)
   for (int i = 0; i < s.length; i++) {
      if (output.size < 3)
         output.add(s[i])
      else {
         output.add(output.get(i)+s[i]);
      }
   }
}
like image 450
birdy Avatar asked Dec 05 '25 16:12

birdy


1 Answers

You can use a recursive approach. This will work for any (reasonably) sized list:

public static List<String> combine(List<String[]> list) {
    List<String> elements = new ArrayList<String>();
    if (!list.isEmpty()) {
        String[] head = list.get(0);
        List<String> tail;
        if (list.size() > 1) {
            tail = combine(list.subList(1, list.size()));
        } else {
            tail = Arrays.asList("");
        }
        for (String headElem : head) {
            for (String tailElem : tail) {
                elements.add(headElem + tailElem);
            }
        }
    }
    return elements;
}
like image 86
Keppil Avatar answered Dec 07 '25 04:12

Keppil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!