17

如果您在阅读问题后能想出一个更好的标题,请随时更改。

因此,作为输入,我有一个整数,它是 2 到 20 之间的偶数。我们称它为 integer $teams。我需要做的是在遵守以下规则的同时生成一个$teams x $teams大小介于 1 和(含)之间的数字矩阵:$teams-1

  1. 对角线(从左上角到右下角)的值为 -1。
  2. 同一数字不得多次出现在同一列或同一行中。
  3. 如果一个数字出现在第 N 列,那么 in 可能不会出现在第 N 行。例如,如果它出现在第 2 列,它可能不会出现在第 2 行,等等。

请注意,我们只查看对角线上方的部分。它下面的部分只是一个反映(每个数字是它的反映 + $teams - 1),对于这个问题并不重要。

前两个条件相当容易完成,但第三个条件让我很生气。我不知道如何做到这一点,特别是因为这个$teams数字可以是 2 到 20 之间的任何偶数。下面给出了为条件 1 和 2 提供正确输出的代码。有人可以帮我解决第 3 个条件吗?

$teams = 6;         //example value - should work for any even Int between 2 and 20
$games = array();   //2D array tracking which week teams will be playing

//do the work
for( $i=1; $i<=$teams; $i++ ) {
    $games[$i] = array();
    for( $j=1; $j<=$teams; $j++ ) {
        $games[$i][$j] = getWeek($i, $j, $teams);
    }
}

//show output
echo '<pre>';
$max=0;
foreach($games as $key => $row) {
    foreach($row as $k => $col) {
        printf('%4d', is_null($col) ? -2 : $col);
        if($col > $max){
            $max=$col;
        }
    }
    echo "\n";
}
printf("%d teams in %d weeks, %.2f weeks per team\n", $teams, $max, $max/$teams);
echo '</pre>';

function getWeek($home, $away, $num_teams) {
    if($home == $away){
        return -1;
    }
    $week = $home+$away-2;
    if($week >= $num_teams){
        $week = $week-$num_teams+1;
    }
    if($home>$away){
        $week += $num_teams-1;
    }

    return $week;
}

当前代码(对于 $teams=6)给出以下输出:

  -1   1   2   3   4   5
   6  -1   3   4   5   1
   7   8  -1   5   1   2
   8   9  10  -1   2   3
   9  10   6   7  -1   4
  10   6   7   8   9  -1
6 teams in 10 weeks, 1.67 weeks per team

如您所见,数字 1 出现在第 2 列和第 2 行中,数字 4 出现在第 5 列和第 5 行等中,这违反了规则 #3。

4

4 回答 4

5

无需任何猜测或回溯即可解决该问题,方法是为 n 队在 n 轮比赛中相互比赛创建一个循环赛时间表,然后由此构建一个表示问题中描述的时间表的数组

为了建立时间表,将 n(这里 6)队分成两排

1 2 3
6 5 4

这是第 1 轮,其中 1 遇到 6,2 遇到 5,3 遇到 4。

然后对于每一轮,轮换除第 1 队以外的其他球队,给出完整的时间表

Round 1    Round 2    Round 3    Round 4    Round 5
1 2 3      1 3 4      1 4 5      1 5 6      1 6 2    
6 5 4      2 6 5      3 2 6      4 3 2      5 4 3  

这可以表示为一个数组,每一行代表一个星期,其中第一列中的团队与最后一个团队相遇,第二个与倒数第二个等。

1 2 3 4 5 6  (Week 1: 1-6, 2-5, 3-4)
1 3 4 5 6 2  (Week 2: 1-2, 3-6, 4-5)
1 4 5 6 2 3  (Week 3: 1-3, 2-4, 5-6)
1 5 6 2 3 4  (Week 4: 1-4, 3-5, 2-6)
1 6 2 3 4 5  (Week 5: 1-5, 4-6, 2-3)

将团队表示为行和列,将周表示为表条目,这变成

-1  1  2  3  4  5
 6 -1  4  2  5  3
 7  9 -1  5  3  1
 8  7 10 -1  1  4
 9 10  8  6 -1  2
10  8  6  9  7 -1 

以下是为不同数量的团队生成此代码的代码:

<?php

function buildSchedule($teams) {
  // Returns a table with one row for each round of the tournament                   
  // Matrix is built by rotating all entries except first one from row to row,       
  // giving a matrix with zeroes in first column, other values along diagonals       
  // In each round, team in first column meets team in last,                         
  // team in second column meets second last etc.                                    
  $schedule = array();
  for($i=1; $i<$teams; $i++){
    for($j=0; $j<$teams; $j++){
      $schedule[$i][$j] = $j==0 ? 0 : ($i+$j-1) % ($teams-1) + 1;
    }
  }
  return $schedule;
}

