例如,我有一个数组(它可以是任何东西,但它已经排序):
array(1,7, 12, 18, 25);
我需要找到最接近该数组的数字。
取上面的数组:
$needle = 11;
我想要检索的数组中的数字是7
。
与 11
最接近的数字应该是 12
,但我不需要最接近的数字,我想要最接近的次要数字(如果这有意义的话)。
另一个例子:
- 输入
26
检索到的号码应为 25
- 输入
1
检索到的号码应为 1
- 输入
6
检索到的号码应为 1
- 输入
7
检索到的号码应为 7
- 输入
16
检索到的数字应该是 12
我发现了一个不错的函数,但它只检索最接近的数字,而不是最接近的次要数字:
function closestnumber($number, $candidates) {
for($i = 0; $i != sizeof($candidates); $i++) {
$results[$i][0] = abs($candidates[$i] - $number);
$results[$i][1] = $i;
}
sort($results);
$end_result['closest'] = $candidates[$results[0][1]];
$end_result['difference'] = $results[0][0];
return $end_result;
}
$closest = closestnumber(8,array(1,7, 12, 18, 25));
echo "Closest: ".$closest['closest']."<br>";
echo "Difference: ".$closest['difference'];
提前致谢。
I have an array, for example (it can be anything, but it's already ordered):
array(1,7, 12, 18, 25);
I need to find what number is the closest to that array.
Taking the above array:
$needle = 11;
The number in array i want to retrieve is 7
.
The closest number to 11
should be 12
, but i dont want the closest number, i want the minor closest number, if that makes any sense.
Another examples:
- Entering
26
the retrieved number should be 25
- Entering
1
the retrieved number should be 1
- Entering
6
the retrieved number should be 1
- Entering
7
the retrieved number should be 7
- Entering
16
the retrieved number should be 12
I found a nice function, but it does only retrieve the closest number, and not the minor closest number:
function closestnumber($number, $candidates) {
for($i = 0; $i != sizeof($candidates); $i++) {
$results[$i][0] = abs($candidates[$i] - $number);
$results[$i][1] = $i;
}
sort($results);
$end_result['closest'] = $candidates[$results[0][1]];
$end_result['difference'] = $results[0][0];
return $end_result;
}
$closest = closestnumber(8,array(1,7, 12, 18, 25));
echo "Closest: ".$closest['closest']."<br>";
echo "Difference: ".$closest['difference'];
Thanks in advance.
发布评论
评论(3)
编辑
假设数组值始终为正整数
简化版本
EDIT
Assumes array values will always be positive integers
Simplified version
这看起来像是家庭作业,但我会幽默一下:
This looks like homework but I'll humour you:
仅测试少于或等于您人数的候选人。如果您始终只记住最佳解决方案,则无需对解决方案进行排序以找到最佳解决方案。
所以试试这个:
Only test candidates that are less than or equal to your number. And if you always remember only the best solution you don’t need to sort the solutions to find the best.
So try this: