Created
November 14, 2019 19:54
-
-
Save adrianosferreira/db3b5b6ac130a33bbe06eff885f8255e to your computer and use it in GitHub Desktop.
Number of connections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: adriano | |
* Date: 14/11/19 | |
* Time: 16:37 | |
*/ | |
function numberOfConnections( $gridOfNodes ) { | |
$nodesPreviousLine = null; | |
$connections = 0; | |
foreach( $gridOfNodes as $row ) { | |
$nodesLine = 0; | |
foreach ( $row as $line ) { | |
if ( $line === 1 ) { | |
$nodesLine ++; | |
} | |
} | |
if ( $nodesPreviousLine !== null ) { | |
$connections += $nodesLine * $nodesPreviousLine; | |
} | |
if ( $nodesLine ) { | |
$nodesPreviousLine = $nodesLine; | |
} | |
} | |
return $connections; | |
} | |
$grid = [ | |
[ 1, 0, 1, 1 ], | |
[ 0, 1, 1, 0 ], | |
[ 0, 0, 0, 0 ], | |
[ 1, 0, 0, 0 ], | |
]; | |
assert( 8 === numberOfConnections( $grid ) ); | |
assert( 17 === numberOfConnections( | |
[ | |
[ 1, 0, 1, 1, 1 ], | |
[ 0, 1, 1, 0, 1 ], | |
[ 0, 0, 0, 0, 1 ], | |
[ 1, 0, 0, 0, 1 ], | |
] | |
) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment