0

给定一个Javascript二维数组,如何得到其笛卡尔积。
var Test = new Array();
Test[0] = new Array(1, 2, 3);
Test[1] = new Array(4, 5, 6);

求大神解答!

查看全部 3 个回答

0

不就是循环一下么

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;
}

是这个意思么

推荐答案

2

已采纳

改编了一个大神给的解决方案!

<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>