如何创建这种循环赛国际象棋锦标赛生成器

How to create this round robin chess tournament generator

我有玩家列表,想为 JavaScript 的国际象棋锦标赛创建循环生成器。 循环赛应该像这张图一样,显示了 10 支球队和 6 支球队:

我试图为偶数和奇数轮数创建单独的逻辑,但我未能找到最佳算法:

var list = [1,2,3,4,5,6,7,8,9,10];
var pairing = []
var size = list.length;
var halfSize = size/2;
var evenOrOdd
if (halfSize % 2 != 1) {
    list.push("BYE")
}
for (var i=0 ; i <= size-1 ; i++) {
    var lastOne = list[size]
    if (isEven(i)) {
        var games = []
        for (var j = 0; j <= halfSize-1; j++) {
            if (j == 0) {
                games.push({"home": list[size-1], "away": list[(i+2)/2-1+j]})
          } else {
                if(list[size-j-i/2]==list[size-2] && i>0){
                    games.push({"home": list[j+i/2], "away": list[0]})
                } else {
                    games.push({"home": list[j+i/2], "away": list[(i+2)/2]})
            }
            }
        }
        pairing.push({"round":i+1,"games":games})
    } else {
    }
}
console.log(pairing)

function isEven(num) {
    if (num % 2 == 0)
        return true;
    return false;
}

我得到的结果不像上图中的配对,它只正确地产生了第一轮。

还有一些类似的问题有答案,比如Scheduling algorithm for a round-robin tournament?,但是它们是针对足球比赛的,我想要它是针对国际象棋比赛的:它与足球比赛有一些不同。

如何修正我的国际象棋锦标赛生成器,使其适用于任意数量的玩家?

您可以使用余数运算符 (%) 来使用模块化逻辑,因为很明显一个数字增加,而另一个数字减少。第一个游戏是个例外,最后一个玩家总是参与其中,增加的计数器与之前生成的对相同。它还根据回合的平价交换双方。

这是一种使用 mapArray.from 调用动态创建数组的方法。递增和递减变量在用作索引时更新:

function generatePairings(players) {
    let n = players.length;
    let mod = n - 1;
    let decr = 0;
    let incr = -1;
    let arr = {length: n / 2 - 1}; // n is assumed to be even
    let props = ["away", "home"];
    let template = { home: players[mod], away: players[mod] };
    return players.slice(1).map((_, i) => ({
        round: i + 1,
        games: [
            { ...template, ...{ [props[i % 2]]: players[incr = (incr + 1) % mod] }}, 
            ...Array.from(arr, () => ({
                home: players[incr = (incr + 1) % mod], 
                away: players[decr = (decr + mod - 1) % mod] 
            }))
        ]
    }));
}

console.log(generatePairings([1,2,3,4,5,6]));

或使用 for 循环:

function generatePairings(players) {
    let n = players.length;
    let mod = n - 1;
    let decr = 0;
    let incr = -1;
    let gameCount = n / 2; // n is assumed to be even
    let props = ["away", "home"];
    let template = { home: players[mod], away: players[mod] };
    let pairings = [];
    for (let round = 1; round < n; round++) {
        let games = [{ ...template, 
            ...{ [props[round % 2]]: players[incr = (incr + 1) % mod] }
        }];
        for (let k = 1; k < gameCount; k++) {
            games.push({
                home: players[incr = (incr + 1) % mod], 
                away: players[decr = (decr + mod - 1) % mod] 
            });
        }
        pairings.push({ round, games });
    }
    return pairings;
}

console.log(generatePairings([1,2,3,4,5,6]));