function buildWeekTable($schedule) {
  // Convert schedule into desired format                                            

  //create n x n array of -1                                                         
  $teams = sizeof($schedule)+1;
  $table = array_pad(array(), $teams, array_pad(array(), $teams, -1));

  // Set table[i][j] to week where team i will meet team j                           
  foreach($schedule as $week => $player){
    for($i = 0; $i < $teams/2 ; $i++){
      $team1 = $player[$i];
      $team2 = $player[$teams-$i-1];
      $table[$team1][$team2] = $team2 > $team1 ? $week : $week + $teams -1;
      $table[$team2][$team1] = $team1 > $team2 ? $week : $week + $teams -1;
    }
  }
  return $table;
}

function dumpTable($table){
  foreach($table as $row){
    $cols = sizeof($row);
    for($j=0; $j<$cols; $j++){
      printf(" %3d", isset($row[$j]) ? $row[$j] : -1);
    }
    echo "\n";
  }
}

$teams = 6;

$schedule = buildSchedule($teams);
$weekplan = buildWeekTable($schedule);
dumpTable($weekplan);
于 2013-04-14T21:51:51.807 回答
3

我不相信有一种确定性的方法可以解决这个问题,而无需让您的程序进行一些反复试验(如果猜测与规则冲突,则猜测然后回溯)。

我的想法是只修改 getWeek() 函数,但将$games数组传递给它,然后:

  1. 创建与我们的元素属于同一行或列的所有矩阵元素的数组
  2. 检查我们的一周是否已经属于同一行或对应的列
  3. 如果是这样,然后使用我提供的公式随机选择它
  4. 在while循环中执行此操作,直到猜测正确,然后继续

我对 4、6、8、10 和 20 个团队进行了测试,效果很好。$week我设置了一个安全机制,如果 while 循环有可能变成无限循环,该机制将设置为 0,但这不会发生。

这是整个代码:

$teams = 10;
    $games = array();   //2D array tracking which week teams will be playing

    //do the work
    for( $i=1; $i<=$teams; $i++ ) {
        $games[$i] = array();
        for( $j=1; $j<=$teams; $j++ ) {
            $games[$i][$j] = getWeek($i, $j, $teams, $games);
        }
    }

    echo '<pre>';
    $max=0;
    foreach($games as $key => $row) {
        foreach($row as $k => $col) {
            printf('%4d', is_null($col) ? -2 : $col);
            if($col > $max){
                $max=$col;
            }
        }
        echo "\n";
    }
    printf("%d teams in %d weeks, %.2f weeks per team\n", $teams, $max, $max/$teams);
    echo '</pre>';

getWeek功能:

function getWeek($home, $away, $num_teams, $games) {
    if($home == $away){
        return -1;
    }
    $week = $home+$away-2;
    if($week >= $num_teams){
        $week = $week-$num_teams+1;
    }
    if($home>$away){
        $week += $num_teams-1;
    }

    $tries=0;
    $problems=array();

    //create array of all matrix elements that have the same row or column (regardless of value)
    foreach($games as $key => $row) {
        foreach($row as $k => $col) {
            if($home==$key || $home==$k || $away==$key || $away==$k)
                $problems[]=$col;   
        }
    }

    while(in_array($week, $problems)) {

        if($home<=$away)
                $week=rand(1,$num_teams-1);
            else
                $week=rand($num_teams,2*($num_teams-1));

            $tries++;
            if($tries==1000){
                $week=0;
                break;
            }
        }

    return $week;
}

这是结果$teams=10

  -1   1   2   3   4   5   6   7   8   9
  10  -1   3   4   5   6   7   8   9   2
  11  12  -1   5   6   7   8   9   1   4
  12  13  14  -1   7   8   9   1   2   6
  13  14  15  16  -1   9   1   2   3   8
  14  15  16  17  18  -1   2   3   4   1
  15  16  17  18  10  11  -1   4   5   3
  16  17  18  10  11  12  13  -1   6   5
  17  18  10  11  12  13  14  15  -1   7
  18  11  13  15  17  10  12  14  16  -1
10 teams in 18 weeks, 1.80 weeks per team
于 2013-04-14T18:35:33.043 回答
0

