combination of two lists in java

2019-07-21 00:51发布

问题:

Is there any algorithm to achieve this combination of output? Input :

arr1 = {x, y, z}
arr2 = {a, b}

Output :

xa, ya, za
xa, ya, zb
xa, yb, za
xa, yb, zb
xb, ya, za
xb, ya, zb
xb, yb, za
xb, yb, zb

回答1:

static char[] arr1 = {'x', 'y', 'z'};
static char[] arr2 = {'a', 'b'};

public static void main(String[] args) {
    print(new char[arr1.length - 1], 0);
}

static void print(char[] store, int depth) {
    for(char c : arr2) {
        if(depth < store.length) {
            store[depth] = c;
            print(store, depth + 1);
        } else {
            for(int i = 0; i < store.length; i++) {
                System.out.print(arr1[i] + "" + store[i] + ", ");
            }
            System.out.println(arr1[depth] + "" + c);
        }
    }
}

EDIT: Couldn't resist trying out @DenisKulagin's method, so here goes:

public static void main(String[] args) {
    char[] arr1 = {'x', 'y', 'z'};
    char[] arr2 = {'a', 'b'};

    for(int i = 0; i < 1 << arr1.length; i++) {
        for(int j = 0; j < arr1.length; j++) {
            int inverted = arr1.length - 1 - j;
            int index = (i & (1 << inverted)) >>> inverted;
            System.out.print(arr1[j] + "" + arr2[index] + " ");
        }
        System.out.println();
    }
}

Not quite as flexible as my version, since arr2 can only contain 2 elements, but definitely a clever approach.



回答2:

  1. Encode {a, a, a} as {0, 0, 0} - 0/binary.
  2. Encode {b, b, b} as {1, 1, 1} - 7/binary.
  3. Loop through 0..7, joining {x, y, z} & resulting 3-tuple.
  4. Profit!


回答3:

It maybe a 2 power 3 (arr2.length power arr1.length). This should give the num of rows.

So you need an Algorithm that calculates every single row. The shorter one gives the num and the longer one the exponent.