Trying to generate n sets of unique pairs from an array without repeating items, creating a set of pairs that uses all items in the array only once.
I am working with javascript. I have an array of say 10 items I need to generate the following:
The code I am using gets tripped up like this:
arrPlayers = [1,2,3,4,5,6,7,8,9,10]
matchups-week-1 = [[1,2],[3,4],[5,6],[7,8],[9,10]]
matchups-week-2 = [[1,3],[2,4],[5,7],[6,8],[ ooops!! ] can't do [9,10] again so this set won't work.
You see how the 9,10 pair paints the code into a corner? You can only produce 4 pairs because 9,10 is not unique.
I thought this would be easy to work out but I am stuck. Any ideas on code that would not paint itself into this "set of 4" corner?
The code I am using. ...admittedly I am grasping at straws. That's why I am asking the question.
function CreateMatchups(player_ids){
//Create array of PLAYER IDs where checkbox = checked
arrPlayers = player_ids.split(", ");
arrOpponents = arrPlayers;
arrPrevUsed = GetPrevUsedPairs();
var arrUsed = [];
var arrTempMatchups = [];
var intNumPlayers = arrPlayers.length;
var blnOddNumberOfPlayers = isOdd(intNumPlayers);
if(blnOddNumberOfPlayers){
arrPlayers.push(9999); //bogus id for placeholder player - fix this
}
for (var i = 0; i < arrPlayers.length; i++) {
player_id = arrPlayers[i];
if(!arrUsed.contains(player_id)){
for (var j = 0; j < arrOpponents.length; j++) {
opponent_id = arrOpponents[j];
if((!arrUsed.contains(opponent_id)) && (!arrUsed.contains(player_id)) && (player_id != opponent_id)){
matchup = player_id + "vs" + opponent_id;
if(!arrPrevUsed.contains(matchup)) {
arrTempMatchups.push(matchup);
arrUsed.push(player_id);
arrUsed.push(opponent_id);
}
}
}
}
}
return arrTempMatchups;
}