On Thu, Jun 28, 2012 at 9:44 AM, Emeka Patrick <[email protected]> wrote:
> In the example below why was it necessary to put (max+1)? Couldn't that
> result in the generation of a random number up to and including 50?
>
> This code calls a code blocklimittimes, each time passing in a random
> number betweenminandmax:
>
>  def pick_random_numbers(min, max, limit)
>    limit.times { yield min+rand(max+1) }
>  end

I am surprised nobody mentioned that code is flawed because it does
not adherer to the mentioned contract: the code will yield random
numbers outside the range given by min and max.  Demonstration:

irb(main):005:0> pick_random_numbers(10, 11, 20){|r| p r}
15
20
17
10
10
12
17
15
21
12
11
21
12
13
11
17
19
17
10
18
=> 20

You need

def pick_random_numbers(min, max, limit)
  limit.times { yield min + rand(max + 1 - min) }
end

Or use the range version as has been mentioned.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- You received this message because you are subscribed to the Google Groups 
ruby-talk-google group. To post to this group, send email to 
[email protected]. To unsubscribe from this group, send email 
to [email protected]. For more options, visit this 
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en

Reply via email to