Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created November 14, 2019 19:54
Show Gist options
  • Save adrianosferreira/db3b5b6ac130a33bbe06eff885f8255e to your computer and use it in GitHub Desktop.
Save adrianosferreira/db3b5b6ac130a33bbe06eff885f8255e to your computer and use it in GitHub Desktop.
Number of connections
<?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