Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate differences between array elements

Given a sorted array of n integers, like the following:

ary = [3, 5, 6, 9, 14]

I need to calculate the difference between each element and the next element in the array. Using the example above, I would end up with:

[2, 1, 3, 5]

The beginning array may have 0, 1 or many elements in it, and the numbers I'll be handling will be much larger (I'll be using epoch timestamps). I've tried the following:

times = @messages.map{|m| m.created_at.to_i}
left  = times[1..times.length-1]
right = times[0..times.length-2]
differences = left.zip(right).map { |x| x[0]-x[1]}

But my solution above is both not optimal, and not ideal. Can anyone give me a hand?

like image 425
Mike Trpcic Avatar asked Jan 11 '11 21:01

Mike Trpcic


People also ask

How do you find the difference between elements in arrays?

You can use array#map . For the first index value subtract from 0 and for other indexes, subtract from the previous number.

How do you diff an array in Python?

The numpy module of Python provides a function called numpy. diff for calculating the nth discrete difference along the given axis. If 'x' is the input array, then the first difference is given by out[i]=x[i+1]-a[i]. We can calculate the higher difference by using diff recursively.


1 Answers

>> ary = [3, 5, 6, 9, 14] #=> [3, 5, 6, 9, 14]
>> ary.each_cons(2).map { |a,b| b-a } #=> [2, 1, 3, 5]

Edit: Replaced inject with map.

like image 98
Michael Kohl Avatar answered Oct 21 '22 08:10

Michael Kohl