1 回答

TA貢獻1854條經驗 獲得超8個贊
為了獲得最大可能游戲回合數的所有組合(每個玩家只與其他玩家一起玩一次),我用 https://math.stackexchange.com/a/3094469 作為靈感。
// From: https://stackoverflow.com/a/12646864/9487478
const shuffleArray = (array) => {
let shuffledArray = [...array];
for (let i = shuffledArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
}
return shuffledArray;
}
// Note: The number of players needs to be even.
let createGames = (playerArr) => {
let players = [...playerArr];
const teamsPerRound = [],
rounds = mod = players.length - 1,
gamesPerRound = 4,
// Helper for checking how often a player is confronted with another player.
confrontations = Array(players.length).fill().map(x => Array(players.length).fill(0));
// Inspired by: https://math.stackexchange.com/a/3094469
// Create as many unique teams as possible, whereas within a round every player occurs exactly once.
for (let i = 0; i < rounds; i++) {
let team = [[
players.length - 1,
(players.length + i) % mod
]];
for (let k = 1; k < (players.length / 2); k++) {
team.push([
(players.length + i + k) % mod,
(players.length + i - k) % mod
]);
}
teamsPerRound.push(team);
console.log(`Teams-Round ${i+1}`, JSON.stringify(team));
}
// Now that we have teams, we can create the games. Let's shuffle the teams per round before to ensure it's more random.
const games = shuffleArray(teamsPerRound).map(teams => {
let roundMatches = [];
teams = shuffleArray(teams);
for (let i = 0; i < teams.length/2; i++) {
let first = teams[i], second = teams[teams.length - 1 - i];
roundMatches.push({
team1: first.map(x => ({...players[x]})),
team2: second.map(x => ({...players[x]}))
})
// Helper for checking how often a player is confronted with another player.
first.forEach(x => second.forEach(y => (confrontations[x][y]++, confrontations[y][x]++)));
}
return roundMatches;
});
confrontations.forEach((x,i) => console.log(`Confrontations (playerIndex: ${i})`, JSON.stringify(x), x.reduce((acc, val) => acc += val)));
return games;
}
var players = [
{ id: 1, name : 'player1'},
{ id: 2, name : 'player2'},
{ id: 3, name : 'player3'},
{ id: 4, name : 'player4'},
{ id: 5, name : 'player5'},
{ id: 6, name : 'player6'},
{ id: 7, name : 'player7'},
{ id: 8, name : 'player8'},
{ id: 9, name : 'player9'},
{ id: 10, name : 'player10'},
{ id: 11, name : 'player11'},
{ id: 12, name : 'player12'},
{ id: 13, name : 'player13'},
{ id: 14, name : 'player14'},
{ id: 15, name : 'player15'},
{ id: 16, name : 'player16'}
];
const games = createGames(players);
console.log("Matches", games);
添加回答
舉報