【问题标题】:javascript generate combinations of arrays of javascript objectsjavascript 生成 javascript 对象数组的组合
【发布时间】:2011-12-26 04:42:08
【问题描述】:

如何找到相同数组的笛卡尔积? (握手问题)。

我发现 cart_prod() 和 cartesianProductOf() 函数可以正常工作,但是当我这样做时:

cart_prod(list1, list1)

我没有给我一个大小为 (n^2+n)/2 的数组,而是得到一个大小为 n^2 的数组。基本上它返回给我所有的排列而不是组合。我跨越了两个列表,因为这有点像握手问题。

这里是笛卡尔ProductOf()函数:

function cartesianProductOf() {
//better cartesian function
//usage: cartesianProductOf([1,2],[3,4],[5,6]) returns 8 arrays [1,3,6],[1,3,5] and so on.
  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;
  }, [[]]);
}

【问题讨论】:

    标签: javascript iterator


    【解决方案1】:

    这里不需要花哨……你可以用一个 for 循环来解决这个问题。 (诀窍是执行排序 i

    for(var i=0; i<arr.length. i++){
        for(var j=i+1; j<arr.length; j++){
            //do something with the i-th and j-th elements of the array
        }
    }
    

    顺便说一句,笛卡尔积应该在您给出的示例中给出 N^2 个元素。而且我

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 2012-03-04
      • 2016-11-12
      • 1970-01-01
      • 2012-08-19
      相关资源
      最近更新 更多