This is more of a logic question than a coding question, but for everyones information I'm working in Javascript.
I need to programmatically create a 14 week schedule between 12 teams that abides by the following rules: -Each team plays each other team at least once. -No team plays another team more than twice -Each team plays 14 games
I tried looping through the each player, creating the matches for each week (Game 1 - Player 1 against Player 2, Game 2 - Player 1 against Player 3 etc.) and then checking that the current player isn't already playing in a game so (Game 1 - SKIP (Player 2 already playing), Game 2 - Player 2 against Player 4 (player 3 already playing), Game 3 - Player 2 against Player 5) so on. So it creates the entire schedule for one team, then moves on to the next team etc.
Works fine, BUT when I add the logic to check that no player plays another player more than twice it breaks and enters an endless cycle.
I tried going through each Week and creating the matchups like that (Game1 - Ply1 vs Ply2, Game2 - Ply3 vs Ply4, Game3 etc. checking that the player is not already playing a game, but again it broke when adding the qualifiers.
Any suggestions or pointing in the right direction is much appreciated! I can store the UserIDs in key value pairs or as an array so those are not limiting factors in any solution.
Desired Final Result is something like this:
Schedule:{
Week1:{
Game1:{
Play1: somePlayer,
Play2: someOtherPlayer
},
Game2:{
Play1: somePlayer1,
Play2: someOtherPlayer1
},
Game3:{
Play1: somePlayer2,
Play2: someOtherPlayer2
}
//etc. and so on with 6 games per week for 14 weeks.
}
}
Basic skeleton of the solution that got me the closest(first method):
let userArray = [1,2,3,4,5,6,7,8,9,10,11,12]
let schedule = {}
for(let x=0; x < userArray.length ; x++){
for(let y = 0; y < 14; y++){
//Check if schedule['WK'+y] exists and if not create it.
//Check if userArray[x] is playing in any existing games in schedule['WK'+y]
//Check if userArray[x+1] is playing in any existing games in schedule['WK'+y]
//IF YES - TRY userArray[x+2] etc (loop back to 0 if x+y is >12)
//IF NO - CREATE schedule['WK'+y]['Game'+x] = {Play1: userArray[x],Play2:userArray[x+whatever is accepted]
}
}
(Game1 - Ply1 vs Ply2, Game2 - Ply3 vs Ply4, Game3 etc)
Maybe you want to create like this..
let userArray = [1,2,3,4,5,6,7,8,9,10,11,12]
let oneGame2Team = userArray.length/2
let schedule = {}
let i = 0
for(let k = 1; k <= 14; k++){
schedule[`Week${k}`] = {}
let newWeek = schedule[`Week${k}`]
for(let j = 0; j < oneGame2Team; j++) {
let firstPlayer = `Play${userArray[i]}`
let secondPlayer = `Play${userArray[i+=1]}`
newWeek[`Game${j+1}`] = {}
newWeek[`Game${j+1}`][firstPlayer] = `SomePlayer${j}`
newWeek[`Game${j+1}`][secondPlayer] = `SomePlayer${j}`
i++
}
i = 0
}
console.log(schedule)