I want to use javascript to generate 50 no-repeat random numbers and the number is in the range 1 to 50.how can I realize it?The 50 numbers stored in a array.
Asked
Active
Viewed 2,710 times
1 Answers
3
First generate an ordered list:
var i, arr = [];
for (i = 0; i < 50; i++) {
arr[i] = i + 1;
}
then shuffle it.
arr.sort(function () {
return Math.random() - 0.5;
});
I tested the above method and it performed well. However, the ECMAScript spec does not require Array.sort
to be implemented in such a way that this method produces a truly randomized list - so while it might work now, the results could potentially change without warning. Below is an implementation of the Fisher-Yates shuffle, which is not only guaranteed to produce a reasonably random distribution, but is faster than a hijacked sort.
function shuffle(array) {
var p, n, tmp;
for (p = array.length; p;) {
n = Math.random() * p-- | 0;
tmp = array[n];
array[n] = array[p];
array[p] = tmp;
}
}

st-boost
- 1,877
- 1
- 14
- 17
-
Your code has a minor bug since i starts from 1. Use array's `push` method instead to add element to it. http://jsfiddle.net/KUfcf/ – ShankarSangoli May 22 '12 at 01:33
-
Thanks, fixed (before the comment actually). `push` is slightly slower than a direct assignment, so (in this case) I think it's better to use `[i]`. – st-boost May 22 '12 at 01:35
-
The solution you provided works perfectly.Thanks – LiveJin May 22 '12 at 03:19
-
1[That's doesn't generate uniformly random arrangements](http://stackoverflow.com/q/962802/102441) – Eric May 25 '12 at 14:43
-
@Eric I wouldn't say that, but rather, that it is not required to produce uniformly random arrangements. But thanks for the comment and especially the link; answer edited to include a true sort. – st-boost May 26 '12 at 04:34