Skip to content

Instantly share code, notes, and snippets.

@josafafilho josafafilho/gridsearch.php
Last active Aug 29, 2015

Embed
What would you like to do?
The Grid Search HackerRank Solution using PHP
<?php
function gridSearch($big,$small){
$firstMatch = null;
foreach($big as $key => $bigLine){
$position = strpos($bigLine,$small[0]);
if ($position!==false){
$firstMatch = [$key,$position];
break;
}
}
if (!$firstMatch){
return false;
}
for($i=1,$j=$firstMatch[0]+1;$i<count($small);$i++,$j++){
$position = strpos($big[$j],$small[$i]);
if($position===false || $position!=$firstMatch[1]){
return false;
}
}
return true;
}
$_fp = fopen("php://stdin", "r");
$numberOfTests = (int) fgets($_fp);
$bigGrids = array();
$smallGrids = array();
for($i=0;$i<$numberOfTests;$i++){
$bigGridLines = '';
$smallGridLines = '';
$bigGridDimensions = explode(' ',fgets($_fp));
for ($j=0;$j<$bigGridDimensions[0];$j++){
$bigGridLines[] = trim(fgets($_fp));
}
$bigGrids[] = $bigGridLines;
$smallGridDimensions = explode(' ',fgets($_fp));
for ($j=0;$j<$smallGridDimensions[0];$j++){
$smallGridLines[] = trim(fgets($_fp));
}
$smallGrids[] = $smallGridLines;
}
foreach($bigGrids as $key => $bigGrid){
echo gridSearch($bigGrids[$key],$smallGrids[$key])?"YES\n":"NO\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.