Ruby Issue Tracking System: Issueshttps://bugs.ruby-lang.org/https://bugs.ruby-lang.org/favicon.ico?17113305112011-01-07T19:20:51ZRuby Issue Tracking System
Redmine Ruby master - Feature #4247 (Rejected): New features for Array#sample, Array#choicehttps://bugs.ruby-lang.org/issues/42472011-01-07T19:20:51Zoj (Yoji Ojima)
<p>=begin<br>
We are planning to add the following features of the random sampling to Array.</p>
<ol>
<li>Weighted random sampling.</li>
<li>Sampling with replacement.</li>
<li>Iteration.</li>
</ol>
<p>It is discussed in ruby-dev (Feature <a class="issue tracker-2 status-7 priority-4 priority-default closed" title="Feature: Array#sample(n, replace=false) (Feedback)" href="https://bugs.ruby-lang.org/issues/3647">#3647</a> and <a class="issue tracker-2 status-7 priority-4 priority-default closed" title="Feature: Array#sample で重みを指定したい (Feedback)" href="https://bugs.ruby-lang.org/issues/4147">#4147</a>).</p>
<p>API will be:</p>
<p>Array#sample([size, [opt]])</p>
<ul>
<li>Random selection without replacement.</li>
<li>Returns a new array when size is specified.</li>
<li>opt:<br>
weight: proc or array<br>
random: Random instance</li>
</ul>
<p>Array#choice([size, [opt]])</p>
<ul>
<li>Random selection with replacement.</li>
<li>Returns a new array when size is specified.</li>
<li>opt: same as above.</li>
</ul>
<p>Array#each_sample([opt])</p>
<ul>
<li>Random selection iterator without replacement.</li>
<li>Choose a random element and yield it.</li>
<li>Returns an Enumerator if a block is not given.</li>
<li>opt: same as above.</li>
</ul>
<p>Array#each_choice([opt])</p>
<ul>
<li>Random selection iterator with replacement.</li>
<li>Choose a random element and yield it.</li>
<li>Returns an Enumerator if a block is not given.</li>
<li>opt: same as above.</li>
</ul>
<p>Comments?<br>
=end</p> Ruby master - Feature #4147 (Feedback): Array#sample で重みを指定したいhttps://bugs.ruby-lang.org/issues/41472010-12-10T22:06:32Zoj (Yoji Ojima)
<p>=begin<br>
Array#sample にブロックを渡したとき、ブロックの戻り値を要素の重みとして使用するのはいかがでしょうか。</p>
<p>下記のサンプルで、"大吉" が "凶" の 1000 倍の確率で選択されるようにしたいです。</p>
<p>omikuji_box = [<br>
{:name => "大吉", :weight => 1000},<br>
{:name => "中吉", :weight => 100},<br>
{:name => "小吉", :weight => 10},<br>
{:name => "凶", :weight => 1}<br>
]<br>
omikuji = omikuji_box.sample {|v| v[:weight] }<br>
puts omikuji[:name]<br>
=end</p>