11

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
Shouvik
  • 449
  • 1
  • 7
  • 17
  • 1
    Duplicate: http://stackoverflow.com/questions/15584716/unique-random-number-generator-javascript/15584880#15584880 – apelsinapa Mar 23 '13 at 09:33

12 Answers12

20

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);
Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
8

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>
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • The second line in the script above should be changed to var random = a.splice(Math.floor(Math.random() * i), 1)[0]; The splice function uses zero-based index so with array length of 5 as above the calculated index could be 5 as well and the a array doesn't have a[5]. – Matt Sergej Rinc Sep 17 '19 at 00:01
6

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() );
}
Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
3

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);
symlink
  • 11,984
  • 7
  • 29
  • 50
2

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();
Shouvik
  • 449
  • 1
  • 7
  • 17
1

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

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
1

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)
Jijo Paulose
  • 1,896
  • 18
  • 20
1

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

Blackjack
  • 1,322
  • 1
  • 16
  • 21
0

simple and cryptographically secure with randojs:

console.log(randoSequence(4))
<script src="https://randojs.com/2.0.0.js"></script>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15
0

So many solutions to this! Here's my code for a reuseable function that takes in 3 arguments: the number of integers wanted in the array (length) and the range that the array should be comprised of (max and min).

function generateRandomArr(length, max, min) {
  const resultsArr = [];
  for (let i = 0; i < length; i++) {
    const newNumber = Math.floor(Math.random() * (max - min)) + min;
    resultsArr.includes(newNumber) ? length += 1 : resultsArr.push(newNumber);
  }
  return resultsArr;
}

generateRandomArr(10, 100, 0);
// this would give a list of 10 items ranging from 0 to 100
// for example [3, 21, 56, 12, 74, 23, 2, 89, 100, 4]
  • 1
    Could ```i -= 1``` be a reasonable replacement for ```length += 1``` in order to keep the "we want a serie of _length_ randomly choosen numbers" ? – nvidot Oct 27 '20 at 20:40
0

Here's a solution that allows you to specify the length of the resulting array and works with negative numbers as well.

// FROM: https://stackoverflow.com/a/2450976/2345158
function shuffleArr(array) {
  let currentIndex = array.length;
  let randomIndex;
  // While there remain elements to shuffle...
  while (currentIndex !== 0) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
  return array;
}

// Will generate a list of random numbers in a range without duplicates
function getRandomNumberArr(min, max, length) {
  if (length > max - min + 1) throw Error('Length must not be longer than number of unique values.')
  // Generate list of possible values
  let optionsArr = [...Array(max - min + 1).keys()];
  // Return the needed number of random elements
  return shuffleArr(optionsArr).splice(0, length).map(el => el + min);
}

console.log(getRandomNumberArr(-2, 2, 5))
jfunk
  • 7,176
  • 4
  • 37
  • 38
-1
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);
    }
}
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68