JavaScript 笛卡尔积 小算法!

给定一个Javascript二维数组,如何得到其笛卡尔积。

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

求大神解答!

阅读 14.6k
4 个回答

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

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

不就是循环一下么

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

是这个意思么

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]);
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]);

移步参考:
https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