如何在PHP中找到该数组中数组和元素的平均值之间的最小差异

时间:2015-08-09 19:36:27

标签: php arrays

首先,我需要找到数组的平均值,然后我需要找到该数组中数组和元素的平均值之间的最小差异,并显示该元素的位置。这是数组:

myArray(4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19);

3 个答案:

答案 0 :(得分:0)

原油但正在工作:

<?php
$myArray = [4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19];

// the average: sum/count
$average = round(array_sum($myArray) / count($myArray));

foreach ($myArray as $value) {
  $diffs[] = abs($average - $value);
}

asort($diffs);
print_r($diffs);
$d = reset($diffs);
$p = array_search($d, $diffs);

echo sprintf("Average: %s, min diff: %s, diff pos: %s\n", $average, $d, $p);

答案 1 :(得分:0)

你可以试试这个:

    <?php

$myArray = array(4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19);
$averageArray = "";

//Average of the array
if(count($myArray) > 0) {
    $averageArray = array_sum($myArray)  / count($myArray);
}
$diff = array();

//Diff of average value and each value in a array named diff 
if(isset($myArray)) {
    foreach($myArray as $value) {
        $diff[] = abs($averageArray - $value);
    }
}
$key = array_search(min($diff),$diff);
echo "average = " . $averageArray .' - min value :'.min($diff).' - index:'.$key .' value: '.$myArray[$key]."\n";

答案 2 :(得分:0)

第一步是概念化算法。我想到的是:找到平均值,找出每个元素与平均值的绝对差值,然后找出最小值。平均值可以从总和和长度计算得出。

$avg = array_sum($array) / count($array);
$diff = function ($x) use ($avg) { return abs($x - $avg); };
$answer = min(array_map($diff, $array));

要获得最接近平均值的元素,而不是映射到差异,我们可以保持原始元素的乘坐。然后,当我们找到最小值时,我们只比较差异。

function minBy(callable $f, array $xs) {
  $min = $xs[0];
  foreach ($xs as $x) {
    if ($f($x, $min) < 0) $min = $x;
  }
  return $min;
}

$avg = array_sum($array) / count($array);
$diff = function ($x) use ($avg) { return array($x, abs($x - $avg)); };
$byDiff = function ($x,$y) { return $x[1] - $y[1]; };
$answer = minBy($byDiff, array_map($diff, $array));

要查找数组中元素的索引(请注意,这可能不是唯一的),您可以使用array_search