0

var randomArray = [];

function random(x) {
    var emptyRandom = null;
    temp = Math.floor(Math.random() * x);
     emptyRandom = temp;
     return emptyRandom;

}

for (var i = 10; i > 0 ; i--) {
    randomArray.push(random(10));
}
console.log(randomArray);
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>practice</title>

    </head>
    <body>


    <script src="script.js" charset="utf-8"></script>
    </body>
</html>

i want to shuffle the randomArray to make sure numbers don't repeat, All the answers that people post are very hard to understand for a beginner so if you can please explain how you do it that would help me a lot!

  • You don't want consecutive repeated numbers or do you need a randomisation without replacement? – hhh Apr 29 '17 at 13:35
  • you want `randomArray` to have unique values? – Junius L Apr 29 '17 at 13:35
  • This should get you started [How to Generate a Sequence of Unique Random Integers](http://preshing.com/20121224/how-to-generate-a-sequence-of-unique-random-integers/) – RamblinRose Apr 29 '17 at 13:35
  • you could have a look here: [Random number, which is not equal to the previous number](http://stackoverflow.com/q/40056297/1447675) – Nina Scholz Apr 29 '17 at 13:36

1 Answers1

0

You can use a function to check if the random number already exists in your array. If it does, call the function again to randomize a new number:

function random(x) {
    var num = Math.floor(Math.random() * x);
    if (isInArray(randomArray, num))
       random(x);
    else
       return num;
}

function isInArray(array, search)
{
    return array.indexOf(search) >= 0;
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103