How to randomly generate numbers without repetition in javascript?

I want to generate every number from 0 to 4 randomly using javascript, and each number can only appear 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 repeats the values. Please, help.

+5
source share
6 answers

Create 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);
+13
source

Another way to do this:

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);
}

I don’t know if it’s even possible to make it more compact.

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

Here is the demo version:

$('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>
Run code
+6
source

( , , ): .

, , , . , , .

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() );
}
+5

. , , , .

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();
+2

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

+1
source

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)
+1
source

All Articles