Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #7248
| From | Robert Klemme <shortcutter@googlemail.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: How to Generate Weighted Random Numbers |
| Date | 2016-05-05 19:08 +0200 |
| Message-ID | <dp1d0oFdafpU1@mid.individual.net> (permalink) |
| References | <014542d8-a512-4732-9328-677230605f33@googlegroups.com> |
On 05.05.2016 18:17, Jesus Castello wrote:
> I wrote an article about how you can generate weighted random
> numbers with some simple algorithms. I think you will like it :)
>
> Read it here:
> http://www.blackbytes.info/2016/05/weighted-random-numbers/
>
> Let me know what you think!
Unfortunately indentation was screwed up in the comment. So here it
comes again:
Here’s my solution:
weights = {cats: 5, dogs: 1}.inject([]) {|a, (it, w)|
a << [it, w + (a.last.last rescue 0)]}
p weights
counts = Hash.new {|h, it| h[it] = 0}
10000.times do
r = rand(weights.last.last)
it = weights.find {|it, w| r < w}
p r, it
counts[it] += 1
end
p counts
Advantage: you have to do less arithmetic during picking of the value
because that is done in the preparation step.
Cheers
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
Back to comp.lang.ruby | Previous | Next — Previous in thread | Find similar
How to Generate Weighted Random Numbers Jesus Castello <matugm@gmail.com> - 2016-05-05 09:17 -0700 Re: How to Generate Weighted Random Numbers Robert Klemme <shortcutter@googlemail.com> - 2016-05-05 19:08 +0200
csiph-web