Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number generator that fills an interval

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 
like image 285
Cristian Diaconescu Avatar asked Nov 30 '22 11:11

Cristian Diaconescu


1 Answers

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.

like image 132
James Curran Avatar answered Dec 05 '22 18:12

James Curran