【问题标题】:Increasing the conditions in IF statement with loop PHP, Diagonal Check使用循环 PHP,对角检查增加 IF 语句中的条件
【发布时间】:2021-08-14 08:13:43
【问题描述】:

我有作业要在 PHP 中做这个程序,它需要一个矩阵和关键字,所以它可以在矩阵中对角线找到它们:

这就是第一个矩阵的样子,有很多不同的关键字,例如关键字是“牛肉”和“猪肉”。所以我为一个看起来像这两个例子的输入制作了一个程序:

这里有这两个的正确输入:

这是我的代码,仅适用于第一种情况,我不知道如何创建一个循环来生成越来越多的条件,而不是在 if 语句中用 && 写下所有这些条件。

请给我一些提示:

<?PHP


$input_line = trim(fgets(STDIN));
$input_array = explode(" ",$input_line);

// get mojiban
$mojiban = array();
for($ix=0; $ix<$input_array[0];$ix++){
    $mojiban[] = str_split(trim(fgets(STDIN)));
}

//get words
    $words = array();
    for( $kx = 0; $kx < $input_array[1]; $kx++ ){
    $words[] = trim(fgets(STDIN));
}

////check verticales
//get word
    $wordCharArray = array();
for($dx=0; $dx < $input_array[1]; $dx++){
    $wordCharArray = str_split($words[$dx]);

//looping and checking
    
    for ( $line = 0; $line < $input_array[0] ; $line++) {
        for ( $column = 0; $column < $input_array[0] ; $column++ ){
           // for ($wordsNumber = 0; $wordsNumber < $input_array[1] ; $wordsNumber++){
            
                if ($mojiban[$line][$column] == $wordCharArray[0] && $mojiban[$line+1][$column+1] == $wordCharArray[1]) {
                    echo ($column+1)." ".($line+1)."\n";
                
            //}
        }
    }
}

提前致谢!

【问题讨论】:

  • 您可以implode()矩阵的行或列并做strpos($line, $word),而不是将输入拆分为字符并将每个字符与矩阵进行比较
  • 将其分成单独的步骤。首先编写代码/函数,允许您从起始坐标 x/y 检查矩阵中是否存在给定的关键字。这很简单——只要关键字有字符,就循环,检查当前字符是否设置在给定位置,然后将一个添加到 x 和 y,然后继续检查下一个字符。一旦你找到一个不匹配的字符,你就知道这个关键字在这个位置不存在,你可以把整个事情打断。 […]
  • [...] 如果您可以循环到最后,遍历关键字的所有字符并每次找到匹配项 - 然后关键字设置在您开始时的原始 x/y 坐标。然后,接下来,您需要将此测试应用于所有可能的起始位置 - 这意味着两个嵌套循环,在 x 和 y 坐标上。你当然应该确保,你没有超过每个方向的最大数组索引。这可以在你的函数中实现,检查关键字是否设置在特定的 x/y 坐标,[…]
  • [...] 或在 x/y 坐标上的这两个循环中 - 如果您的关键字长 4 个字符,而矩阵宽 6 个字符 - 那么您只需要检查 x= 0,x=1 和 x=2,因为对于 x>=3,单词将不再适合开头。 (是的,你应该使用从零开始的索引。如果你想通过计算从 1 开始的行和列来呈现结果,那么之后添加 1。)
  • @CBroe 在您的评论必须分为三个部分的时候,您可能应该停下来想想它是否应该是一个答案,特别是如果您正在描述如何解决问题,而不是如何澄清问题。

标签: php arrays loops if-statement matrix


【解决方案1】:

这是您现在的问题的解决方案,它只检查对角线元素。您可以从下面根据需要进行重构。

有许多不同的解决方案,但我粘贴的代码解决方案首先检查数组中的字符匹配。如果有匹配,它会从找到第一个元素的位置开始对角线检查元素。

<?php

// First martix
// $searchWords = ["BEEF", "PORK"];
// $matrix = ["HPPLLM", "UROQUV", "FBSRZY", "DPEFKT", "GBBEUY", "EMCQFY"];

// Second martix
$searchWords = ["ABA", "BAB"];
$matrix = ["ACEG", "HBDF", "EGAC", "DFHB"];

// returns true if it diagonally matches the element in matrix from start row
function checkDiagonallyForString(string $search, array $matrix, int $startRow, int $firstMatchPosition)
{
    $endRow = $startRow + (strlen($search) - 2);
    $finding = true;

    foreach (range($startRow, $endRow) as $searchIndex => $rowValue) {
        if (!$finding) {
            break;
        }
        $char = $search[$searchIndex + 1];
        $finding = $matrix[$rowValue][$firstMatchPosition + $searchIndex] == $char;

    }
    return $finding;
}

// format: [word: [column, row]]
$found = [];

foreach ($matrix as $row => $matrixString) {
    if (!count($searchWords)) {
        break;
    }
    foreach ($searchWords as $wordRow => $word) {
        $position = strpos($matrixString, $word[1]);
        if ($position != false) {
            if (checkDiagonallyForString($word, $matrix, $row, $position)) {
                // $position = column of matrix
                // $row = row of matrix
                $found[$word] = [$position, $row];
                unset($searchWords[$wordRow]);
            }
        }
    }

}

// Pretty output
echo "<pre>";
print_r($found);

foreach ($found as $word => $indexes) {
    echo $word . " " . implode(" ", $indexes) . "\n";
}

结果是:

注意:这是一个完整的答案,但在复制和粘贴之前,请尝试获得一个大致的想法并尝试自己解决它。这不是唯一的方法。

【讨论】:

    【解决方案2】:

    我们可以使用 cmets 的implode 策略。以下是示例:click。

    代码:

    // First martix
    $searchWords = ["BEEF", "PORK"];
    $matrix = ["HPPLLM", "UROQUV", "FBSRZY", "DPEFKT", "GBBEUY", "EMCQFY"];
    
    // Second martix
    // $searchWords = ["ABA", "BAB"];
    // $matrix = ["ACEG", "HBDF", "EGAC", "DFHB"];
    
    $matrixStr = implode('', $matrix);
    $matrixSize = count($matrix);
    $positions = [];
    
    foreach ($searchWords as $wordIdx => $word) {
        $wordSize = strlen($word);
        $found = false;
        for ($y = 0; $y <= $matrixSize - $wordSize && !$found; $y++) {
            for ($x = 0; $x <= $matrixSize - $wordSize && !$found; $x++) {
                $allLettersOk = true;
                for ($l = 0; $l < $wordSize; $l++) {
                    if ($matrixStr[$y * $matrixSize + $x + $l * $matrixSize + $l] != $word[$l]) {
                        $allLettersOk = false;
                        break;
                    }
                }
                if ($allLettersOk) {
                    $positions[$word] = [$x + 1, $y + 1];
                    $found = true;
                }
            }
        }
    }
    
    foreach ($positions as $word => $indexes) {
        echo $word . " " . implode(" ", $indexes) . "\n";
    }
    

    如果您需要对此代码的描述 - 写评论。

    【讨论】:

      【解决方案3】:
      // First martix
      $searchWords = ["BEEF", "PORK"];
      $matrix = ["HPPLLM", "UROQUV", "FBSRZY", "DPEFKT", "GBBEUY", "EMCQFY"];
      
      // Second martix
      // $searchWords = ["ABA", "BAB"];
      // $matrix = ["ACEG", "HBDF", "EGAC", "DFHB"];
      
      $matrixStr = implode('', $matrix);
      $matrixSize = count($matrix);
      $positions = [];
      
      foreach ($searchWords as $wordIdx => $word) {
          $wordSize = strlen($word);
          $found = false;
          for ($y = 0; $y <= $matrixSize - $wordSize && !$found; $y++) {
              for ($x = 0; $x <= $matrixSize - $wordSize && !$found; $x++) {
                  $allLettersOk = true;
                  for ($l = 0; $l < $wordSize; $l++) {
                      if ($matrixStr[$y * $matrixSize + $x + $l * $matrixSize + $l] != $word[$l]) {
                          $allLettersOk = false;
                          break;
                      }
                  }
                  if ($allLettersOk) {
                      $positions[$word] = [$x + 1, $y + 1];
                      $found = true;
                  }
              }
          }
      }
      
      foreach ($positions as $word => $indexes) {
          echo $word . " " . implode(" ", $indexes) . "\n";
      }
      

      【讨论】:

        【解决方案4】:

        你的$input_array 包含你的矩阵,在每个位置你都有一个字符,像这样

        $input_array = [
            ['H', 'P', 'P', 'L', 'L', 'M'],
            ['U', 'R', 'O', 'Q', 'U', 'V'],
            ['F', 'B', 'S', 'R', 'Z', 'Y'],
            ['D', 'P', 'E', 'F', 'K', 'T'],
            ['G', 'B', 'B', 'E', 'U', 'Y'],
            ['E', 'M', 'C', 'Q', 'F', 'Y'],
        ];
        

        为简单起见,我们假设您还有一个数组数组。我知道你有字符串,但是字符串操作会使这个解决方案难以阅读,我们对算法最感兴趣,所以,为了便于理解,我不会从你的实际数据结构开始,但如果你有困难会回答问题将此实施到您的解决方案中:

        $words = [
            ['B', 'E', 'E', 'F'],
            ['P', 'O', 'R', 'K']
        ];
        

        注意牛肉和猪肉的长度相同,但我们不要假设所有单词的长度都相同。

        //Computing row count so it can be reused
        $rowCount = count($input_array);
        //Computing the column count so it can be reused
        //We assume that each row of the matrix has the same number of columns
        $colCount = count($input_array[0]);
        //Looping the rows
        for ($row = 0; $row < $rowCount; $row++) {
            //Looping the columns of the row
            for ($column = 0; $column < $colCount; $column++) {
                //Computing the max length of allowed words
                $maxLength = min($rowCount - $row, $colCount - $col);
                //Looping the words
                for ($wIndex = 0; $wIndex < count($words); $wIndex++) {
                    //Storing the length of the current word for later use
                    $charCount = count($words[$wIndex]);
                    //We avoid checking for the presence of words that are
                    //Longer than the current position allows
                    if ($charCount <= $maxLength) {
                        //match is initialilzed with true and will be set false at
                        //the first mismatch. If no mistmatch is found, then we know
                        //that the word is present at the current position
                        $match = true;
                        //Looping the word's characters and check for possible
                        //mismatches
                        //Notice that we stop the loop either at the first mismatch
                        //or at the last character if there is no mismatch
                        for ($cIndex = 0; $match && ($cIndex < $charCount); $cIndex++) {
                            //If the word character at cIndex offset mismatches
                            //the character of input array at the same offset, starting
                            //from the [$row][$column] position, then it mismatches
                            if ($words[$wIndex][$cIndex] !== $input_array[$row + $cIndex][$column + $cIndex]) $match = false;
                        }
                        if ($match) {
                            //Say the word
                            echo implode("", $words[$wIndex]) . " found at row " . ($row + 1) . ", column " . ($column + 1);
                        }
                    }
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-06-05
          • 2014-02-05
          • 1970-01-01
          • 2021-04-18
          • 1970-01-01
          • 1970-01-01
          • 2022-06-21
          • 2017-12-08
          相关资源
          最近更新 更多