计算 JavaScript 中多个数组的笛卡尔积
我们需要编写一个 JavaScript 函数,它接受多个数字数组。该函数应返回来自所有数组中元素的笛卡尔积数组。
例如 −
如果输入数组为 −
[1, 2], [10, 20], [100, 200, 300]
则输出应为 −
const output = [ [ 1, 10, 100 ], [ 1, 10, 200 ], [ 1, 10, 300 ], [ 1, 20, 100 ], [ 1, 20, 200 ], [ 1, 20, 300 ], [ 2, 10, 100 ], [ 2, 10, 200 ], [ 2, 10, 300 ], [ 2, 20, 100 ], [ 2, 20, 200 ], [ 2, 20, 300 ] ];
示例
const arr1 = [1, 2]; const arr2 = [10, 20]; const arr3 = [100, 200, 300]; const cartesianProduct = (...arr) => { return arr.reduce((acc,val) => { return acc.map(el => { return val.map(element => { return el.concat([element]); }); }).reduce((acc,val) => acc.concat(val) ,[]); }, [[]]); }; console.log(cartesianProduct(arr1, arr2, arr3));
输出
这将生成以下输出 −
[ [ 1, 10, 100 ], [ 1, 10, 200 ], [ 1, 10, 300 ], [ 1, 20, 100 ], [ 1, 20, 200 ], [ 1, 20, 300 ], [ 2, 10, 100 ], [ 2, 10, 200 ], [ 2, 10, 300 ], [ 2, 20, 100 ], [ 2, 20, 200 ], [ 2, 20, 300 ] ]
广告