3-25 笛卡尔积算法

问题:假设集合 A={a, b},集合 B={0, 1, 2},
则两个集合的笛卡尔积为{(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}。
求当 A={a, b, ..., n}, B={0, 1, 2, ..., n}时的笛卡尔积.

复习reduce的基本参数:

  1. reduce 的第一个previousValue参数:
    上一次调用 callbackFn 时的返回值。在第一次调用时,
    若指定了初始值 initialValue,
    其值则为 initialValue,
    否则为数组索引为 0 的元素 array[0]
  2. reduce 的第二个参数currentValue:
    数组中正在处理的元素。
    在第一次调用时,若指定了初始值 initialValue,
    其值则为数组索引为 0 的元素 array[0],
    否则为 array[1]

代码


var year = ['2019', '2020'];
var color = ['白色', '灰色', '蓝色'];
var size = ['S', 'M', 'L'];

// 集合
var list = [year, color, size];

function calcDescartes(array) {
    if(!Array.isArray(array)) {
        throw new TypeError('is not array')
    }

    return array.reduce((previousValue, currentValue) => {
        const result = []
        previousValue.forEach(item => {
            currentValue.forEach(ite => {
                if(Array.isArray(item)) {
                    result.push([...item, ite])
                } else {
                    result.push([item, ite])
                }
            })
        })

        return result
    })

}
console.log(calcDescartes(list), '打印');

参考:JS - 笛卡尔积算法:https://blog.csdn.net/chenjineng/article/details/108007074

MySQL的多表查询(笛卡尔积原理)
先确定数据要用到哪些表。
将多个表先通过笛卡尔积变成一个表。
然后去除不符合逻辑的数据(根据两个表的关系去掉)。
最后当做是一个虚拟表一样来加上条件即可。

https://segmentfault.com/a/1190000022289699

posted @ 2022-03-25 11:12  林见夕  阅读(320)  评论(0编辑  收藏  举报