一种解决方案是将要排除的数字传递给getWeek()一个数组(即,一个包含与当前行等效的列上的所有数字的数组)。

您可以创建这样的排除数组,并将其传递给getWeek()这样的:

//do the work
for( $i=1; $i<=$teams; $i++ ) {
    $games[$i] = array();
    for( $j=1; $j<=$teams; $j++ ) {
        $exclude = array();
        for ( $h=1; $h<=$i; $h++ ) {
           if ( isset($games[$h][$j]) ) {
              $exclude[] = $games[$h][$j];
           }
        }
        $games[$i][$j] = getWeek($i, $j, $teams, $exclude);
    }
}

然后剩下的是检查内部getWeek()是否不包含$exclude数组中传递的数字之一,如下所示:

function getWeek($home, $away, $num_teams, $exclude) {
    //
    // Here goes your code to calculate $week
    //

    if (in_array($week, $exclude)) {
       //the calculated $week is in the $exclude array, so you need
       //to calculate a new value which is not in the $exclude array
       $week = $your_new_valid_value;
    }

    return $week;
}
于 2013-04-14T14:42:47.177 回答
-1

更新:我尝试使用回溯实现解决方案。代码可能需要重写(可能是一个类)并且可以优化事情。

这个想法是遍历所有解决方案,但一旦明确分支违反了三个规则之一,就停止分支。有 6 个团队,在 71 次尝试中找到了解决方案——即使理论上有 759,375 种组合。

请参阅http://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF以计算所需的游戏总数。

<?php
$size = 10;

$gamesPerTeam = $size-1;
$games = ($gamesPerTeam*($gamesPerTeam+1))/2;

$gamePlan = array_fill(0, $games, 1);

function increaseGamePlan(&$gamePlan, $pointOfFailure, $gamesPerTeam) {
    if ($gamePlan[$pointOfFailure] === $gamesPerTeam) {
        $gamePlan[$pointOfFailure] = 1;
        increaseGamePlan($gamePlan, $pointOfFailure-1, $gamesPerTeam);
    } else {
        $gamePlan[$pointOfFailure]++;
    }

}

function checkWeekFor($i, $row, $column, &$pools) {
    if ($column-$row <= 0)
        return '-';

    if (!in_array($i, $pools['r'][$row]) && !in_array($i, $pools['c'][$column]) && !in_array($i, $pools['c'][$row])) {
        $pools['r'][$row][] = $i;
        $pools['c'][$column][] = $i;
        return true;
    }
}

$a = 0;
while (true) {
    $a++;
    $m = [];

    $pools = [
        'r' => [],
        'c' => [],
    ];
    $i = 0;
    for ($row = 0;$row < $size;$row++) {
        $m[$row] = array();
        $pools['r'][$row] = array();
        for ($column = 0;$column < $size;$column++) {
            if ($column-$row <= 0)
                continue;

            if (!isset($pools['c'][$column]))
                $pools['c'][$column] = array();

            if (!isset($pools['c'][$row]))
                $pools['c'][$row] = array();

            $week = $gamePlan[$i];
            if (!checkWeekFor($week, $row, $column, $pools)) {
                for ($u = $i+1;$u < $games;$u++)
                    $gamePlan[$u] = 1;
                increaseGamePlan($gamePlan, $i, $gamesPerTeam);
                continue 3;
            }
            $m[$row][$column] = $week;
            $i++;
        }
    }
    echo 'found after '.$a.' tries.';
    break;
}

?>
<style>
    td {
        width: 40px;
        height: 40px;
    }
</style>
<table cellpadding="0" cellspacing="0">
    <?
    for ($row = 0;$row < $size;$row++) {
        ?>
        <tr>
            <?
            for ($column = 0;$column < $size;$column++) {
                ?>
                <td><?=$column-$row <= 0?'-':$m[$row][$column]?></td>
                <?
            }
            ?>
        </tr>
        <?
    }
    ?>
</table>

它打印:

found after 1133 tries.
-   1   2   3   4   5   6   7   8   9
-   -   3   2   5   4   7   6   9   8
-   -   -   1   6   7   8   9   4   5
-   -   -   -   7   8   9   4   5   6
-   -   -   -   -   9   1   8   2   3
-   -   -   -   -   -   2   3   6   1
-   -   -   -   -   -   -   5   3   4
-   -   -   -   -   -   -   -   1   2
-   -   -   -   -   -   -   -   -   7
-   -   -   -   -   -   -   -   -   -
于 2013-04-14T15:46:09.387 回答