开发者

How to get average distance between array values in PHP?

For the array below, it's ~20 but how to get it programatically?

array(12) {
  [0]=>
  int(29)
  [1]=>
  int(50)
  开发者_开发技巧[2]=>
  int(72)
  [3]=>
  int(93)
  [4]=>
  int(114)
  [5]=>
  int(136)
  [6]=>
  int(157)
  [7]=>
  int(178)
  [8]=>
  int(199)
  [9]=>
  int(221)
  [10]=>
  int(242)
  [11]=>
  int(263)
}


What is stopping you from (pseudo-code):

diff = 0
for i from 0 to (array length)-2                 # this should be run (array length)-1 times total
  diff += Math.abs(array[i]-array[i+1])
end                                    
return diff/(array length-1)           

?

If PHP has inject (or reduce) or map (or array walk) methods for enumerables, this would be even more succinct.

note I am only providing this pseudo-code as the self-evident algorithm that would be used to solve this problem. I admit I am no master at PHP (rather, I am approaching this problem from an algorithms point of view); I was just wondering why this simple solution is not adoptable by the asker. If there is an answer that does this same thing, essentially, and does it in proper PHP, please pick it above mine.


$difference = 0;

$length = count($array);

for ($i=1; $i < $length; $i++)
    $difference += abs($array[$i] - $array[$i-1]); 
if ($length  !== 0)
    $result = $difference  / $length;
else
    $result = 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