A solution for Ruby quiz #234 - Random Points within a Circle
This file contains 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
# 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