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

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

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.

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;
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>``````

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

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();
``````

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

DEMO

Generate random numbers without any range

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

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

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

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

randojs.com makes this a simple one-liner:

``````randoSequence(4)
``````

This will return an array of numbers from 0 through 4 in random order. You just need to add the following to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions as I've shown here.

``````<script src="https://randojs.com/1.0.0.js"></script>
``````

Recursive Method in Type Script I used this in Angular app, it's similar in JS

`````` private randomNumbers:Array<number> = []
private auxRandomColor:number
public avoidRepeatNumber():void{

let numberRandom:number =  this.getRandomInt(0,9)
//sistema considera o zero como undefined, logo 0 zero é 100 depois converte pra zero
if(numberRandom === 0){
numberRandom = 100
}
let existNumber = this.randomNumbers.find( number => number === numberRandom)
if(!existNumber){

this.randomNumbers.push(numberRandom)
if(numberRandom === 100){
numberRandom = 0;
}
this.auxRandomColor =  numberRandom
return
}
this.avoidRepeatNumber()
}

public getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
``````

HTML

``````<p id="array_number" style="font-size: 25px; text-align: center;"></p>
``````

JS

``````var min = 1;
var max = 90;
var stop = 6;  //Number of numbers to extract

var numbers = [];

for (let i = 0; i < stop; i++) {
var n =  Math.floor(Math.random() * max) + min;
var check = numbers.includes(n);

if(check === false) {
numbers.push(n);
} else {
while(check === true){
n = Math.floor(Math.random() * max) + min;
check = numbers.includes(n);
if(check === false){
numbers.push(n);
}
}
}
}

sort();

//Sort the array in ascending order
function sort() {
numbers.sort(function(a, b){return a-b});
document.getElementById("array_number").innerHTML = numbers.join(" - ");
}
``````

DEMO