Search code examples
ruby-on-railsrubygeokit

What Ruby enumerable method makes the most sense to sum distances between Geokit objects


I'm using Geokit in order to figure out the distance between two location objects. http://geokit.rubyforge.org/

My question is, if I have an array of locations, what's the best algorithm to go through them to figure out the total distance travel? I thought at first that Enumerable#inject is the way to go, passing a memo of the distance traveled between N-1 location objects, but then there is no way to store state of what location objects you've already checked in the actual array.

This would require having the size of the array, an index we're currently on, plus the behavior of inject. Ideally you could do something like:

locations = [Geokit::LatLng, Geokit::LatLng, ...]
locations.inject(0) do |memo, location|
  memo += location.distance_from(previous_location)
end 

previous_location is undefined in this case, though.

thoughts?


Solution

  • Here's a grossly simplified example of what you want to accomplish. I'm using regular numbers and absolute value as the distance metric solely to make the iteration clearer.

    arr = [1, 2, 3, 4]
    arr.each_cons(2).collect {|a| (a[1]-a[0]).abs }.reduce(:+)
    => 3
    
    1. Each_cons(2) takes every 2 consecutive elements, in this case, generating [1,2], [2, 3], and [3,4]
    2. Collect is the map operation mapping each pair to a distance measure.
    3. Reduce just adds them together.