2

我希望我能解释我的问题

我在数组(10x10)上填充了 1 和 0,例如

0000000000
0000000000
00 00000 000
00 00000 000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000

现在我想推另一个数组

例如

11111
11111

在一个特定的位置点上,(3,3)
我用粗体突出了这个位置

0000000000
0000000000
00 11111 000
00 11111 000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000

此外,如果字段上已经有一个值添加它,所以如果我重复这个过程,矩阵将变成这个。

0000000000
0000000000
00 22222 000
00 22222 000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000

我希望有人能指出我正确的方向。我已经玩过一些数组函数,但我无法让它工作。

你有什么建议?

4

3 回答 3

2

沿着这些路线的东西应该这样做:

/**
 * Push a small matrix into a larger matrix.
 * Note: no size restrictions are applied, if $push
 * exceeds the size of $matrix or the coordinates are
 * too large you'll get a jaggy array.
 *
 * @param array $matrix A 2D array of ints.
 * @param array $push   A 2D array <= $matrix to push in.
 * @param int   $x      The starting x coordinate.
 * @param int   $y      The starting y coordinate.
 * @return array The modified $matrix.
 */
function matrix_push(array $matrix, array $push, $x, $y) {
    list($i, $j) = array($x, $y);

    foreach ($push as $row) {
        foreach ($row as $int) {
            $matrix[$i][$j++] += $int;
        }
        $i++;
        $j = $y;
    }

    return $matrix;
}
于 2013-07-05T15:25:31.070 回答
1

对于二维数组,你可以做这样的事情。请注意,从数组的角度来看,您在问题中定义为 (3,3) 实际上是 (2,2)。在这种情况下,输入$xand$y将是 2 和 2。

function replaceArray( $orig, $replace, $x, $y ) {
  //Some safety checks
  //Return false if the array that we replace with exceeds the boundaries of the original array
  if( $x + count( $replace[0] ) > count( $orig[0] ) || $y + count( $replace ) > count( $orig ) ) {
    return false;
  }

  for( $i = 0; $i < count($replace[0]); $i++ ) {
    for( $j = 0; $j < count( $replace ); $j++ ) {
      $orig[ $x + $i ][ $x + $j ] += $replace[ $i ][ $j ];
    }
  }

  return $orig;
}
于 2013-07-05T15:30:22.560 回答
0

哇,这很快:)

你实现它的好方法。这是我的代码也可以解决它,但是还有更多

$array1 = array(0=>array(0,0,0,0,0,0,0,0,0,0,0),
        1=>array(0,0,0,0,0,0,0,0,0,0,0),
        2=>array(0,0,0,0,0,0,0,0,0,0,0),
        3=>array(0,0,0,0,0,0,0,0,0,0,0),
        4=>array(0,0,0,0,0,0,0,0,0,0,0),
        5=>array(0,0,0,0,0,0,0,0,0,0,0),
        6=>array(0,0,0,0,0,0,0,0,0,0,0),
        7=>array(0,0,0,0,0,0,0,0,0,0,0));



$array2 = array(0=>array(1,1,1),
                1=>array(1,1,1),
                2=>array(1,1,1));

$row = 3;
$col = 3;
foreach($array2 AS $valuesToReplace)
{   $col = 3;
    foreach($valuesToReplace AS $value)
    {
        $array1[$row][$col] = $value;
        $col++;
    }
    $row++;
}
于 2013-07-05T15:33:20.333 回答