在数组中搜索最接近0的负值和正值

时间:2018-07-20 14:40:45

标签: php arrays

我需要在数组中找到最接近零的负值和正值。

  • 如果数组为empty,则我们return 0
  • 例如,如果数组中有-7, 7,则我们return 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;



}






}

3 个答案:

答案 0 :(得分:1)

您可以用更少的代码来做到这一点:

<?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) }

答案 1 :(得分: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 :(得分:-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)]);