有点类似笛卡尔积的问题,按条件打印指定的数组,是否有性能好点的办法?

代码:

public class example {

    public static void main(String[] args) {
        String[] arr1 = new String[] { "苹果", "橘子", "香蕉", "栗子" };

        String[] arr2 = new String[] { null, "12", null, "24" };
        String[] arr3 = new String[] { "33", "42", null, "51" };
        String[] arrN = new String[] { "33", "43", "", "11" };
    }
}

已知条件:

  • 所有arr的长度一致
  • 只有arr1里面不包含null
  • arrN里面可能出现null,但是至少有一个非null元素

我现在需要把arr1输出显示,arrN里面相同索引的值作为备用值
要求把各种可能性都打印显示,还需要忽略null
比如:
"苹果", "橘子", "香蕉", "栗子"
"苹果", "12", "香蕉", "栗子"
"苹果", "12", "香蕉", "24"

各位有好点的思路吗?自己有实现但性能不太好。

阅读 790
1 个回答

把每一列(索引位)的可选值列表先算出来,然后对每一列的可选值做笛卡尔积,直接输出所有组合

试试

import java.util.*;
import java.util.stream.Collectors;

public class Example {

    public static void main(String[] args) {
        String[] arr1 = { "苹果", "橘子", "香蕉", "栗子" };
        String[] arr2 = { null, "12", null, "24" };
        String[] arr3 = { "33", "42", null, "51" };

        // 所有备用数组放这里
        List<String[]> backupArrays = Arrays.asList(arr2, arr3);

        // 步骤1:构建每一列的可选值
        List<List<String>> columnOptions = buildColumnOptions(arr1, backupArrays);

        // 步骤2:计算笛卡尔积(所有组合)
        List<List<String>> result = cartesianProduct(columnOptions);

        // 步骤3:打印所有结果
        for (List<String> line : result) {
            System.out.println(line);
        }
    }

    // 构建每一列的可选值(去null、去空串)
    private static List<List<String>> buildColumnOptions(String[] base, List<String[]> backups) {
        List<List<String>> columns = new ArrayList<>();
        int len = base.length;

        for (int i = 0; i < len; i++) {
            Set<String> set = new LinkedHashSet<>(); // 去重 + 保持顺序
            set.add(base[i]);

            for (String[] arr : backups) {
                String val = arr[i];
                if (val != null && !val.isEmpty()) {
                    set.add(val);
                }
            }
            columns.add(new ArrayList<>(set));
        }
        return columns;
    }

    // 笛卡尔积
    private static List<List<String>> cartesianProduct(List<List<String>> lists) {
        List<List<String>> result = new ArrayList<>();
        result.add(new ArrayList<>());

        for (List<String> list : lists) {
            List<List<String>> temp = new ArrayList<>();
            for (List<String> res : result) {
                for (String s : list) {
                    List<String> newList = new ArrayList<>(res);
                    newList.add(s);
                    temp.add(newList);
                }
            }
            result = temp;
        }
        return result;
    }
}