0

我有玩家列表,想用 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;
}

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

还有一些其他类似的问题有答案,例如循环赛的调度算法?,但它们是用于足球比赛的,我希望它用于国际象棋比赛:与足球相比,它有一些不同。

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

4

1 回答 1

2

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

这是一种使用 somemapArray.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]));

于 2021-07-13T21:26:30.173 回答