在行和列中创建唯一的数字矩阵

时间:2013-04-11 10:17:43

标签: php algorithm

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

所以,作为输入,我有一个整数,它是2到20之间的偶数。让我们调用这个整数$teams。我需要做的是生成一个$teams x $teams大小的数字矩阵,其数字介于1和$teams-1之间(包括),同时遵守以下规则:

  1. 对角线(从左上角到右下角)的值为-1。
  2. 相同的数字可能不会多次出现在同一列或行中。
  3. 如果一个数字出现在N列中,那么in可能不会出现在第N行中。例如,如果它出现在第2列中,它可能不会出现在第2行等中。
  4. 请注意,我们只关注对角线上方的部分。它下面的部分只是一个反映(每个数字是它的反射+ $团队 - 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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:3)

我不相信有一种确定性的方法可以解决这个问题,而不会让你的程序做一些试错(如果猜测与规则冲突,就猜测然后回溯)。

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

  1. 创建与我们的元素
  2. 属于同一行或列的所有矩阵元素的数组
  3. 检查我们的周是否已属于同一行或相应列
  4. 如果是,则使用我提供的公式随机选择
  5. 在while循环中执行此操作直到猜测结果良好,然后继续
  6. 我测试了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
    

答案 2 :(得分: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;
}

答案 3 :(得分:-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
-   -   -   -   -   -   -   -   -   -