我有一个团队阵列:
var teams = [a, b, c, d]
我需要一个函数来生成所有可能的匹配对,
例如,如果a
与b
一起播放,则c
会以d
格式播放此格式:
[{ team1: a, team2: b }, { team1: c, team2: d }]
然后4支球队的最终结果如下:
var matches = {
0: [{ team1: a, team2: b }, { team1: c, team2: d }]
1: [{ team1: b, team2: c }, { team1: a, team2: d }]
2: [{ team1: c, team2: a }, { team1: d, team2: b }]
}
团队数量始终为偶数且大于3(4,6,8,...)
答案 0 :(得分:1)
一种简单的方法,迭代直到每支球队都与他的所有敌人作战:
var teams = ["a", "b", "c", "d"];
teams = teams.map(id => ({id}));
teams.forEach(team => team.enemies = teams.filter(enemy => enemy !== team));
const matches = [];
while(teams.some(team => team.enemies.length)){
const playing = [];
for(const team of teams){
if(playing.includes(team)) continue;
const enemy = team.enemies.find(enemy => !playing.includes(enemy));
if(!enemy) continue;
team.enemies.splice(team.enemies.indexOf(enemy),1);
enemy.enemies.splice(enemy.enemies.indexOf(team), 1);
//console.log(team.id, enemy.id, playing.map(t => t.id));
playing.push(team, enemy);
}
if(playing.length) matches.push(playing.map(t => t.id))
}
console.log(matches);
每场比赛可以将比赛分成两队
答案 1 :(得分:0)
我认为这是一个非重复对的一般问题。
var teams = ["a", "b", "c", "d"]
function possibleMatches(teams) {
for (var firstTeam = 0; firstTeam < teams.length; firstTeam++) {
for (var secondTeam = firstTeam + 1; secondTeam < teams.length; secondTeam++) {
console.log("Your firstTeam and second Team", teams[firstTeam], teams[secondTeam])
}
}
}
possibleMatches(teams)