如何在 PHP 中随机填充单个锦标赛淘汰赛而不重复?

Posted

技术标签:

【中文标题】如何在 PHP 中随机填充单个锦标赛淘汰赛而不重复?【英文标题】:How to populate a single tournament elimination randomly in PHP without repeat? 【发布时间】:2015-09-02 23:11:37 【问题描述】:

如果我有这个:

$players = array("A","B","C","D","E","F","G","H","I","J","L","M","N","O","P","Q");

例如,我如何填充单个锦标赛淘汰赛:

Matche 1: AxL
Matche 2: CxJ
Matche 3: HxQ
.
.
.
Matche 8: ExP

16 名玩家 = 8 场比赛

我也试试这个代码和其他代码:

<?php

$players = array("A","B","C","D","E","F","G","H","I","J","L","M","N","O","P","Q");
shuffle ($players);

foreach($players as $key=>$value)

    echo $value.','.$value.'<br>';


?>

【问题讨论】:

这不是一个代码编写服务,但如果你尝试编写一些东西,你可能会在这里找到一些帮助。 shuffle 播放器数组并分配给他们 0x1,2x3... 分享你的代码,到目前为止你尝试了什么? $value) echo $value.','.$value.''; ?> 我试过了,但是很多代码都不能正常工作 【参考方案1】:

这应该适合你:

只需 shuffle() 您的数组,然后将 array_chunk() 分成 2 个一组,例如

<?php

    $players = ["A","B","C","D","E","F","G","H","I","J","L","M","N","O","P","Q"];
    shuffle($players);
    $players = array_chunk($players, 2);

    foreach($players as $match => $player)
        echo "Match " . ($match+1) . ": " . $player[0] . "x" . $player[1] . "<br>";

?>

【讨论】:

如何使用:array(8) [0]=> object(stdClass)#4 (2) ["idPlayer"]=> string(1) "7" ["namePlayer "]=> string(8) "玩家 3" [1]=> object(stdClass)#5 (2) @DoXuanNguyen 预期的输出是什么?【参考方案2】:

使用suffle函数随机排列玩家的顺序,以2步读取数组

shuffle($players);

for ($x = 0; $x < count($players); $x += 2) 
  echo "Match " . (($x/2)+1) . ": " . $players[$x] . "x" . $players[$x+1] . "\n";

【讨论】:

以上是关于如何在 PHP 中随机填充单个锦标赛淘汰赛而不重复?的主要内容,如果未能解决你的问题,请参考以下文章

双淘汰赛的数据结构

Silverlight 4 - 锦标赛风格视图(淘汰赛,树)

带有用户输入的锦标赛括号(php?)

单场淘汰赛算法

CodeM资格赛2

用ajax和php提交表单