gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:32:10 41 4
gpt4 key购买 nike

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

  • 如果数组为空,我们返回 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;



}






}

最佳答案

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

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

关于php - 在数组中搜索最接近 0 的负值和正值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51445016/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com