Home  >  Article  >  Web Front-end  >  Comparison of methods of obtaining non-repeating random numbers in javascript_javascript skills

Comparison of methods of obtaining non-repeating random numbers in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:01:111005browse

Non-repeating random number scheme 1: 1531 milliseconds
The general idea is to first create an array of 1-3000, take out one at a time, and then reduce the array by one, take one, Reduce one so that it can never be repeated.


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]
No duplicates Random number scheme 2: 297 milliseconds

However, scheme 1 uses the slice method. This method regenerates the array, which will occupy a lot of memory and CPU operations. The efficiency is very low, so improve it and take a number from the original array. Then let this position of the original array be assigned a value of null. In this way, the next time the number is retrieved, if it is determined to be null, it will not be retrieved until it is not null. After testing, it can significantly improve efficiency.

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
No duplicates Random number scheme 3: 234 milliseconds

Another way of thinking, if you break up the original array origin and then print it one after another,
In this way, randomness can never be repeated, and it is more efficient,
Because the further the program 2 is run, the higher the frequency of the original array being null, and the greater the number of operations.
[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]
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