【问题标题】:How do you find the closest value to a number in an associative array?如何在关联数组中找到最接近数字的值?
【发布时间】:2021-02-23 01:59:17
【问题描述】:

我有一个包含 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;
        }
    }
}

有什么建议吗?

【问题讨论】:

  • 请不要“yatta-yatta”您的样本输入数据。请使用var_export() 创建一个minimal reproducible example 来表达您的数组数据。根据 PSR-12 指南,else if 应该是一个词。不建议将幻数 (161) 硬编码到您的代码中。如果此值是动态的,请将其设置为变量并适当/直观地命名该变量。如果两个企业拥有161,会发生什么?如果一个企业是 160 而另一个是 162 怎么办?

标签: php arrays


【解决方案1】:

当您遍历您的业务条目数组时,缓存具有最小绝对差值(包括平均值)的业务。

虽然在许多情况下您可能期望一个值,但可能有多个符合条件的企业这一事实意味着您必须保留一系列符合条件的企业才能获得最准确的结果。

线性(单循环)过程 (O(n)) 将优于排序算法 (O(n log n))。
https://stackoverflow.com/q/56506410/2943403

代码:(Demo)

$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)
]);

输出:

array (
  'average' => 154,
  'bestDistances' => 
  array (
    'B' => 1,
    'G' => 1,
  ),
  'bestBusinessPrices' => 
  array (
    'B' => 155,
    'G' => 153,
  ),
)

【讨论】:

    【解决方案2】:

    我不是来同意股市的,但你可能想知道他们在做什么:

    <?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;
    ?>
    

    【讨论】:

    • 这个答案缺少教育解释。我特别想听听array_slice($array, 0) 做了什么。从 PHP8 开始:Deprecated: uasort(): Returning bool from comparison function is deprecated 请不要在一行代码上写多个声明——垂直空间节省不值得对代码可读性的影响。根据 PHP 版本,当价格与平均值之间存在平局时,您的 sn-p 将给出不同的结果。 3v4l.org/lhmfg
    • @mickmackusa,我在没有= 分配的情况下转储数组,以防与数组关联。
    • 请在我之前的评论中解决所有问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多