JSFiddle - React, Tailwind, and code Playground
JavaScript
let players = [
{
name: 'juan',
uid: '1'
},
{
name: 'estebi',
uid: '2'
},
{
name: 'camilo',
uid: '3'
},
{
name: 'sebas',
uid: '4'
},
{
name: 'helen',
uid: '5'
}/*,
{
name: 'jenni',
uid: '6'
}*/
]
// Find out how many teams we want fixtures for
let numberPlayers = players.length
// If odd number of players add a "ghost".
let ghost = false
if (numberPlayers % 2 == 1) {
numberPlayers++
ghost = true
}
// Generate the fixtures using the cyclic algorithm.
let totalRounds = numberPlayers - 1
let matchesPerRound = numberPlayers / 2
let rounds = {}
for (let round = 0; round < totalRounds; round++) {
for (let match = 0; match < matchesPerRound; match++) {
let home = (round + match) % (numberPlayers - 1)
let away = (numberPlayers - 1 - match + round) % (numberPlayers - 1)
// Last player stays in the same place while the others
// rotate around it.
if (match == 0) {
away = numberPlayers - 1
}
// Add one so players are number 1 to players not 0 to players - 1
// upon display.
if (!rounds[round]) rounds[round] = {}
rounds[round][match] = (home + 1) + " v " + (away + 1)
}
}
// Interleave so that home and away games are fairly evenly dispersed.
let interleaved = {}
let evn = 0;
let odd = (numberPlayers / 2)
for (let i = 0; i < totalRounds; i++) {
if (i % 2 == 0) {
interleaved[i] = rounds[evn++]
} else {
interleaved[i] = rounds[odd++]
}
}
rounds = interleaved
// Last team can't be away for every game so flip them
// to home on odd rounds.
for (let round = 0; round < totalRounds; round++) {
if (round % 2 == 1) {
rounds[round][0] = flip(rounds[round][0])
}
}
console.log('rounds end: ', rounds)
function flip(match) {
let components = match.split(" v ")
return components[1] + " v " + components[0]
}