recently on the Internet to see a question, how to take 100 not repeat the 100 random number? The code is as follows:
var nums =New int[ -];varList=Newlist<int> (); var random =NewRandom (); for(inti =0; I < -; i++) {intR while(List. Contains (r = Random. Next (0, About))) { }List. ADD (R); Nums[i] = r;}
Personal feeling of the topic is classic, because the real life will often encounter such problems, but the answer is so inefficient, inevitably some disappointment, open vs tried A, sure enough 2 minutes did not run out.
Good topic but no good answer some not reconciled, then continue to explore, found that the problem is not simple, in the " Programming Pearls" A book also mentioned, titled "How to efficiently produce m n range of non-repeating random number (m<=n)" , if you continue to use the above algorithm, the M, N amplification to 10000, the estimated program 1 hours can not run out, the efficiency is heinous.
So how does the book solve the problem? The code is as follows:
varNums =New int[ -];varRandom =NewRandom (); for(inti =0; I < -; i++) {Nums[i] = i;} for(inti =0; I < -; i++) {varr = Random. Next (I, About); Swap (refNums[i],refNums[r]);}
The algorithm is very clever to take the position of the random number ( 数组的下标 ), instead of taking the random number itself, after each fetch to a random number, it will be excluded in the range of values, the next time will only be taken in the remaining number, a traversal can complete the selection of random numbers, the efficiency is quite high.
This method is explained in detail below:
- First, each number of the array is in its place (
subscript " of the array, we get a 100 numbers , An array of sequential .
- Then, the random number of i-99 Vanhee is taken, and the random number of each fetch is exchanged as the position (
数组的下标 ) and the position ( 数组的下标 ) is the number of I. The implication of this is that the random number that has been taken is excluded from the value range, and the next random number is only taken in the remaining digits.
The 2nd step is not easy to understand, I take you to analyze the specific principles of each step, you can immediately glance:
Loop: i = 0, r = 39 (假设随机数为该值), exchanging values for nums[0] and nums[39].
Analysis: The first fetch of the random number is 39, the位置39的数And位置0的数After the exchange, and then from位置1Start looking at the array, you will be surprised to find that the rest is 0-99 except 39 all numbers, but their position is 1-99, next we just need to take a random number from 1-99, as an array subscript, you can take the remaining number of random numbers, and so on.
Algorithm: How to efficiently produce non-repeating random numbers in the range of M n (m<=n)