Skip to content

Instantly share code, notes, and snippets.

@thdaraujo
Created March 5, 2016 21:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thdaraujo/6e6ff71330f9199fd97d to your computer and use it in GitHub Desktop.
Save thdaraujo/6e6ff71330f9199fd97d to your computer and use it in GitHub Desktop.
class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def to_s
"(#{@x}, #{@y})"
end
end
def distance(p1, p2)
sum_of_squares = (p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2
Math.sqrt(sum_of_squares.abs)
end
def average_distance(p1, p2, p3)
distances = [distance(p1, p2), distance(p2, p3), distance(p1, p3)]
distances.reduce(:+).to_f / distances.size
end
#testing...
p1 = Point.new(0, 0)
p2 = Point.new(0, 1)
p3 = Point.new(0, 2)
avg_distance = average_distance(p1, p2, p3)
puts "Points: [#{p1}, #{p2}, #{p3}]"
puts "the average distance is #{avg_distance}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment