Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If the amount of possible integers from which you draw is significantly larger (say factor 2) than the amount of integers you want you can simply use a <code>HashSet&lt;T&gt;</code> to check for duplicates.</p> <pre><code>List&lt;int&gt; GetUniqueRandoms(Random random, int count) { List&lt;int&gt; result = new List&lt;int&gt;(count); HashSet&lt;int&gt; set = new HashSet&lt;int&gt;(count); for(int i = 0; i &lt; count; i++) { int num; do { num = random.NextInt(); while(!set.Add(num)); result.Add(num); } return result; } </code></pre> <p>This allocates the collections with the correct capacity to avoid reallocation during growth. Since your collections are large this should be a large improvement.</p> <p>You can also use <code>Distinct</code> a single time:</p> <pre><code>IEnumerable&lt;int&gt; RandomSequence(Random random) { while(true) { yield return random.NextInt(); } } RandomSequence(rand).Distinct().Take(1000000000).ToList(); </code></pre> <p>But with both solutions you need enough memory for a <code>HashSet&lt;int&gt;</code> and a <code>List&lt;int&gt;</code>.</p> <hr> <p>If the amount of possible integers from which you draw is about as large as the amount of integers you want, you can create an array that contains all of them, shuffle them and finally cut off those you're not interested in.</p> <p>You can use <a href="https://stackoverflow.com/questions/1287567/c-is-using-random-and-orderby-a-good-shuffle-algorithm/1287572#1287572">Jon Skeet's shuffle implementation</a>.</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