Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #7248

Re: How to Generate Weighted Random Numbers

Path csiph.com!2.us.feeder.erje.net!feeder.erje.net!1.eu.feeder.erje.net!news-1.dfn.de!news.dfn.de!news.informatik.hu-berlin.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail
From Robert Klemme <shortcutter@googlemail.com>
Newsgroups comp.lang.ruby
Subject Re: How to Generate Weighted Random Numbers
Date Thu, 5 May 2016 19:08:39 +0200
Lines 42
Message-ID <dp1d0oFdafpU1@mid.individual.net> (permalink)
References <014542d8-a512-4732-9328-677230605f33@googlegroups.com>
Mime-Version 1.0
Content-Type text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding quoted-printable
X-Trace individual.net ghDltt/J1qNnRDK2hyXhQQLUr4epi7dcmW3d25by1YB3lv/rE=
Cancel-Lock sha1:5y02ApGhB8rDbSXlHds2pBBb9Nc=
User-Agent Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.7.2
In-Reply-To <014542d8-a512-4732-9328-677230605f33@googlegroups.com>
Xref csiph.com comp.lang.ruby:7248

Show key headers only | View raw


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 | NextPrevious in thread | Find similar


Thread

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