In JavaScript, the random numbers generated generally repeat, but sometimes we need non-repeating random numbers. How to achieve this? Next, we will explain three methods to generate non-repeating random numbers and compare them to see which method is more efficient.
Method 1
Idea: First create an array from 1 to 3000, take one number each time, and then remove the number taken out from the array, so that it can never be repeated .
Performance: took 1528 milliseconds.
Method 2 Idea: Improve the slice method of Method 1 to improve efficiency. Or take out a number from the original array, and then assign the value of this position in the original array to null. The next time the number is retrieved, determine whether it is null. If it is null, it will not be retrieved.
Performance: 290 milliseconds.
Method 3 Idea: Break up the original array and then output it one by one. This way, it can be random and never repeated, and it is more efficient.
Performance: takes 229 milliseconds.
Through performance analysis, it is concluded that method three is the best solution.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn