# JavaScript 笛卡尔积 小算法！

• 1.1k

var Test = new Array();
Test[0] = new Array(1, 2, 3);
Test[1] = new Array(4, 5, 6);

4 个回答
var cartesianProduct = function(input) {
return input.reduce((a, b) => {
let m = a.map((av) => b.map((bv) => [bv].concat(av)))
return m.reduce((c, d) => c.concat(d), [])
}).map(v => v.reverse())
}

var a = cartesianProduct([[1,2], [3,4], [5,6]])
console.log(a)
var cartesianProduct2 = function() {
return Array.prototype.reduce.call(arguments, function(a, b) {
var ret = [];
a.forEach(function(a) {
b.forEach(function(b) {
ret.push(a.concat([b]));
});
});
return ret;
}, [[]]);
}
var b = cartesianProduct2([1,2], [3,4], [5,6])
console.log(b)
var cartesianProduct3 = function(array) {
return array.reduce(
function(a, b) {
return a
.map(function(x) {
return b.map(function(y) {
return x.concat(y)
})
})
.reduce(function(a, b) {
return a.concat(b)
}, [])
},
[[]]
)
}
var c = cartesianProduct3([[1,2], [3,4], [5,6]])
console.log(c)
var cartesianProduct4 = function(input) {
return input.reduce((prev, curr, currIndex, arr) => {
const ret = []
prev.map((a) => {
curr.map((b) => {
ret.push((Array.isArray(a) ? a : [a]).concat(b))
})
})
return ret
})
}

var d = cartesianProduct4([[1,2], [3,4], [5,6]])
console.log(d)
var f = (a, b) => [].concat(...a.map((d) => b.map((e) => [].concat(d, e))))
var cartesianProduct5 = (a, b, ...c) => (b ? cartesianProduct5(f(a, b), ...c) : a)
var e = cartesianProduct5([1,2], [3,4], [5,6])
console.log(e)
// 多数组求笛卡儿积
var cartesianProduct6 = function(array) {
return array.reduce(
function(a, b) {
return a
.map(function(x) {
return b.map(function(y) {
return x.concat(y)
})
})
.reduce(function(a, b) {
return a.concat(b)
}, [])
},
[[]]
)
}
var f = cartesianProduct6([[1,2], [3,4], [5,6]])
console.log(f)
// Generate cartesian product of given iterables:
var cartesianProduct7 = function* (head, ...tail) {
const remainder = tail.length > 0 ? cartesianProduct7(...tail) : [[]];
for (let r of remainder) for (let h of head) yield [h, ...r];
}

var g = cartesianProduct7([1,2], [3,4], [5,6])
console.log([...g]);