How to randomly generate numbers without repetitio

2019-01-26 13:29发布

问题:

I want to generate each number between 0 to 4 randomly using javascript and each number can appear only once. So I wrote the code:

for(var l=0; l<5; l++) {
    var randomNumber = Math.floor(Math.random()*5);  
    alert(randomNumber)
}

but this code is repeating the values. Please help.

回答1:

Generate a range of numbers:

var numbers = [1, 2, 3, 4];

And then shuffle it:

function shuffle(o) {
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

var random = shuffle(numbers);


回答2:

One more way to do it:

for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
    var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
    console.log(random);
}

Don't know if it's even possible to make it more compact.

Tests: http://jsfiddle.net/2m3mS/1/

Here is embed demo:

$('button').click(function() {
    $('.output').empty();
    
    for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
        var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
        $('.output').append('<span>' + random + '</span>');
    }
    
}).click();
.output span {
    display: inline-block;
    background: #DDD;
    padding: 5px;
    margin: 5px;
    width: 20px;
    height: 20px;
    text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>
<button>Run</button>



回答3:

The answers given by Adil and Minko have a major problem (although Minko at least constrained it to a small set of numbers): They go over the same numbers over and over again.

In that sense, a better method would be to create the array containing the possible values, shuffle it and then just pop elements off of it. This will require the complexity of shuffling the array, but it will get rid of the problem mentioned above.

var elements = [1, 2, 3, 4];
elements.shuffle(); // not a standard Javascript function, needs to be implemented

while( elements.length > 0 ) {
    console.log( elements.pop() );
}


回答4:

Appreciate all your help. But probably another way to generate random number in a given max range can be implemented as per below.

function generateRan(){
    var max = 20;
    var random = [];
    for(var i = 0;i<max ; i++){
        var temp = Math.floor(Math.random()*max);
        if(random.indexOf(temp) == -1){
            random.push(temp);
        }
        else
         i--;
    }
    console.log(random)
}

generateRan();


回答5:

If the range of random numbers is not very large you can use this:

var exists = [],
    randomNumber,
    max = 5;
for(var l = 0; l < max; l++) {
   do {
       randomNumber = Math.floor(Math.random() * max);  
   } while (exists[randomNumber]);
   exists[randomNumber] = true;
   alert(randomNumber)
}

DEMO



回答6:

Generate random numbers without any range

function getuid() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)

        }
          return s4() + s4();
 }
 var uid = getuid();
 alert(uid)


回答7:

var randomNumber = [];

for (var i = 0; i < 16; i++) {
    var number = Math.floor(Math.random() * 4);
    var genNumber = randomNumber.indexOf(number);
    if (genNumber === -1) {
        randomNumber.push(number);
    }
}