问题描述
你如何实现一个随机数生成器,给定一个时间间隔,(随机地)产生那个区间中的所有数字,而没有任何重复?
这应该消耗尽可能少的时间和内存越好。
例如,在刚刚发明了C#-ruby十岁上下的伪$ C $ C:
的间隔=新区间(0,9)
RG =新RandomGenerator(区间);
数= interval.Count //等于10
count.times.do {
打印rg.GetNext()+
}
这应该输出是这样的:
1 4 3 2 7 5 0 9 8 6
填充用的时间间隔的数组,然后将它洗。
洗牌N个元素的数组的标准方法是选择与项[N]在0和N-1(说R)和交换项[R]的随机数。然后减一N,并重复,直到你达到N = 1。
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
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.
这篇关于随机数生成器,填补了区间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!