tags:

views:

51

answers:

2

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)
}
+1  A: 

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.

Justin L.
The loop needs to iterate from 0 to *array-length* - 2.
Gumbo
http://www.php.net/manual/en/function.array-walk.php - Runs a user function over each element of an array.
Kazar
@Gumbo - my apologies; I was using a range with the end value excluded.
Justin L.
@Kazar - Should also note that this is useful if you're running PHP 5.3 or above which has closures. For older PHP versions the syntax will be so awkward that a simple loop is better. IMHO.
Vilx-
A: 
$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;
Thariama
Formatted your code and fixed it up a bit. Hope you don't mind. :)
Vilx-
no problem - thx
Thariama
Don't know where the comment about adding `abs` went, but added that too. Though Justin L. is right - if the values are sorted in ascending order, it's not needed.
Vilx-
Oh, also note that it would be better to assign `count($array)` to a variable at the beginning, and not call it on each iteration.
Vilx-