Random numbers are often used in programming, and Golang provides the rand package to generate pseudo-random numbers. However, in some cases we may need to generate a set of random numbers that are different from each other. In order to achieve this goal, we need to consider a feasible algorithm.
This article will introduce several methods to generate non-repeating random numbers, and provide a method to use the Golang rand package to generate non-repeating random numbers.
Method 1: Shuffling Algorithm
In the shuffling algorithm, we randomly arrange an array of numbers with the same range once. The time complexity of this algorithm is O(n). The disadvantage of this method is that the system takes up a lot of memory when we use this algorithm to generate a large number of random numbers.
The algorithm is implemented as follows:
Method 2: Rejection Sampling Algorithm
In the rejection sampling algorithm, we store the generated random numbers in a set and check the set when generating the next random number whether the same number already exists in . If present, regenerate the random number. The advantage of this algorithm is that it is a space efficient algorithm. However, this algorithm can become more time-consuming when the number of unique numbers we need to generate is larger.
The algorithm is implemented as follows:
Method Three: Bitmap Algorithm
In the bitmap algorithm, we create a bitmap where each bit represents the presence or absence of a number in the range. We use this bitmap to keep track of whether a certain number already exists in the set of random numbers we have generated. The advantage of this algorithm is that it is a time- and space-efficient algorithm.
The algorithm is implemented as follows:
Method 4: Golang’s rand package implementation
Golang provides the rand package, which can be used to generate pseudo-random numbers. We can use this to generate non-repeating random numbers.
The algorithm is implemented as follows:
The above four methods can be used to generate non-repeating random numbers. Each algorithm has its advantages and disadvantages. Which algorithm to use depends on your needs, if the importance lies in space then use rejection sampling algorithm, if in importance over time then choose bitmap algorithm. And if you are using Golang, you can directly use the rand package to implement a simple, direct, and efficient non-repeating random number generation algorithm.
The above is the detailed content of golang rand does not repeat. For more information, please follow other related articles on the PHP Chinese website!