Skip to content Skip to sidebar Skip to footer

Javascript To Generate 50 No-repeat Random Numbers

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.

Solution 1:

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.

functionshuffle(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;
    }
}

Post a Comment for "Javascript To Generate 50 No-repeat Random Numbers"