Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Something like this:</p> <pre><code>public class Randomizer&lt;T&gt; { private readonly Random _random = new Random(); private readonly IList&lt;T&gt; _numbers; public Randomizer(IList&lt;T&gt; numbers) { _numbers = numbers; } public T Next() { int idx = _random.Next(0, _numbers.Count); return _numbers[idx]; } } </code></pre> <p>Usage:</p> <pre><code>var r = new Randomizer&lt;int&gt;(new int[] { 10, 20, 30, 40, 50 }); for (int i = 0; i &lt; 100; i++) Console.Write(r.Next() + " "); </code></pre> <p>Or do you want to <a href="https://stackoverflow.com/questions/108819/best-way-to-randomize-a-string-array-in-c">shuffle the array</a>?</p> <p><strong>[Edit]</strong></p> <p>To shuffle the array, you can use the <a href="http://en.wikipedia.org/wiki/Knuth_shuffle" rel="nofollow noreferrer">Fisher–Yates shuffle</a> shown in <a href="https://stackoverflow.com/questions/108819/best-way-to-randomize-a-string-array-in-c/110570#110570">this post</a>:</p> <pre><code>// https://stackoverflow.com/questions/108819/110570#110570 public class Shuffler { private Random rnd = new Random(); public void Shuffle&lt;T&gt;(IList&lt;T&gt; array) { int n = array.Count; while (n &gt; 1) { int k = rnd.Next(n); n--; T temp = array[n]; array[n] = array[k]; array[k] = temp; } } } </code></pre> <p>If you want the interface to be same as the <code>Randomizer</code> class above, you can modify it to use the <code>Shuffler</code> class:</p> <pre><code>public class Randomizer&lt;T&gt; { private readonly Shuffler _shuffler = new Shuffler(); private readonly IList&lt;T&gt; _numbers; public Randomizer(IList&lt;T&gt; numbers) { _numbers = new List&lt;T&gt;(numbers); _shuffler.Shuffle(_numbers); } volatile int idx = 0; public T Next() { if (idx &gt;= _numbers.Count) { _shuffler.Shuffle(_numbers); idx = 0; } return _numbers[idx++]; } } </code></pre> <p>Note that the code is <strong>not thread safe</strong>, so some locking should be implemented if <code>Next</code> method might be called simultaneously from multiple threads.</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. 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