Search code examples
c#randomshuffleprng

How to generate a list of shuffled integers between 2 numbers?


I want to create a shuffled set of integers such that:

  1. Given the same seed, the shuffle will be the same every time
  2. As I iterate through, every number in the shuffled set will be used exactly once before repeating itself
  3. Will work for large sets (I want all numbers between 0 and 2 billion)
  4. Will generate between a range, for example, 100 to 150.

This option gives a great solution if you want, say, all of the numbers between 0 and a specified number: Generating Shuffled Range Using a PRNG Rather Than Shuffling

Any ideas?


Solution

  • You can use the exact same algorithm as the linked question. Just generate numbers between 0 and upperBound - lowerBound + 1 and add lowerBound to the result.

    e.g. (using code from linked question):

    var upper = 5;
    var lower = 3;
    foreach (int n in GenerateSequence(upper-lower+1))
    {
        Console.WriteLine(n+lower);
    }
    

    If you want the sequence to repeat (shuffled differently each time), you can add a while (true) around the iterator method body.