JavaScript小算法!
给定一个Javascript二维数组,如何得到其笛卡尔积。
var Test = new Array();
Test[0] = new Array(1, 2, 3);
Test[1] = new Array(4, 5, 6);
求大神解答!
MaxLee
10 years, 6 months ago
Answers
function descartes(){
if( arguments.length < 2 ) return arguments[0] || [];
return [].reduce.call(arguments, function(col, set) {
var res = [];
col.forEach(function(c) {set.forEach(function(s) {
var t = [].concat( Array.isArray(c) ? c : [c] );
t.push(s);
res.push(t);
})});
return res;
});
}
descartes([1,2,3],[4,5,6],[7,8,9],[10,11,12]);
wxklr
answered 10 years, 6 months ago
不就是循环一下么
function descartes(dimensionX, dimensionY) {
var xLen,yLen;
if(!(xLen = dimensionX.length) || !(yLen = dimensionY.length)) return [];
var products = [];
for(var i=0; i< xLen;i++){
for(var j=0;j<yLen;j++){
products.push([dimensionX[i],dimensionY[j]])
}
}
return products;
}
是这个意思么
命莲寺忘却缘起
answered 10 years, 6 months ago
改编了一个大神给的解决方案!
<script type="text/javascript">
var data = new Array(new Array(1, 2, 3), new Array(4, 5, 6));
var result = [];
console.log(data);
function descartes(arrIndex, aresult){
if (arrIndex >= data.length) {
result.push(aresult);
return ;
}
var aArr = data[arrIndex];
for (var i = 0; i < aArr.length; ++i) {
var theResult = aresult.slice(0, aresult.length);
theResult.push(aArr[i]);
descartes(arrIndex + 1, theResult);
}
}
descartes(0, []);
console.log(result);
</script>
境界边缘
answered 10 years, 6 months ago