【问题标题】:PHP array - Unique matchingPHP数组 - 唯一匹配
【发布时间】:2011-05-30 15:12:19
【问题描述】:

嘿伙计们,我想知道你是否可以帮助我了解一下我的 PHP 逻辑......

我想根据以下数据生成一个排行榜..

  • 由 user_ids 组成的数值数组
  • 一个带有数值的变量,表示两人之间要玩多少个独特的游戏。

我需要创建一个数组来反映每个独特的游戏..

player1 vs player2 
player1 vs player2
player1 vs player2

但是我不想要这样的欺骗

player2 vs player 1 -这将超过上面作为变量指定的最大游戏限制,即使玩家的顺序不同。

我真的很难理解这个问题的逻辑,所以任何帮助都会很棒..

谢谢,

【问题讨论】:

  • 如果有一个“自制”的规则,即用户 ID 较低的玩家总是排在第一位,那又如何呢?喜欢玩家 1000 与玩家 1001 吗?

标签: php arrays logic numeric


【解决方案1】:

像这样跟踪对,以及他们的匹配:

// $players - the players width ids
// $num_of_matches - max number of matches between 2 players

$match_counter = array();
$matches = array();
foreach ($players as $idA)
{
    foreach ($players as $idB)
    {
        if ($idA != $idB)
        {
            $match_id = $idA < $idB ? $idA."vs".$idB : $idB."vs".$idA;
            if (empty($match_counter[$match_id])) 
                $match_counter[$match_id] = 1
            elseif ($match_counter[$match_id] < $num_of_matches)
                $match_counter[$match_id] += 1;
            $match_id .= "_".$match_counter[$match_id];
            $matches[$match_id] = "player".$idA." vs player".$idB;
        }
    }
}

$matches 将包含所有唯一匹配项。

【讨论】:

    【解决方案2】:

    我希望你这样说:

    $players = array(1, 2, 3);
    $games = 3;
    
    for($i=0; $i<$games; $i++){
        for($j=0; $j<(count($players)-1); $j++){
            for($k=1; $k<count($players); $k++){
                if($j != $k)
                    echo 'player' . $players[$j] . ' - player' . $players[$k] . '<br />';
            }
        }
    }
    

    返回:

    player1 - player2
    player1 - player3
    player2 - player3
    player1 - player2
    player1 - player3
    player2 - player3
    player1 - player2
    player1 - player3
    player2 - player3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多