笛卡尔积的 JS 实现

第一种:

function descartes(...args) {
    if (args.length < 2) {
        return args[0] || [];
    }

    return [].reduce.call(args, (col, set) => {
        let res = [];
        col.forEach(c => {
            set.forEach(s => {
                let t = [].concat(Array.isArray(c) ? c : [c]);
                t.push(s);
                res.push(t);
            });
        });
        return res;
    });
}

descartes([1, 2, 3], ['a', 'b', 'c'], [8, 9]);

第二种:

function descartes2(list) {
    // parent上一级索引;count指针计数
    let point = {};
    let result = [];
    let pIndex = null;
    let tempCount = 0;
    let temp  = [];

    // 根据参数列生成指针对象
    for (let index in list) {
        if (typeof list[index] === 'object') {
            point[index] = {parent: pIndex, count: 0};
            pIndex = index;
        }
    }

    // 单维度数据结构直接返回
    if (pIndex == null) {
        return list;
    }

    // 动态生成笛卡尔积
    while (true) {
        let index;
        for (index in list) {
            tempCount = point[index].count;
            temp.push(list[index][tempCount]);
        }

        // 压入结果数组
        result.push(temp);
        temp = [];

        // 检查指针最大值问题
        while (true) {
            if (point[index].count + 1 >= list[index].length) {
                point[index].count = 0;
                pIndex = point[index].parent;
                if (pIndex == null) {
                    return result;
                }

                // 赋值parent进行再次检查
                index = pIndex;
            }
            else {
                point[index].count++;
                break;
            }
        }
    }
}

descartes2([[1, 2, 3], ['a', 'b', 'c'], [8, 9]]);

你可能感兴趣的:(javascript)