Created
June 27, 2021 18:27
-
-
Save sagittaracc/f219897be22856cd40c75d48f7c960ce to your computer and use it in GitHub Desktop.
Mehen Games Test
This file contains 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 | |
/** | |
* Mehen games test | |
* | |
* @author sagittaracc <[email protected]> | |
*/ | |
// Массив имеет произвольные значения | |
$array = [-1, 2, 10, 3, -5, 3]; | |
$needle = 5; | |
$distances = array_map(function($haystack) use ($needle){ | |
return abs($haystack - $needle); | |
}, $array); | |
$minDistance = min($distances); | |
$closestToTheNeedle = array_search($minDistance, $distances); | |
echo $closestToTheNeedle; | |
echo "\n"; | |
/** | |
* ---------------------------------------------------------- | |
*/ | |
// Массив отсортирован | |
$array = [1, 2, 3, 5, 6]; | |
$needle = 4; | |
function needleBetween($leftOne, $rightOne, $needle) | |
{ | |
return $leftOne <= $needle && $needle <= $rightOne; | |
} | |
function needleCloserToTheLeftOne($leftOne, $rightOne, $needle) | |
{ | |
return $needle - $leftOne <= $rightOne - $needle; | |
} | |
for ($i = 0; $i < count($array); $i++) { | |
$leftOne = $array[$i]; | |
$rightOne = $array[$i + 1]; | |
if (needleBetween($leftOne, $rightOne, $needle)) { | |
echo needleCloserToTheLeftOne($leftOne, $rightOne, $needle) | |
? $i | |
: $i + 1; | |
echo "\n"; | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment