Re: [問題] 判斷一數字是否介於某些範圍之內

作者: AchieveDream (AchieveDream)   2015-06-14 03:28:57
※ 引述《red0whale (red whale)》之銘言:
: 假設我有一陣列變數$a=[2,7,14,28,32,38,41,49];
: 今假設一個數$b
: 請問怎麼判斷$b是否介於2~7、14~28、32~38、41~49這些範圍之內?
: (亦即$b是否介於$a的數值範圍內,假設$a有偶數個元素)
覺得題目滿有趣的,因此嘗試一下,這也是我第一次PO文~
function is_in_range(array $range = [], $search)
{
$high = count($range) - 1;
if ((-1 === $high) || 0 === ($high & 1))
{
return false;
}
$low = 0;
$search = intval($search);
while ($low <= $high)
{
$mid = (($low + $high) >> 1);
if ($search === $range[$mid])
{
return true;
}
else if ($search > $range[$mid])
{
if ($mid === $high)
{
return false;
}
else if ((0 === ($mid & 1)) && ($search < $range[$mid+1]))
{
return true;
}
$low = $mid + 1;
}
else
{
if ($mid === $low)
{
return false;
}
else if ((1 === ($mid & 1)) && ($search > $range[$mid-1]))
{
return true;
}
$high = $mid - 1;
}
}
return false;
}

Links booklink

Contact Us: admin [ a t ] ucptt.com