To find the Cartesian product of multiple sets, I have implemented an algorithm, but its output is still incorrect.
The algorithm uses two stacks (stack1 and stack2) to store intermediate results.
Here my implementation:
java.util.ArrayList;
java.util.Stack;
public class CartesianProduct {
int k;
ArrayList<String[]> product = new ArrayList<String[]>();
public CartesianProduct(ArrayList<String> input) {
k = input.size();
Stack<String[]> stack1 = new Stack<String[]>();
Stack<String[]> stack2 = new Stack<String[]>();
String[] tupel = new String[k];
for (int l = 0; l < k; ++l) {
tupel[l] = input.get(l);
}
stack1.push(tupel);
System.out.println("push on 1: "+tupel[0]+" "+tupel[1]+" "+tupel[2]);
for (int l = 0; l < k; ++l) {
System.out.println();
if (l % 2 == 0) {
while (!stack1.empty()) {
String[] tupel1 = stack1.pop();
System.out.println("pop from 1: "+tupel1[0]+" "+tupel1[1]+" "+tupel1[2]);
String[] indices = tupel1[l].split(",");
String[] tupel2 = tupel1;
for (String index : indices) {
tupel2[l] = index;
stack2.push(tupel2);
System.out.println("push on 2: "+tupel2[0]+" "+tupel2[1]+" "+tupel2[2]); }
}
} else {
while (!stack2.empty()) {
String[] tupel1 = stack2.pop();
System.out.println("pop from 2: "+tupel1[0]+" "+tupel1[1]+" "+tupel1[2]);
String[] indices = tupel1[l].split(",");
String[] tupel2 = tupel1;
for (String index : indices) {
tupel2[l] = index;
stack1.push(tupel2);
System.out.println("push on 1: "+tupel2[0]+" "+tupel2[1]+" "+tupel2[2]);
}
}
}
}
if (k % 2 == 0) {
while (!stack1.isEmpty()) {
product.add(stack1.pop());
}
} else {
while (!stack2.isEmpty()) {
product.add(stack2.pop());
}
}
}
public int getK() {
return k;
}
public ArrayList<String[]> getProduct() {
return product;
}
public static void main(String args[]) {
ArrayList<String> set = new ArrayList<String>();
set.add("k1,k2,k3");
set.add("m1,m2");
set.add("s1");
CartesianProduct prod = new CartesianProduct(set);
System.out.println("k: " + prod.getK());
for (String[] tupel : prod.getProduct()) {
System.out.println(tupel[0] + " " + tupel[1] + " " + tupel[2]);
}
}
}
In a first while loop I put results on stack2 with push, but when I want to get them back down from stack2 in a second while loop with pop, this doesn't seem to work correctly.
At the moment the algorithm for the given example still returns the following erroneous output: determination