Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I believe this is correct. It is not seeking efficiency, but a clean style through recursion and abstraction.</p> <p>The key abstraction is to introduce a simple <code>Tuple</code> class. This helps the generics later:</p> <pre><code>class Tuple&lt;T&gt; { private List&lt;T&gt; list = new ArrayList&lt;T&gt;(); public void add(T t) { list.add(t); } public void addAll(Tuple&lt;T&gt; subT) { for (T t : subT.list) { list.add(t); } } public String toString() { String result = "("; for (T t : list) { result += t + ", "; } result = result.substring(0, result.length() - 2); result += " )"; return result; } } </code></pre> <p>With this class, we can write a class like so:</p> <pre><code>public class Example { public static &lt;T&gt; List&lt;Tuple&lt;T&gt;&gt; cartesianProduct(List&lt;Set&lt;T&gt;&gt; sets) { List&lt;Tuple&lt;T&gt;&gt; tuples = new ArrayList&lt;Tuple&lt;T&gt;&gt;(); if (sets.size() == 1) { Set&lt;T&gt; set = sets.get(0); for (T t : set) { Tuple&lt;T&gt; tuple = new Tuple&lt;T&gt;(); tuple.add(t); tuples.add(tuple); } } else { Set&lt;T&gt; set = sets.remove(0); List&lt;Tuple&lt;T&gt;&gt; subTuples = cartesianProduct(sets); System.out.println("TRACER size = " + tuples.size()); for (Tuple&lt;T&gt; subTuple : subTuples) { for (T t : set) { Tuple&lt;T&gt; tuple = new Tuple&lt;T&gt;(); tuple.addAll(subTuple); tuple.add(t); tuples.add(tuple); } } } return tuples; } </code></pre> <p>}</p> <p>I have a decent example of this working, but it is omitted for brevity.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload