[英]Find all possible set of two combinations in array
Given an array of size n which will be even always, I need to output all possible combinations of 2 pair elements.给定一个大小为 n 的数组,它总是偶数,我需要输出 2 对元素的所有可能组合。
I have this:我有这个:
let teams = ["team1","team2","team3","team4"]
what I tried:我试过的:
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' ]
This seems fine but some are missing for example I don't see the following :这看起来不错,但有些缺失,例如我没有看到以下内容:
[ 'team2', 'team1' ]
[ 'team3', 'team1' ]
[ 'team3', 'team2' ]
[ 'team4', 'team1' ]
[ 'team4', 'team2' ]
[ 'team4', 'team3' ]
So my expected output is the above and previous result in the code I posted above.所以我的预期输出是上面和我上面发布的代码中的先前结果。
Notice that I don't need them in particular order as long as I get all the possible combinations.请注意,只要我获得所有可能的组合,我就不需要它们的特定顺序。
Functional JS:函数式JS:
let teams = ["team1", "team2", "team3", "team4"]; var result = teams.flatMap( (v) => teams. filter( w => v!=w ). map ( w => [v, w] ) ); console.log(result);
If you intend to do more combinatorics than this simple example, then you can use the js-combinatorics package.如果您打算做比这个简单示例更多的组合,那么您可以使用js-combinatorics包。 For example:
例如:
const Combinatorics = require('js-combinatorics');
const teams = ['team1', 'team2', 'team3', 'team4'];
const matches = Combinatorics.permutation(teams, 2).toArray();
console.log(matches);
Output is:输出是:
[
[ 'team1', 'team2' ],
[ 'team2', 'team1' ],
[ 'team1', 'team3' ],
[ 'team3', 'team1' ],
[ 'team2', 'team3' ],
[ 'team3', 'team2' ],
[ 'team1', 'team4' ],
[ 'team4', 'team1' ],
[ 'team2', 'team4' ],
[ 'team4', 'team2' ],
[ 'team3', 'team4' ],
[ 'team4', 'team3' ]
]
If you want to get all the possible combinations including reverse duplicates, you need to iterate j loop from 0 to array's length as well.如果您想获得所有可能的组合,包括反向重复,您还需要将 j 循环从 0 迭代到数组的长度。
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]]);
}
}
for(var i=0; i<l; ++i)
{
for(var j=0; j<l; ++j)
{
if(i!=j)
res.push([arr[i], arr[j]]);
}
}
Above code will generate all pairs上面的代码将生成所有对
array.flatMap(x => array.map(y => x !== y ? x + ' ' + y : null)).filter(x => x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.