如何在循环赛中配对? [英] How to match up pairs in a round robin tournament?
问题描述
我正在制作一个锦标赛应用程序,其中将有4名,6名或8名玩家相互竞争.
这是基于回合的.因此,例如,如果总共有6个玩家,那么将有5个回合,每个回合3对.每个玩家每回合只能出现一次.
我尝试过的
我一直在使用for循环来获取所需的组合,但是如何将这些对分成几轮以免重复呢?到目前为止,这是我所做的事情(将所有组合组合在一起):
<?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;/* 输出:[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"] */
我的问题
有没有一种通用的方式将两对分配成几回合,而玩家却没有在同一回合中出现过一次以上?
示例
- 1 st 回合:12、34、56;
- 2 nd 回合:13、25、46 ...
您可以使用此代码.它基于
玩家1永远不会移动,将位于第2位的玩家从数组中切出,并推入数组的末尾,这意味着它将到达第6位.
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.
What I tried
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"
]*/
My question
Is there any generic way to distribute the pairs into rounds, without players showing up more than once in the same round?
Example
- 1st round: 12, 34, 56;
- 2nd round: 13, 25, 46...
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.
这篇关于如何在循环赛中配对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!