findNeighbours()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 7
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 14
rs 9.2222
1
<?php
2
3
$matrix = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ];
4
5
for ( $row = 0; $row < sizeof( $matrix ); $row++ ) {
6
    for ( $column = 0; $column < sizeof( $matrix[0] ); $column++ ) {
7
        echo $matrix[$row][$column] . " ";
8
    }
9
    echo PHP_EOL;
10
}
11
12
function findNeighbours ( array $matrix, int $row, int $column ) : array
13
{
14
    $neighbours = [];
15
16
    for ( $currentRow = $row - 1; $currentRow <= $row + 1; $currentRow++ ) {
17
        for ( $currentColumn = $column - 1; $currentColumn <= $column + 1; $currentColumn++ ) {
18
            if ( isElementInRange( $currentRow, $currentColumn,
19
                    $matrix ) && ( $currentRow != $row || $currentColumn != $column ) ) {
20
                $neighbours[] = [ "row" => $currentRow, "column" => $currentColumn ];
21
            }
22
        }
23
    }
24
25
    return $neighbours;
26
}
27
28
function isElementInRange ( $row, $column, $matrix ) : bool
29
{
30
    $inRange = true;
31
32
    if ( $row < 0 || $column < 0 ) {
33
        $inRange = false;
34
    }
35
36
    if ( $row > sizeof( $matrix ) - 1 ) {
37
        $inRange = false;
38
    }
39
40
    if ( $column > sizeof( $matrix[0] ) - 1 ) {
41
        $inRange = false;
42
    }
43
44
    return $inRange;
45
}
46
47
for ( $row = 0; $row < sizeof( $matrix ); $row++ ) {
48
    for ( $column = 0; $column < sizeof( $matrix[0] ); $column++ ) {
49
        $neighbours = findNeighbours( $matrix, $row, $column );
50
        echo "neighbours for row $row, column $column are:" . print_r( $neighbours, true ) . PHP_EOL;
0 ignored issues
show
Bug introduced by
Are you sure print_r($neighbours, true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

50
        echo "neighbours for row $row, column $column are:" . /** @scrutinizer ignore-type */ print_r( $neighbours, true ) . PHP_EOL;
Loading history...
51
    }
52
}
53