Skip to content

Instantly share code, notes, and snippets.

@ysulaiman
Created June 21, 2010 21:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ysulaiman/447554 to your computer and use it in GitHub Desktop.
A solution for Ruby quiz #234 - Random Points within a Circle
# A solution for Ruby quiz #234 - Random Points within a Circle.
# http://rubyquiz.strd6.com/quizzes/234-random-points-within-a-circle
# Yaser Sulaiman.
class Point
attr_accessor :x, :y
def initialize(x = 0, y = 0)
@x, @y = x, y
end
# Calculates the Euclidean distance between the point and other_point.
def distance_to(other_point)
Math.hypot((@x - other_point.x), (@y - other_point.y))
end
# Performs two-dimensional translation: moves the point along the x-axis by
# other_point.x and along the y-axis by other_point.y.
def +(other_point)
@x += other_point.x
@y += other_point.y
self
end
# Generates a random point that falls within a circle of a given center and
# radius.
def self.random(center = ORIGIN, radius = 1)
# Initialize a random point p and place it at the origin.
p = Point.new
# Randomly reposition p within a square of side 2*radius centered at the
# origin until it falls within a circle of the given radius that is also
# centered around the origin.
begin
p.x, p.y = rand * radius, rand * radius
# Flip a coin to decide whether to reflect p around the y-axis.
p.x *= -1 if rand > 0.5
# Flip a coin to decide whether to reflect p around the x-axis.
p.y *= -1 if rand > 0.5
end until p.distance_to(ORIGIN) < radius
# Translate p to its correct position relative to the given center.
p + center
end
ORIGIN = Point.new.freeze
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment