I'm trying to create a match-up schedule, where teams of players compete against each other. The issue is that there can be any number of teams (minimum of 2). On average I think there will probably be 4 teams of 4 players that compete. Players on the same team will never compete against each other. Ideally each player should verse every other player (not in the same team) at least once.
Here is what I did for a 1v1 approach:
var matchupEl = document.getElementById('matchup');
var match = [];
var allTeams = [
{ teamname: "team charlie", playername: "Will" },
{ teamname: "team charlie", playername: "Lil" },
{ teamname: "team charlie", playername: "Elvis" },
{ teamname: "team charlie", playername: "Freddie" },
{ teamname: "team alpha", playername: "Adam" },
{ teamname: "team alpha", playername: "Morgan" },
{ teamname: "team alpha", playername: "Marshall" },
{ teamname: "team alpha", playername: "Michael" },
{ teamname: "team delta", playername: "Jennifer" },
{ teamname: "team delta", playername: "Chris" },
{ teamname: "team delta", playername: "Paris" },
{ teamname: "team delta", playername: "Macaulay" },
{ teamname: "team beta", playername: "Jet" },
{ teamname: "team beta", playername: "Joe" },
{ teamname: "team beta", playername: "Frank" },
{ teamname: "team beta", playername: "Bob" }
];
let queue = allTeams.map(object => ({ ...object })); // non-reference copy
while (queue.length > 0) {
for (let i = 0; i < queue.length; i++) {
if (queue[0].teamname == queue[i].teamname) {
continue;
} else {
match.push({ team1: queue[0], team2: queue[i] });
}
}
queue.splice(0, 1);
}
for (let j = 0; j < match.length; j++) {
matchupEl.textContent += match[j].team1.playername + ' vs. ' + match[j].team2.playername + "\r\n";
}
#matchup {
white-space: pre;
}
<div id='matchup'></div>
What that does is it starts at the first player and loops through, skipping if the player is on the same team. At the end they are removed from the queue, and it repeats. It works fine but my brain starts to break down when considering more than 1v1. Perhaps I could select combinations from this list? How would you approach this problem?