• #### How to Generate Weighted Random Numbers

From Jesus Castello@21:1/5 to All on Thu May 5 09:17:14 2016
Hey,

I wrote an article about how you can generate weighted random numbers with some simple algorithms. I think you will like it :)

http://www.blackbytes.info/2016/05/weighted-random-numbers/

Let me know what you think!
- Jesus Castello

--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)
• From Robert Klemme@21:1/5 to Jesus Castello on Thu May 5 19:08:39 2016
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 :)

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)