java中多个数组元素进行排列组合

package mytest;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombineTest {

    public static void main(String[] args) {
        String[][] arr = new String[3][];
        for (int i = 0; i < 3;  i++) {
            String[] a = new String[4];
            for (int j = 0; j < 4; j++) {
                a[j] = RandomUtil.randomString(5);
            }
            arr[i] = a;
        }
        System.out.println(JSONUtil.toJsonStr(arr));
        String[] item = new String[arr.length];
        List result = new ArrayList<>();
        combine(arr, 0, item, result);
        for (String[] a : result) {
            System.out.println(JSONUtil.toJsonStr(a));
        }
    }

    private static void combine(String[][] arr, int i, String[] item, List result) {
        if (i + 1 < arr.length) {
            for (int j = 0; j < arr[i].length; j++) {
                String[] rs = Arrays.copyOf(item, item.length);
                rs[i] = arr[i][j];
                combine(arr, i + 1, rs, result);
            }
        } else {
            for (int j = 0; j < arr[i].length; j++) {
                String[] rs = Arrays.copyOf(item, item.length);
                rs[rs.length - 1] = arr[i][j];
                result.add(rs);
            }
        }
    }
}

你可能感兴趣的:(java,开发语言)