gpt4 book ai didi

javascript - 足球赛程javascript算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:11:37 25 4
gpt4 key购买 nike

我有一个包含团队的数组:

var teams = [a, b, c, d]

我需要一个函数来生成所有可能的配对,例如,如果 ab 一起玩,则 cd 一起玩,格式如下:

[{ 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 , ...)

最佳答案

一种简单的迭代方法,直到每个团队都与他的所有敌人战斗:

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

每场比赛可能分为 2 支球队进行比赛

关于javascript - 足球赛程javascript算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47961077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com