简体   繁体   中英

How can i scan over a square matrices using php / for loop?

I need to write some code using some for-loops which tests the values of some array data.

1st pass: checking the following...

{x0,y0}

2nd pass: checking the 4 bits of data...

{x0,y0}, {x1,y0}, 
{x0,y1}, {x1,y1}.

3rd pass: checking 9 bits of data...

{x0,y0}, {x1,y0}, {x2,y0}, 
{x0,y1}, {x1,y1}, {x2,y1},
{x0,y2}, {x1,y2}, {x2,y2}.

My little brain doesn't seem to want to function to get this answered. Can anyone help?

<?php

for ($pass = 0; $pass < count($matrix); $pass++)
{
    for ($i = 0; $i <= $pass; $i++)
    {
        for ($j = 0; $j <= $pass; $j++)
        {
            checkbit($matrix[$i][$j]);
        }
    }   
}

?>

Maybe something like this?

You could start with a simple function that operates on the matrix:

function scan($x, $y) {...}

Additionally the canvas has a range for x and y, the starting number and it's ending number:

range x/y: 0,0/0,0

or later on:

range x/y: 0,2/0,2

If you say that the ranges always start at 0 , and both ranges always have the same upper value, this can be reduced as one variable: $range . You can then just iterate over the matrix easily ( Demo ):

$range = 2;

foreach(range(0, $range) as $y)
    foreach(range(0, $range) as $x)
        scan($x, $y);

function scan($x, $y)
{
...
}

As $range depends on the number of the current pass, you can specify the maximum number of passes in $passes and iterate over it changing $range based on $pass ( Demo ):

$passes = 3;

foreach(range(1, $passes) as $pass)
{
    $range = $pass-1;
    foreach(range(0, $range) as $y)
        foreach(range(0, $range) as $x)
            scan($x, $y);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM