How to create cartesian product over arbitrary groups of numbers in Java?

后端 未结 4 1450
野性不改
野性不改 2021-02-08 07:36

Let\'s say I have 2 groups of numbers:

{1, 2, 3},
{4, 5}

I\'d like to create an algorithm (in Java) that outputs the following 6 combinations:<

4条回答
  •  轮回少年
    2021-02-08 08:00

    Got a bit bored and decided to give it a shot. Should be exactly what you need:

    public static void main(String args[]) {
    
        ArrayList input = new ArrayList();
        input.add(new int[] { 1, 2, 3 });
        input.add(new int[] { 4, 5 });
        input.add(new int[] { 6, 7 });
    
        combine(input, new int[input.size()], 0);
    }
    
    private static void combine(ArrayList input, int[] current, int k) {
    
        if(k == input.size()) {
            for(int i = 0; i < k; i++) {
                System.out.print(current[i] + " ");
            }
            System.out.println();
        } else {            
            for(int j = 0; j < input.get(k).length; j++) {
                current[k] = input.get(k)[j];
                combine(input, current, k + 1);
            }       
        }
    }
    

提交回复
热议问题