我正在尝试执行此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,0]数组,现在正尝试将正确的对局推向该对局。我最终将删除[0,0]元素。
我认为这一行需要一些调整,但无法弄清楚它是如何不正确的:
if (!arr[i][j].includes(pairs[k][0]) && !arr[i][j].includes(pairs[k][1])){
我将不胜感激。谢谢你。
function buildMatchesTable(numberOfTeams) {
let pairs = [];
let n = numberOfTeams;
//create array of the correct size with [0,0] arrays as placeholders
let arr = [...Array(n-1)].map(v => Array(n/2).fill([0, 0]));
//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]);
}
}
//cycle through arr and push pairs[k] to arr[i] when both elements of pairs[k] don't exist in arr[i][j].
for (var i = 0; i < (n-1); i++){
for (var j = 0; j <= n/2; j++){
for (var k = 0; k < pairs.length; k++){
if (!arr[i][j].includes(pairs[k][0]) && !arr[i][j].includes(pairs[k][1])){
arr[i].push(pairs[k]);
pairs.splice(k,1);
}
}
}
}
console.log(pairs);
console.log(arr);
}
buildMatchesTable(4)