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/
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)