Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly generate numbers without repetition in javascript?

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.

like image 842
Shouvik Avatar asked Mar 23 '13 09:03

Shouvik


People also ask

How do you generate a random number in JavaScript?

Generating Javascript Random Numbers Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.


2 Answers

function getRanArr(lngth) {
  let arr = [];
  do {
      let ran = Math.floor(Math.random() * lngth); 
      arr = arr.indexOf(ran) > -1 ? arr : arr.concat(ran);
   }while (arr.length < lngth)
   
   return arr;
}

const res = getRanArr(5);

console.log(res);
like image 199
symlink Avatar answered Oct 05 '22 23:10

symlink


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);
like image 20
Blender Avatar answered Oct 06 '22 00:10

Blender