From: timr Date: 2010-06-23T06:25:09+09:00 Subject: Re: Random Points within a Circle (#234) This is actually a pretty interesting puzzle. Correct solutions should have points that are distributed as a hump Gaussian-like curve when histogram plotted over the y rand and x range. My first solution had a humped-histogram over the X ranges but was evenly distributed over the Y ranges. Back to the drawing board. The algorithm I ended up using makes points distributed over the Y and X range, but only keeps them if they are within the circle. Used R to plot. Code below: class Circle attr_reader :r,:x,:y def initialize(r,x,y) @r = r @y = y @x = x end #get random x and y from within circle space def internal_rand #to randomly select rise run values rise = rand(0)*@r*rand_sign run = rand(0)*@r*rand_sign #validate that point lies within circle, about 20% fail if Math.sqrt(run**2+rise**2)<@r [@x+run,@y+rise] else internal_rand end end private def rand_sign rand(2) == 0? -1 : 1 end end #test c1 = Circle.new(4,10,10) xs = []; ys = [] 1000.times do point = c1.internal_rand xs << point.first ys << point.last end plotted in R using: x = c(pasted in xs from ruby output) y = c(pasted in ys from ruby output) plot(x,y) library(plotrix) draw.circle(10,10,4) #evenly distribute points within circle hist(x, breaks=20) #Gaussian histogram bar distribution hist(y, breaks=20) #Gaussian histogram bar distribution On Jun 19, 11:05 am, Daniel Moore wrote: > -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- > > The three rules of Ruby Quiz: > > 1.  Please do not post any solutions or spoiler discussion for this > quiz until 48 hours have elapsed from the time this message was > sent. > > 2.  Support Ruby Quiz by submitting ideas and responses > as often as you can. > > 3.  Enjoy! > > Suggestion:  A [QUIZ] in the subject of emails about the problem > helps everyone on Ruby Talk follow the discussion.  Please reply to > the original quiz message, if you can. > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > > RSS Feed:http://rubyquiz.strd6.com/quizzes.rss > > Suggestions?:http://rubyquiz.strd6.com/suggestions > > -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- > > ## Random Points within a Circle (#234) > > Greetings Rubyists, > > Generating random numbers is a useful feature and Ruby provides us > with `Kernel.rand` to generate numbers uniformly distributed between > zero and one. If we want to generate random numbers with other > distributions, then we'll need to do a little work. The quiz this week > is to generate random points uniformly distributed within a circle of > a given radius and position. > > This quiz is relatively simple, great if you are new to Ruby or > strapped for time. Remember, it is contributions from people like > *you* that make Ruby Quiz succeed! > > Have fun! > > -- > -Danielhttp://rubyquiz.strd6.com