Created
May 2, 2013 16:02
-
-
Save blackwatertepes/5503248 to your computer and use it in GitHub Desktop.
Shortest Driver Distance (Lyft)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rspec' | |
module Trip | |
def distance(a, b) | |
lat_dist = (a[:lat] - b[:lat]).abs | |
long_dist = (a[:long] - b[:long]).abs | |
Math.sqrt(lat_dist**2 + long_dist**2) | |
end | |
def route_distance(*points) | |
legs = [] | |
points[0...-1].each_with_index do |point, i| | |
legs << distance(point, points[i + 1]) | |
end | |
legs.inject(0) {|sum, num| num + sum } | |
end | |
end | |
# Driver Code | |
include Trip | |
@a = {lat: 0, long: 78} | |
@b = {lat: 6, long: 70} | |
@c = {lat: 30, long: 63} | |
@d = {lat: 42, long: 58} | |
route_a = [@a, @c, @d, @b] | |
route_b = [@c, @a, @b, @d] | |
dist_a = route_distance(*route_a) | |
dist_b = route_distance(*route_b) | |
p "Driver 1 is driving from #{route_a.join(' to ')} with a total distance of #{dist_a}" | |
p "Driver 2 is driving from #{route_b.join(' to ')} with a total distance of #{dist_b}" | |
p "Driver #{dist_a < dist_b ? 1 : 2} has the shorter distance to travel, by #{(dist_a - dist_b).abs} units of distance" | |
#Tests | |
describe Trip do | |
include Trip | |
before(:all) do | |
@a = {lat: 0, long: 78} | |
@b = {lat: 6, long: 70} | |
@c = {lat: 30, long: 63} | |
@d = {lat: 42, long: 58} | |
@legs = [10, 25, 13] | |
end | |
context "distance" do | |
it "should return the correct distance" do | |
distance(@a, @b).should == @legs[0] | |
distance(@b, @c).should == @legs[1] | |
distance(@c, @d).should == @legs[2] | |
end | |
end | |
context "route_distance" do | |
it "should return the total of all legs" do | |
route_distance(@a, @b, @c, @d).should == @legs[0] + @legs[1] + @legs[2] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment