在数组中查找最接近0的负数和正数值。

3

我需要在一个数组中找到离零最近的正数和负数。

  • 如果数组是的,我们将返回0
  • 如果数组中有例如-7, 7,我们将返回7

这是正确的做法吗?

$ts = [1.7, 7, -10, 13, 8.4, -7.2, -12, -3.7, 3.5, -9.6, 6.5, -1.7, -6.2, 7];

function closestToZero (array $ts)
{
    if(empty($ts)){

        return 0;
    }

    $negativeArr = [];
    $postiveValue = [];

    foreach ($ts as $number) {
        if ($number < 0) {
            $negativeArr[] = $number;
        }elseif ($number > 0 ) {

            $postiveValue[] = $number;
        }
    }

    if(!empty($negativeArr)){

        $minnegative = max($negativeArr);
    }

    if (!empty($postiveValue)) {
        $minPositive = min($postiveValue);
    }
    if ((abs($minnegative) - $minPositive) == 0) {

        return $minPositive;
    }else{
        return $minnegative.' '.$minPositive;
    }



}

echo "结果是 ".closestToZero($ts);

编辑:

实际上我在寻找一种更优化的方法来完成它,在做了一些研究后,我发现这个方法更加优化。

    //if the array is empty we do nothing we return
if(empty($ts)){

    return 0;
}else{

    $referenceValue = 0;

    //the trick is to add the reference value to the array if it doesnt exist
    if (in_array($referenceValue, $ts) === FALSE) {
        array_push($ts, $referenceValue);
    }

    //we sort the array in an ascending order
    sort($ts);

    // now we are able to get the nearest postive and negative values from 0
    $referenceValueKey = array_search($referenceValue, $ts);

    $positiveValueKey = $referenceValueKey + 1;
    $negativeValueKey = $referenceValueKey - 1;

    $result = '';
    // if there is the same number as negative and positive in the array, we return the positive one
    if((abs($ts[$negativeValueKey]) - $ts[$positiveValueKey]) == 0 )
    {
        $result.= $ts[$positiveValueKey];

    }else{

        $result.= $ts[$negativeValueKey].' '.$ts[$positiveValueKey];
    }

    return $result;



}






}

可能是从数组中获取最接近的值的重复问题。 - Patrick Q
我认为你不需要问。如果它能工作,那么这就是一个正确的方法。如果你想要优化它,那就是另外一个问题了。 - Howard P
2
可能更适合于 https://codereview.stackexchange.com/。 - CD001
3个回答

2
你可以用更少的代码实现这个操作:
<?php

function getClosest(array $x)
{
    // put them in order first
    sort($x);

    $results = [];

    foreach($x as $y) {
        if ($y < 0) {
            $results['-'] = $y; // next negative is closer to 0
        } else {
            $results['+'] = $y; // first positive is closest to 0
            return $results;
        }
    }
    return count($results) > 0 ? $results : 0;
}

$x = [1.7, 7, -10, 13, 8.4, -7.2, -12, -3.7, 3.5, -9.6, 6.5, -1.7, -6.2, 7];

$y = getClosest($x);
var_dump($y);

这将返回:

array(2) { ["-"]=> float(-1.7) ["+"]=> float(1.7) }

它的工作效果很好,但它并不能完全解决问题,因为我们期望返回数字值,如:echo "结果是"。getClosest($x);同时,它还应该处理空数组的情况。 - user1558978
关于空数组,它将跳过循环并在最后返回0,在开头添加额外的if语句是微观优化。至于返回什么,应该比较正负数,并只返回最接近的数?如果(如示例所示)除极性外两者相同,应该返回哪个数字? - delboy1978uk

0
花了我一些时间,但我解决了它。 这个函数不仅可以找到离0最近的正数,还可以处理计算中的任何其他点。
def closest_positive_to_zero(list_of_temperatures, needed_point):
    print(f"got: {list_of_temperatures}") #[7, -10, 4, -7.2, 1.7, -1.7, -6.2, 1.7, 1.8, 1.7, 10]
    sorted_list = sorted(set(list_of_temperatures), key=lambda temperature: abs(temperature-needed_point))  # used a set to get rid of dublicates, sorted with lambda closest to 0
    print(f"sorted: {sorted_list}") #[1.7, -1.7, 1.8, 4, -6.2, 7, -7.2, 10, -10]
    return sorted_list[1] if sorted_list[0] < sorted_list[1] and abs(sorted_list[0]) == abs(sorted_list[1]) else sorted_list[0] # if there are two first same closest numbers (+1.7 and -1.7) take the positive one

list_of_temperatures = [7, -10, 4, -7.2, 1.7, -1.7, -6.2, 1.7, 1.8, 1.7, 10]
the_closest = closest_positive_to_zero(list_of_temperatures, 0)
print(f"{the_closest}")

-2
<?php
$array = [-5, 2, -4, 3, 7];
$positive = array_filter($array, function ($v) {
  return $v > 0;
});
$negative = array_filter($array, function ($v) {
  return $v < 0;
});
print_r(['positive' => array_values($positive)[0], 'negative' => end($negative)]);

排序在哪里?也许通过排序可以解决。尝试使用 $array = [-5, 2.1, 1.9, -4, 3, 7]; 并且将会给出 [positive] => 2.1,这是错误的。 - qräbnö

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接