Making all possible pairs from the elements in a list and then sorting them evenly

So, I have 3 to 8 players, I want each of them to play against all other 1 versus 1. Matches are played sequentially one at a time. The order of the pair is not important (a vs b == b vs a).

I create matchup pairs in a simple nested loop in which I loop over the players and concatenate the current index with all of the following indices.

The problem is that Player 1 will play all of their matches and then have nothing to do while Player 8 will have to wait.

Is there a way to distribute pairs evenly so that all players have equal downtime?

I am currently randomizing an array containing pairs, but I am looking for a better way.

+3


source to share


2 answers


You can use Round-robin tournament scheduling algorithm .



The circle method is a standard algorithm for scheduling a round robin tournament. All participants are assigned to numbers and then in the first round:

Round 1. (1 plays 14, 2 plays 13, ...)

 1  2  3  4  5  6  7
14 13 12 11 10  9  8    

      

then correct one of the participants in the first or last column of the table (number one in this example) and rotate the others clockwise one position.

Round 2. (1 plays 13, 14 plays 12, ...)

 1 14  2  3  4  5  6
13 12 11 10  9  8  7 

      

Round 3. (1 plays 12, 13 plays 11, ...)

 1 13 14  2  3  4  5
12 11 10  9  8  7  6    

      

until you return to the starting position

Round 13. (1 plays 2, 3 plays 14, ...)

 1  3  4  5  6  7  8
 2 14 13 12 11 10  9

      

+3


source


Store the matches in order in the array, then shuffle it like this

function shuffle(a) {
for (let i = a.length; i; i--) {
    let j = Math.floor(Math.random() * i);
    [a[i - 1], a[j]] = [a[j], a[i - 1]];
}

      

}



And then use it like this:

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

      

Taken from here

0


source







All Articles