Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm assuming that in your example "probability" means "weight" (so folks with a 1.0 probability aren't guaranteed to win and the total probability won't sum to 1.0)</p> <p>You could build a tree of nodes where the leaf nodes contained your individual entries:</p> <pre><code>leaf1 = {:name =&gt; "Adam" , :prob =&gt; 0.5} leaf2 = {:name =&gt; "Ben" , :prob =&gt; 1.0} </code></pre> <p>and each node contained the sum of the nodes under it</p> <pre><code>node1 = { :prob_sum =&gt; 1.5 , :children=&gt; [ leaf1, leaf2] } </code></pre> <p>The root node then contains the sum of the whole structure</p> <pre><code>root_node = { :prob_sum =&gt; 33 , :children =&gt; [ leaf9, leaf10] } </code></pre> <p>Then you pick a random number between zero and the sum contained in the root node.</p> <pre><code>my_random = rand( root_node.prob_sum ) </code></pre> <p>Then traverse the tree. Each node contains the sum of all nodes under it, so if your random number is larger than the node you subtract that node's value and skip that branch.</p> <pre><code>def find_node( my_random ): c = children.first() while( c ): if ( c.prob_sum &lt; my_random ): return c.find_node(my_random) my_random -= c.prob_sum c = c.next </code></pre> <p>Assuming you've built a balanced tree you should get results in O(log n)</p> <p>Alternatively, you could get the same result by adding a running total field to your current data set and doing a binary search based on that running total. That would probably be easier to implement, but would only be applicable if your working set could fit in memory.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload