java 二维数组中的元素所有组合

原文
二维数组矩阵

/**
     * @param array 目标数组
     * @return 矩阵结果
     * @description: 根据给定二维数组,输出排列组合矩阵
     */
    public String[][] generateMatrix(String[][] array) {
        ArrayList lengthArr = new ArrayList<>();
        ArrayList productArr = new ArrayList<>();
        int length = 1;
        for (int i = 0; i < array.length; i++) {
            int len = array[i].length;
            lengthArr.add(len);
            int product = i == 0 ? 1 : array[i - 1].length * productArr.get(i - 1);
            productArr.add(product);
            length *= len;
        }
        String[][] result = new String[array.length][length / array.length];
        for (int i = 0; i < length; i++) {
            StringBuilder item = new StringBuilder();
            for (int j = 0; j < array.length; j++) {
                item.append(array[j][(int) (Math.floor(i / productArr.get(j)) % lengthArr.get(j))]);
            }
            int index1 = i % array.length;
            int index2 = i / array.length;
            result[index1][index2] = item.toString();
        }
        return result;
    }

二维数集合

  /**
     * @param array 目标数组
     * @return 排列组合结果
     * @description: 根据给定二维数组,输出排列组合结果
     */
    public ArrayList generateList(String[][] array) {
        ArrayList lengthArr = new ArrayList<>();
        ArrayList productArr = new ArrayList<>();
        ArrayList result = new ArrayList<>();
        int length = 1;
        for (int i = 0; i < array.length; i++) {
            int len = array[i].length;
            lengthArr.add(len);
            int product = i == 0 ? 1 : array[i - 1].length * productArr.get(i - 1);
            productArr.add(product);
            length *= len;
        }
        for (int i = 0; i < length; i++) {
            StringBuilder item = new StringBuilder();
            for (int j = 0; j < array.length; j++) {
                item.append(array[j][(int) (Math.floor(i / productArr.get(j)) % lengthArr.get(j))]);
            }
            result.add(item.toString());
        }
        return result;
    }

测试代码

    //获取矩阵结果
        String[][] matrix = generateMatrix(arr);
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + ",");
            }
            System.out.println();
        }

        System.out.println("**********************************************************");

        //获取集合
        ArrayList list = generateList(arr);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

打印结果

> Task :lib:MyClass.main()
aaaaaa,bbbaaa,abbbbb,baacc,
baaaaa,aaabbb,bbbbbb,abbcc,
abbaaa,baabbb,aaacc,bbbcc,
**********************************************************
aaaaaa
baaaaa
abbaaa
bbbaaa
aaabbb
baabbb
abbbbb
bbbbbb
aaacc
baacc
abbcc
bbbcc

你可能感兴趣的:(java 二维数组中的元素所有组合)