I'm making a tournament app where a number of (4, 6, or 8) players would be matched up against each other.
It is round based. So if there are for example 6 players in total, there would be 5 rounds with 3 pairs each. Every player can show up only once per round.
I've been using for-loops to get the combinations needed, but how can I separate the pairs into rounds such that they don't repeat? Here is what I have done so far (making every combination):
<?php
$players = [1,2,3,4,5,6];
for($i = 0; $i < count($players); $i++):
for($j = 0; $j < $i; $j++):
$pair1 = $players[$j];
$pair2 = $players[$i];
$pairs[] = $pair1.$pair2;
endfor;
endfor;
/* Output:
[
0 => "12"
1 => "13"
2 => "23"
3 => "14"
4 => "24"
5 => "34"
6 => "15"
7 => "25"
8 => "35"
9 => "45"
10 => "16"
11 => "26"
12 => "36"
13 => "46"
14 => "56"
]*/
Is there any generic way to distribute the pairs into rounds, without players showing up more than once in the same round?
You could use this code. It is based on the scheduling algorithm for round robin:
$players = [1,2,3,4,5,6];
$n = count($players);
for ($r = 0; $r < $n - 1; $r++) {
for ($i = 0; $i < $n / 2; $i++) {
$rounds[$r][] = [$players[$i], $players[$n-1 - $i]];
}
// Perform round-robin shift, keeping first player in its spot:
$players[] = array_splice($players, 1, 1)[0];
}
// shift once more to put array in its original sequence:
$players[] = array_splice($players, 1, 1)[0];
Note that this puts the pairs into sub-arrays. It is not a good idea to concatenate them as strings, as this will just make it harder to extract the individual numbers from them again.
After the above code has run, the array $rounds
is:
[
[[1,6],[2,5],[3,4]]
[[1,2],[3,6],[4,5]]
[[1,3],[4,2],[5,6]]
[[1,4],[5,3],[6,2]]
[[1,5],[6,4],[2,3]]
]
The round-robin shift that happens in the loop, can be visualised like this, where the array is "folded" half-way to also show who is paired with who (in columns):
Player 1 never moves, the player at place 2 is sliced out of the array, and pushed on the end of the array, which means it will arrive in place 6.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments