[英]How do you find the closest value to a number in an associative array?
我有一個包含 15 家不同公司及其股票價格的關聯數組,格式如下所示:
$CloseStockPrice ('Business'=>50.5. 'Business two'=>100.5, .....)
我找到了平均股價:
$Average = (array_sum($CloseStockPrice)/count($CloseStockPrice));
平均值最終為 161。
但是我現在需要在關聯數組中找到與該平均值 (161) 最接近的數字(絕對項)。 我需要顯示業務和股票價值。
我最近的嘗試:
function computeClosest(array $CloseStockPrice)
{
$closest = 161;
for ($i = 161; $i < count($CloseStockPrice) ; $i++)
{
if ($closest === 161)
{
$closest = $CloseStockPrice[$i];
} else if ($CloseStockPrice[$i] > 161 && $CloseStockPrice[$i] <= abs($closest))
{
$closest = $CloseStockPrice[$i];
} else if ($CloseStockPrice[$i] < 161 && -$CloseStockPrice[$i] < abs($closest))
{
$closest = $CloseStockPrice[$i];
return $closest;
}
}
}
有什么建議么?
當您遍歷您的業務條目數組時,緩存具有最小絕對差值(包括平均值)的業務。
雖然在許多情況下您可能期望單個值,但可能存在多個合格企業這一事實意味着您必須保留一系列合格企業以獲得最准確的結果。
線性(單循環)過程( O(n)
)將優於排序算法( O(n log n)
)。
https://stackoverflow.com/q/56506410/2943403
代碼:(演示)
$closeStockPrice = [
'A' => 50,
'B' => 155,
'C' => 75,
'D' => 245,
'E' => 300,
'F' => 100,
'G' => 153,
];
$average = array_sum($closeStockPrice) / count($closeStockPrice);
$bestDistances = [];
foreach ($closeStockPrice as $business => $price) {
$distance = abs($average - $price);
$current = current($bestDistances);
if (!$bestDistances || $current > $distance) {
$bestDistances = [$business => $distance]; // new best distance
} elseif ($current === $distance) {
$bestDistances[$business] = $distance; // push business with same distance
}
}
var_export([
'average' => $average,
'bestDistances' => $bestDistances,
'bestBusinessPrices' => array_intersect_key($closeStockPrice, $bestDistances)
]);
Output:
array (
'average' => 154,
'bestDistances' =>
array (
'B' => 1,
'G' => 1,
),
'bestBusinessPrices' =>
array (
'B' => 155,
'G' => 153,
),
)
我不是來同意股市的,但你可能想知道他們在做什么:
<?php
class AvgSorter{
public $sorted = [];
public function sort($array){
$s = &$this->sorted; array_splice($s, 0);
foreach($array as $k => $v){
$s[$k] = $v;
}
$avg = array_sum($s)/count($s);
uasort($s, function($a, $b) use($avg){
$a = abs($a-$avg); $b = abs($b-$avg);
if($a === $b){
return 0;
}
return $a > $b ? 1 : -1;
});
return $this;
}
public function firstKey(){
return array_keys($this->sorted)[0];
}
public function firstValue(){
return $this->sorted[$this->firstKey()];
}
public function lastKey(){
return array_keys($this->sorted)[count($this->sorted)-1];
}
public function lastValue(){
return $this->sorted[$this->lastKey()];
}
}
$array = ['business 1'=>1000.32, 'business 2'=>5.15, 'business 3'=>10.22, 'business 4'=>4.01, 'business 5'=>10.82, 'business 6'=>3.12, 'business 7'=>1.01];
$avgSorter = new AvgSorter; $firstKey = $avgSorter->sort($array)->firstKey();
$firstValue = $avgSorter->firstValue(); $lastKey = $avgSorter->lastKey();
$lastValue = $avgSorter->lastValue();
$test = 'first key:'.$firstKey.', first value:'.$firstValue.', last key:'.$lastKey.', last value:'.$lastValue;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.