【问题标题】:combination of two lists in javajava中两个列表的组合
【发布时间】:2015-02-12 07:41:02
【问题描述】:

有没有什么算法可以实现这种组合输出? 输入:

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

输出:

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

【问题讨论】:

    标签: java algorithm combinations probability


    【解决方案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);
            }
        }
    }
    

    编辑:忍不住尝试@DenisKulagin的方法,所以这里是:

    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();
        }
    }
    

    不如我的版本灵活,因为arr2 只能包含 2 个元素,但绝对是一个聪明的方法。

    【讨论】:

      【解决方案2】:
      1. 将 {a, a, a} 编码为 {0, 0, 0} - 0/binary。
      2. 将 {b, b, b} 编码为 {1, 1, 1} - 7/binary。
      3. 循环 0..7,加入 {x, y, z} 并生成 3 元组。
      4. 利润!

      【讨论】:

        【解决方案3】:

        它可能是 2 次方 3(arr2.length 次方 arr1.length)。这应该给出行数。

        因此,您需要一个计算每一行的算法。越短的给出数字,越长的给出指数。

        【讨论】:

        • 这不是笛卡尔积
        • 还有什么?您将列表一的每个项目与列表二的每个项目结合起来。我错了吗?
        • 这只会产生 6 个项目。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-22
        • 2015-11-08
        • 1970-01-01
        • 1970-01-01
        • 2011-11-29
        • 2017-07-22
        • 1970-01-01
        相关资源
        最近更新 更多