Iterative Cartesian Product in Java

前端 未结 9 1908
既然无缘
既然无缘 2020-11-27 07:00

I want to compute the cartesian product of an arbitrary number of nonempty sets in Java.

I\'ve wrote that iterative code...

public s         


        
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 07:28

    I wrote an recursive cartesian product algorithm for table of Strings. You can modify it to have sets istead. Below is the algorithm. It's also explained in my article

    public class Main {
    
    public static void main(String[] args) {
        String[] A = new String[]{ "a1", "a2", "a3" };
        String[] B = new String[]{ "b1", "b2", "b3" };
        String[] C = new String[]{ "c1" };
    
        String[] cp = CartesianProduct(0, A, B, C);
    
        for(String s : cp) {
             System.out.println(s);
        }
    }
    
    public static String[] CartesianProduct(int prodLevel, String[] res, String[] ...s) {
        if(prodLevel < s.length) {
            int cProdLen = res.length * s[prodLevel].length;
            String[] tmpRes = new String[cProdLen];
    
            for (int i = 0; i < res.length; i++) {
                for (int j = 0; j < s[prodLevel].length; j++) {
                    tmpRes[i * res.length + j] = res[i] + s[prodLevel][j];
                }
            }
            res = Main.CartesianProduct(prodLevel + 1, tmpRes, s);
        }
        return res;
    }}
    

提交回复
热议问题