Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You don't just need a random number generator here, you need one in conjunction with a shuffling algorithm.</p> <p>Create an array of <code>N</code> items (we'll use seven for our example), each containing the integer relating to its position:</p> <pre><code>+---+---+---+---+---+---+---+ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | +---+---+---+---+---+---+---+ &lt;pool(7) </code></pre> <p>and set the pool size to 7.</p> <p>Then generate your random number, based on the pool size (i.e., get a number from 1 to 7). Let's say your generator returns 3.</p> <p>Pull out the value at position 3 then replace that with the top value, then reduce the pool size:</p> <pre><code>+---+---+---+---+---+---+---+ | 1 | 2 | 7 | 4 | 5 | 6 | 7 | -&gt; 3 +---+---+---+---+---+---+---+ &lt;pool(6) </code></pre> <p>Then you just keep doing this until you've gotten the quantity of values required. If our lotto was 5 from 7:</p> <pre><code>+---+---+---+---+---+---+---+ | 1 | 2 | 7 | 4 | 5 | 6 | 7 | +---+---+---+---+---+---+---+ &lt;pool(7) rnd(7) returns 3 +---+---+---+---+---+---+---+ | 1 | 2 | 7 | 4 | 5 | 6 | 7 | -&gt; 3 +---+---+---+---+---+---+---+ &lt;pool(6) rnd(6) returns 1 +---+---+---+---+---+---+---+ | 6 | 2 | 7 | 4 | 5 | 6 | 7 | -&gt; 1 +---+---+---+---+---+---+---+ &lt;pool(5) rnd(5) returns 5 +---+---+---+---+---+---+---+ | 6 | 2 | 7 | 4 | 5 | 6 | 7 | -&gt; 5 +---+---+---+---+---+---+---+ &lt;pool(4) rnd(4) returns 2 +---+---+---+---+---+---+---+ | 6 | 4 | 7 | 4 | 5 | 6 | 7 | -&gt; 2 +---+---+---+---+---+---+---+ &lt;pool(3) rnd(3) returns 1 +---+---+---+---+---+---+---+ | 7 | 4 | 7 | 4 | 5 | 6 | 7 | -&gt; 6 +---+---+---+---+---+---+---+ &lt;pool(2) </code></pre> <p>and there you have it, 5-from-7 numbers (3,1,5,2,6) extracted with no possibilities of duplicates and an efficient O(n) method for getting them. Any solution that relies on just getting random numbers and checking if they've already been used will be less efficient.</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