【问题标题】:Creating matrix of numbers unique in row and column创建行和列中唯一的数字矩阵
【发布时间】:2013-04-15 23:44:08
【问题描述】:

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

所以,作为输入,我有一个整数,它是 2 到 20 之间的偶数。我们称这个整数为$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。

【问题讨论】:

  • 也许有更简单的解决方案,但你可以看看回溯:en.wikipedia.org/wiki/Backtracking
  • 谢谢,但我宁愿先探索更简单的潜在解决方案。回溯看起来肯定可以解决它,但需要付出很多努力,而且在迭代次数方面似乎效率不高(尽管考虑到 $teams 的数量很少,这并不是什么大问题)。
  • 我想到的一件事是当您说“数字出现在第 n 列”时,指的是第一行的nth collumn。好吧,你知道在第一行你有从-1n-1 的数字。当您生成行号x 的数字时,您可以轻松跳过$games[1][x] 中的数字。希望有所帮助;-)
  • @Havelock 我会试试的,谢谢。我怀疑最后一行会有错误的条目,因为那时别无选择。
  • @robert 我想说先尝试在一张纸上得到一个正确的解决方案,然后看看你是否可以在行和列中的数字之间提取一些依赖关系,这会导致你正确的算法。

标签: php algorithm


【解决方案1】:

可以通过为 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);

【讨论】:

  • 我喜欢这个。大多数计划可以是静态的,因为只需要一种解决方案。如果需要随机分组,请随机分组,而不是按时间表随机分组。
  • @Sven 这也是我对随机化的想法。另一种随机化结果的方法是重新排序从buildSchedule 返回的表的行。这是可能的,因为每一行都满足 #2 和 #3 要求(每支球队在给定的一周内只参加一场比赛)。
  • 很好的答案 Terje,比我的好。不过,我认为不可能通过重新排序行来随机化 - 例如,如果您在解决方案中切换第 2 行和第 3 行,则第 1 行将同时出现在第 2 行和第 2 列中。
  • @jovan 我不是在谈论在解决方案中切换行,而是在每行包含团队编号排列的中间表中。切换此表中的两行会导致切换解决方案中相应的周数。
【解决方案2】:

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

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

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

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

这是完整的代码:

$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

【讨论】:

  • 完美的jovan,非常感谢!已接受答案 - 明天将颁发赏金。
  • 好吧,如果有一个解决方案,我宁愿选择不回溯的解决方案 - 而且有......
【解决方案3】:

一种解决方案是向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;
}

【讨论】:

  • 谢谢,我会试试这个并回复你。乍一看,它似乎可以工作,但我仍然怀疑最后一行会出现问题,因为没有什么可跳过的。
  • 不太好用,打印出$exclude 数组并没有显示正确的值,此外,$your_new_valid_value 是什么?正如jovan的回答所示,我认为那里需要一个while循环,而不是if条件。
【解决方案4】:

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

我们的想法是遍历所有解决方案,但一旦发现分支违反了三个规则之一,就立即停止分支。有 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
-   -   -   -   -   -   -   -   -   -

【讨论】:

  • 数字 1 仍然出现在 column2 和 row2 中。
  • Thomas,你有两个额外的“周”(矩阵中的值)。与规则 #3 没有矛盾,因为您将第 6 周和第 7 周添加到组合中。我只需要保留 5 (n-1) 周。
  • @robert 我看不出这怎么可能,因为我的程序应该始终使用尽可能低的值。除非我误解了您的规则之一,否则它们是 1-1 实施的。如果您有有效方案的示例,请发布,我会尝试调整我的代码。
  • @bestprogrammerintheworld,这是问题中要求的反映:“请注意,我们只查看对角线上方的部分。它下面的部分只是反映......”
  • 不,您不应该删除它。这不是此任务的最佳方式,但可以作为其他情况的指南。就像回溯的hello world
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多