Robert Walker wrote in post #1049376:
> #!/usr/bin/env ruby
> require 'set'
>
> def random_numbers(n = 500)
> my_set = Set.new
> while my_set.size < 500
> value = Integer((rand * 1) * 1000) / Float(1000)
> my_set << value
> end
> my_set.to_a
> end
>
> puts random_numbers.size
One caveat with this technique: Make sure you build in some "circuit
breaker" protection code. The more numbers you ask this to generate the
more rounds it will take to produce the result. Generating 500 unique
numbers is averaging about 700 rounds. The closer to 1000 you get the
more rounds it will take. Over 1000 and it will never finish.
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
No comments:
Post a Comment