Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Brute force:</strong> if time complexity doesn't matter it would be a solution for 0 &lt; M &lt;= N invariant. nextRandom(N) is a function which returns random integer in [0..N):</p> <pre><code>init() { for (int idx = 0; idx &lt; N; idx++) { a[idx] = -1; } for (int idx = 0; idx &lt; M; idx++) { getNext(); } } int getNext() { for (int idx = 1; idx &lt; M; idx++) { a[idx -1] = a[idx]; } while (true) { r = nextRandom(N); idx = 0; while (idx &lt; M &amp;&amp; a[idx] != r) idx++; if (idx == M) { a[idx - 1] = r; return r; } } } </code></pre> <p><strong>O(M) solution:</strong> It is recursive solution for simplicity. It supposes to run nextRandom() which returns a random number in [0..1):</p> <pre><code>rnd(0, 0, N, M); // to get next M distinct random numbers int rnd(int idx, int n1, int n2, int m) { if (n1 &gt;= n2 || m &lt;= 0) return idx; int r = nextRandom(n2 - n1) + n1; int m1 = (int) ((m-1.0)*(r-n1)/(n2-n1) + nextRandom()); // gives [0..m-1] int m2 = m - m1 - 1; idx = rnd(idx, n1, r-1, m1); print r; return rnd(idx+1, r+1, n2, m2); } </code></pre> <p>the idea is to select a random r in between [0..N) on first step which splits the range on two sub-ranges by N1 and N2 elements in each (N1+N2==N-1). We need to repeat the same step for [0..r) which has N1 elements and [r+1..N) (N2 elements) choosing M1 and M2 (M1+M2==M-1) so as M1/M2 == N1/N2. M1 and M2 must be integers, but the proportion can give real results, we need to round values with probabilities (1.2 will give 1 with p=0.8 and 2 with p=0.2 etc.). </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. 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