Reputation: 466
I hope I can explain my problem
I have on array(10x10) filled with 1 and 0 e.g.
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000
Now I'd like to push another array
e.g.
11111
11111
into it on a specific position point (3,3)
I've highlighted the position in bold
0000000000
0000000000
0011111000
0011111000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000
Futhermore, if there is already a value on the field add it, so if I repeat the process the matrix will become this.
0000000000
0000000000
0022222000
0022222000
0000000000
0000000000
0000111100
0000000000
1111000000
0000000000
I hope someone can point me in the right direction. I've already played with some array functions, but I can't get it to work.
What do you suggest?
Upvotes: 2
Views: 194
Reputation: 466
Wow thats was fast :)
Nice way you've implemented it. Here is my code that solve it too, but with some line more
$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++;
}
Upvotes: 0
Reputation: 522626
Something along these lines should do it:
/**
* 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;
}
Upvotes: 2
Reputation: 20755
For a 2-dimensional array you could do something like this. Please note that what you define as (3,3) in your question, is actually (2,2) from an array perspective. The input $x
and $y
would be 2 and 2 in this case.
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;
}
Upvotes: 1