Java : Cartesian Product of a List of Lists

后端 未结 12 1094
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 19:03

I have a problem that is really kind of a general programming question, but my implementation is in Java, so I will provide my examples that way

I have a class like

12条回答
  •  旧时难觅i
    2020-12-02 19:55

    Try something like this:

    public static void generate(int[][] sets) {
        int solutions = 1;
        for(int i = 0; i < sets.length; solutions *= sets[i].length, i++);
        for(int i = 0; i < solutions; i++) {
            int j = 1;
            for(int[] set : sets) {
                System.out.print(set[(i/j)%set.length] + " ");
                j *= set.length;
            }
            System.out.println();
        }
    }
    
    public static void main(String[] args) {
        generate(new int[][]{{1,2,3}, {3,2}, {5,6,7}});
    }
    

    which will print:

    1 3 5
    2 3 5
    3 3 5
    1 2 5
    2 2 5
    3 2 5
    1 3 6
    2 3 6
    3 3 6
    1 2 6
    2 2 6
    3 2 6
    1 3 7
    2 3 7
    3 3 7
    1 2 7
    2 2 7
    3 2 7
    

    I've implemented the algorithm above based on (I believe) one of Knuth's TAOCP books (in the comments @chikitin has a more specific reference: it is in

提交回复
热议问题