Zig-zag scan an N x N array

前端 未结 8 1381
暗喜
暗喜 2021-01-30 08:40

I have a simple array. The array length always has a square root of an integer. So 16, 25, 36 etc.

$array = array(\'1\', \'2\', \'3\', \'4\' ... \'25\');
         


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 09:22

    This is my take on it. Its similiar to qiuntus's response but more concise.

    function wave($base) {
      $i = 1;
      $a = $base;
      $square = $base*$base;
      $out = array(1);
    
      while ($i < $square) {
        if ($i > ($square - $base)) { // hit the bottom
          $i++;
          $out[] = $i;
          $a = 1 - $base;
        } elseif ($i % $base == 0) { // hit the right
          $i += $base;
          $out[] = $i;
          $a = $base - 1;
        } elseif (($i - 1) % $base == 0) { // hit the left
          $i += $base;
          $out[] = $i;
          $a = 1 - $base;
        } elseif ($i <= $base) { // hit the top
          $i++;
          $out[] = $i;
          $a = $base - 1;
        }
    
        if ($i < $square) {
          $i += $a;
          $out[] = $i;
        }
      }
    
      return $out;
    }
    

提交回复
热议问题