Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Ok so you are given input as follows:</p> <pre><code>(3, 7) (1, 2) (2, 5) (4, 1) (5, 2) </code></pre> <p>And you want to pick a random number so that the weight of each id is reflected in the picking, i.e. pick a random number from the following list:</p> <pre><code>3 3 3 3 3 3 3 1 1 2 2 2 2 2 4 5 5 </code></pre> <p>Initially, I created a temporary array but this can be done in memory as well, you can calculate the size of the list by summing all the weights up = X, in this example = 17</p> <p>Pick a random number between [0, X-1], and calculate which which id should be returned by looping through the list, doing a cumulative addition on the weights. Say I have a random number 8</p> <pre><code>(3, 7) total = 7 which is &lt; 8 (1, 2) total = 9 which is &gt;= 8 **boom** 1 is your id! </code></pre> <p>Now since you need K random <strong>unique</strong> ids you can create a hashtable from initial array passed to you to work with. Once you find an id, remove it from the hash and proceed with algorithm. <strong>Edit</strong> Note that you create the hashmap initially only once! You algorithm will work on this instead of looking through the array. I did not put in in the top to keep the answer clear</p> <p>As long as your random calculation is not using any extra memory secretly, you will need to store K random pickings, which are &lt;= N and a copy of the original array so max space requirements at runtime are O(2*N)</p> <p>Asymptotic runtime is :</p> <pre><code>O(n) : create copy of original array into hastable + ( O(n) : calculate sum of weights + O(1) : calculate random between range + O(n) : cumulative totals ) * K random pickings = O(n*k) overall </code></pre> <p>This is a good question :)</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.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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