【问题标题】:Find all possible set of two combinations in array在数组中查找所有可能的两个组合的集合
【发布时间】:2019-12-29 16:28:04
【问题描述】:

给定一个大小为 n 的数组,它甚至总是,我需要输出 2 对元素的所有可能组合。

我有这个:

let teams = ["team1","team2","team3","team4"]

我尝试了什么:

function pairs(arr) {
    var res = [],
        l = arr.length;
    for(var i=0; i<l; ++i)
        for(var j=i+1; j<l; ++j)
            res.push([arr[i], arr[j]]);
    return res;
}

pairs(teams).forEach(function(pair){
    console.log(pair);
});

//outputs

[ 'team1', 'team2' ]
[ 'team1', 'team3' ]
[ 'team1', 'team4' ]
[ 'team2', 'team3' ]
[ 'team2', 'team4' ]
[ 'team3', 'team4' ]

这看起来不错,但有些缺失,例如我没有看到以下内容:

[ 'team2', 'team1' ] 
[ 'team3', 'team1' ]
[ 'team3', 'team2' ]
[ 'team4', 'team1' ]
[ 'team4', 'team2' ]
[ 'team4', 'team3' ]

所以我的预期输出是上面发布的代码中的上述结果。

请注意,只要我得到所有可能的组合,我就不需要按特定顺序排列它们。

【问题讨论】:

  • 所以你得到了[ 'team1', 'team2' ],但想要同时得到[ 'team1', 'team2' ][ 'team2', 'team1' ]?如果是,那你为什么说“你不需要它们按特定顺序”?
  • 您不能只获取当前输出并添加数组中的.reverse() 吗?
  • @skyboyer 我认为很清楚我的意思是输出。而且这是比赛日程,所以每支球队都应该打主场/客场比赛。
  • 当顺序无关紧要时,它是一个组合。当顺序很重要时,它就是一种排列。
  • 是的,但我不需要任何顺序,我的意思是成对输出。

标签: javascript arrays combinations


【解决方案1】:

函数式JS:

let teams = ["team1", "team2", "team3", "team4"];

var result = teams.flatMap( (v) => 
  teams.
    filter( w => v!=w ).
    map   ( w => [v, w] ) 
);

console.log(result);

【讨论】:

  • 注意,如果使用 Node.js,这需要 11.0.0 或更高版本。
【解决方案2】:

如果您打算做比这个简单示例更多的组合,那么您可以使用js-combinatorics 包。例如:

const Combinatorics = require('js-combinatorics');

const teams = ['team1', 'team2', 'team3', 'team4'];

const matches = Combinatorics.permutation(teams, 2).toArray();

console.log(matches);

输出是:

[
  [ 'team1', 'team2' ],
  [ 'team2', 'team1' ],
  [ 'team1', 'team3' ],
  [ 'team3', 'team1' ],
  [ 'team2', 'team3' ],
  [ 'team3', 'team2' ],
  [ 'team1', 'team4' ],
  [ 'team4', 'team1' ],
  [ 'team2', 'team4' ],
  [ 'team4', 'team2' ],
  [ 'team3', 'team4' ],
  [ 'team4', 'team3' ]
]

【讨论】:

  • 我认为这是一个不错的选择,我会尝试一下,因为我以后需要更复杂的组合。
【解决方案3】:

如果您想获得所有可能的组合,包括反向重复,您还需要从 0 到数组的长度迭代 j 循环。

for(let i = 0; i < l; i++) 
  for(let j = 0; j < l; j++) {
    if(i == j) continue; // skip the same index
    res.push([arr[i], arr[j]]); 
  }
}

【讨论】:

    【解决方案4】:
    for(var i=0; i<l; ++i)
        {
            for(var j=0; j<l; ++j)
            {
                if(i!=j)
                res.push([arr[i], arr[j]]);
            }
        }
    

    以上代码将生成所有对

    【讨论】:

      【解决方案5】:
      array.flatMap(x => array.map(y => x !== y ? x + ' ' + y : null)).filter(x => x)
      
      

      【讨论】:

        猜你喜欢
        • 2011-08-10
        • 1970-01-01
        • 1970-01-01
        • 2017-08-27
        • 1970-01-01
        • 2013-05-09
        • 2012-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多