Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Created June 27, 2021 18:27
Show Gist options
  • Save sagittaracc/f219897be22856cd40c75d48f7c960ce to your computer and use it in GitHub Desktop.
Save sagittaracc/f219897be22856cd40c75d48f7c960ce to your computer and use it in GitHub Desktop.
Mehen Games Test
<?php
/**
* Mehen games test
*
* @author sagittaracc <sagittaracc@gmail.com>
*/
// Массив имеет произвольные значения
$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