js算法之笛卡尔积

集合XC和Y的笛卡儿积可以表示为:A×B = {(x,y)|x∈A∧y∈B},写一个函数,求数组的笛卡尔积
例如: [1,2] x ['a','b'] = [[1,'a],[1,'b],[2,'a],[2,'b]]
 
代码如下所示:
function cartesianProduct(...Matrix) {
    if(Matrix.length === 0) {return []}
    if(Matrix.length === 1) {return Matrix[0]}
    return Matrix.reduce((A,B) => {
       const product = []
       for(let i = 0; i < A.length; i++){
           for(let j = 0; j < B.length; j++) {
               product.push(
                   Array.isArray(A[i]) ? [...A[i],B[j]] : [A[i],B[j]]
               )
           }
       }
       return product
    })
}
const arr = cartesianProduct([1,2,3],['a','b','c','d'],[1,2])
console.log(arr)

猜你喜欢

转载自www.cnblogs.com/fanzhanxiang/p/10306423.html