Reputation: 1433
I have coded up a league schedule so that 12 teams are playing a total of 192 games (4 times each against conference opponents, 2 times each against cross-conference opponents). I have also shuffled those games.
My final step is to divide those 192 games into 16 weeks of 6 games each. But, it's important that each team only appear once in any given week (i.e. - only play one game per week). This is the part I'm stuck on.
My schedule array looks something like this:
let schedule = ["a : b", "c : d", "e : f", "g : h", "i : j", "k : l", "m : n", "o : p", "q : r", "s : t", "u : v", "x : y", "a : c", "d : f", "g : i", "l : o"]; // remember, this is actually 192 elements long
From this array (just remember it has 192 elements, so it's larger than the above, which is an example to show the data structure) I want to generate week1
, which is an array containing 6 of the elements from the schedule
array, like so:
let week1 = ["a : b", "c : d", "e : f", "g : h", "i : j", "k : l"];
The above is what I want as a result. However, I can't just use schedule.slice(0, 6)
to get 6 elements, because I can end up with teams playing twice, like so:
let week1 = ["a : b", "c : d", "a : e", "f : g", "h : i", "j : k"]; // Notice "a" is playing twice here, which I do not want.
So, the question is, how can I take 6 games from my array of 192 games, but ensure that each team only appears once in that array of 6 games?
Upvotes: 0
Views: 49
Reputation: 138267
const games = ["a : b", "c : d", "e : f", "g : h", "i : j", "k : l", "m : n", "o : p", "q : r", "s : t", "u : v", "x : y", "a : c", "d : f", "g : i", "l : o"];
const teamsTaken = new Set();
const result = [];
for(const game of games) {
if(result.length >= 6) break;
const [teamA, teamB] = game.split(" : ");
if(teamsTaken.has(teamA) || teamsTaken.has(teamB)) continue;
teamsTaken.add(teamA);
teamsTaken.add(teamB);
result.push(game);
}
console.log(result);
Use a Hashtable to exclude duplicates.
Upvotes: 3