Passed
Push — master ( 0603fe...79dd6e )
by Jean Paul
01:20
created

findNeighbours()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 15
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 5
nop 3
dl 0
loc 15
rs 9.2222
1
<?php
2
3
$matrix = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ];
4
//print_r( $matrix ) . PHP_EOL;
5
6
for ( $row = 0; $row < sizeof( $matrix ); $row++ ) {
7
    for ( $column = 0; $column < sizeof( $matrix[0] ); $column++ ) {
8
        echo $matrix[$row][$column] . " ";
9
    }
10
    echo PHP_EOL;
11
}
12
13
function findNeighbours ( array $matrix, int $row, int $column ) : array
14
{
15
    $neighbours = [];
16
17
    for ( $currentRow = $row - 1; $currentRow <= $row + 1; $currentRow++ ) {
18
        for ( $currentColumn = $column - 1; $currentColumn <= $column + 1; $currentColumn++ ) {
19
            if ( isElementInRange( $currentRow, $currentColumn, $matrix ) ) {
20
                if ( $currentRow != $row || $currentColumn != $column ) {
21
                    $neighbours[] = [ "row" => $currentRow, "column" => $currentColumn ];
22
                }
23
            }
24
        }
25
    }
26
27
    return $neighbours;
28
}
29
30
function isElementInRange ( $row, $column, $matrix ) : bool
31
{
32
    $inRange = true;
33
34
    if ( $row < 0 || $column < 0 ) {
35
        $inRange = false;
36
    }
37
38
    if ( $row > sizeof( $matrix ) - 1 ) {
39
        $inRange = false;
40
    }
41
42
    if ( $column > sizeof( $matrix[0] ) - 1 ) {
43
        $inRange = false;
44
    }
45
46
    return $inRange;
47
}
48
49
for ( $row = 0; $row < sizeof( $matrix ); $row++ ) {
50
    for ( $column = 0; $column < sizeof( $matrix[0] ); $column++ ) {
51
        $neighbours = findNeighbours( $matrix, $row, $column );
52
        echo "neighbours for row $row, column $column are:" . PHP_EOL;
53
        print_r( $neighbours ) . PHP_EOL;
54
    }
55
}
56