我正在尝试执行此Kata-https://www.codewars.com/kata/organize-a-round-robin-tournament/train/javascript。
任务是创建一个组织循环赛的功能。
示例:
buildMatchesTable(4)
应返回如下矩阵:
[
[[1,2], [3, 4]], // first round: 1 vs 2, 3 vs 4
[[1,3], [2, 4]], // second round: 1 vs 3, 2 vs 4
[[1,4], [2, 3]] // third round: 1 vs 4, 2 vs 3
]
到目前为止,我已经列出了所有可能的匹配,但是我将它们放入正确格式的代码不正确,并抛出错误“无法读取未定义的属性'0'”。
我将不胜感激。谢谢你。
function buildMatchesTable(numberOfTeams) {
let pairs = [];
let n = numberOfTeams;
let arr = [];
//create all possible pairs without repeating
for (var i = 1; i <= n; i++){
for (var j = i+1; j <= n; j++){
pairs.push([i,j]);
}
}
//not working
for (var i = 0; i < (n-1); i++){
for (var j = 0; j < pairs.length; j++){
for (var k = 0; k < 2; k++){
if (!arr[i][j][k].includes(pairs[j][0]) && !arr[i][j][k].includes(pairs[j][1])){
arr[i][j].push(pairs[j]);
pairs.splice(j,1);
}
}
}
}
}
buildMatchesTable(6)