Random number generator that fills an interval

algorithm, language-agnostic, random

Solution

Fill an array with the interval, and then shuffle it.

The standard way to shuffle an array of N elements is to pick a random number between 0 and N-1 (say R), and swap item[R] with item[N]. Then subtract one from N, and repeat until you reach N =1.

Problem

How would you implement a random number generator that, given an interval, (randomly) generates all numbers in that interval, without any repetition? It should consume as little time and memory as possible. Example in a just-invented C#-ruby-ish pseudocode: ``` interval = new Interval(0,9) rg = new RandomGenerator(interval); count = interval.Count // equals 10 count.times.do{ print rg.GetNext() + " " } ``` This should output something like : ``` 1 4 3 2 7 5 0 9 8 6 ```

Original source

Related problems