Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Pure mathematics:<br/> Let's calculate the quantity of <code>rand()</code> function calls in both cases and compare the results:</p> <p><strong>Case 1:</strong> let's see the mathematical expectation of calls on step <code>i = k</code>, when you already have k numbers chosen. The probability to get a number with one <code>rand()</code> call is equal to <code>p = (n-k)/n</code>. We need to know the mathematical expectation of such calls quantity which leads to obtaining a number we don't have yet. </p> <p>The probability to get it using <code>1</code> call is <code>p</code>. Using <code>2</code> calls - <code>q * p</code>, where <code>q = 1 - p</code>. In general case, the probability to get it exactly after <code>n</code> calls is <code>(q^(n-1))*p</code>. Thus, the mathematical expectation is <br/> <code>Sum[ n * q^(n-1) * p ], n = 1 --&gt; INF</code>. This sum is equal to <code>1/p</code> (proved by wolfram alpha). </p> <p>So, on the step <code>i = k</code> you will perform <code>1/p = n/(n-k)</code> calls of the <code>rand()</code> function.</p> <p>Now let's sum it overall:</p> <p><code>Sum[ n/(n - k) ], k = 0 --&gt; m - 1 = n * T</code> - the number of <code>rand</code> calls in method 1. <br/> Here <code>T = Sum[ 1/(n - k) ], k = 0 --&gt; m - 1</code></p> <p><strong>Case 2:</strong></p> <p>Here <code>rand()</code> is called inside <code>random_shuffle</code> <code>n - 1</code> times (in most implementations).</p> <p>Now, to choose the method, we have to compare these two values: <code>n * T ? n - 1</code>.<br/> So, to choose the appropriate method, calculate <code>T</code> as described above. If <code>T &lt; (n - 1)/n</code> it's better to use the first method. Use the second method otherwise. </p>
    singulars
    1. This table or related slice is empty.
    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. 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.
    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