简体   繁体   English

查找数组中的下一个最大值

[英]Find next highest value in an array

I have an string converted to an array with 1 to 7 values eg 3, 1234567, 1234, 357, 46 etc我将字符串转换为具有 1 到 7 个值的数组,例如 3、1234567、1234、357、46 等

Given any number between 1 and 7, how do I find the next value in the array?给定 1 到 7 之间的任意数字,我如何找到数组中的下一个值?

$str=12345;
$arr=str_split($str);

$end=end($arr);

if ($day==$end) {
    $next=reset($arr);
} else {
    $loc=array_search($day, $arr)+1;
    $next=$arr[$loc];
}

print $next;

If day is 1 the above returns 2 and if day is 5 above returns 1 both of which are correct but if day is 6 or 7 then it does not return the correct value which should be 1 - likewise if the array is 1245 and day is 3 it again does not return the correct value which should be 4.如果 day 为 1,则上述返回 2,如果 day 为 5,则返回 1,这两者都是正确的,但如果 day 是 6 或 7,则它不会返回应该为 1 的正确值 - 同样,如果数组是 1245 并且 day 是3 它再次没有返回应该是 4 的正确值。

What do I need to do to make the above return the correct values in all scenarios?我需要做什么才能使上述在所有情况下都返回正确的值?

$values = array_filter($arr, function($v) use($day) {
    return $v > $day;
});

$value = $values ? array_shift($values) : array_shift($arr);

Probably not optimal and untested but it should work. 可能不是最佳且未经测试,但它应该可以工作。

Of course there will be many different ways to perform this task.当然,将有许多不同的方式来执行此任务。 I'll demonstrate one efficent approach that uses decrementation in a loop to find the next number i the sequence without generating an array.我将演示一种在循环中使用递减来查找序列中的下一个数字而不生成数组的有效方法。 Before looping, declare a fallback value of the first number in the haystack string.在循环之前,声明 haystack 字符串中第一个数字的后备值。

Here are 5 different test cases where the number after 5 is sought.这里有 5 个不同的测试用例,其中寻找 5 之后的数字。

Code: ( Demo )代码:(演示

$tests = [
    '3',
    '1234567',
    '1234',
    '357',
    '46'
];

$find = 5;
++$find;
foreach ($tests as $test) {
    $found = $test[0];
    for ($i = strlen($test) - 1; $i >= 0; --$i) {
        if ($test[$i] < $find) {
            break;
        }
        $found = $test[$i];
    }
    echo "Found $found\n";
}

Output: Output:

Found 3
Found 6
Found 1
Found 7
Found 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM