Skip to content

Instantly share code, notes, and snippets.

@josafafilho
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josafafilho/02baa5c82dd808e8ee4e to your computer and use it in GitHub Desktop.
Save josafafilho/02baa5c82dd808e8ee4e to your computer and use it in GitHub Desktop.
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