0

I am trying to make a script which is outputting every number from 1-10. Using a random number generator, in JavaScript.

I want every number to be unique. Here is an example of what i would like the script to output:

5 9 7 6 1 3 4 8 2 10

This is my attempt:

    var test = [];
    var amountOfNumbers = 10;
    var inArray = false;
    var useNumbers = [];
    for(var i=0; useNumbers.length<=amountOfNumbers; i++){
        var rng = Math.floor((Math.random()*amountOfNumbers)+1);
        for(var a=0; a<=test.length; a++){
            if(rng == test[a]){
                inArray == true;
            }
        }
        if(!inArray){
            document.write(rng);
            test.push(rng);
            useNumbers.push(rng);
        }
    }

Hope you can help.

for the record I am not interested in jQuery og any other library :)

Kristian Daugaard
  • 185
  • 1
  • 3
  • 11
  • 5
    Generate the numbers from one to ten, and then shuffle them: http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – NPE Feb 12 '14 at 07:28

2 Answers2

5

1) How to fix your code

You have a few errors, among them the fact you don't reset inArray to false and that you don't iterate over the whole test array (use <, not <=). But using a loop to see if you already have the number isn't efficient, it's better to use an object as a map :

var test = [];
var amountOfNumbers = 10;
var useNumbers = {};
for(var i=0; test.length<amountOfNumbers; i++){
        var rng = Math.floor((Math.random()*amountOfNumbers)+1);
        if(!useNumbers[rng]){
            document.write(rng);
            test.push(rng);
            useNumbers[rng] = true;
        }
}

2) How to do it properly

Your algorithm will loop until it is lucky enough to find the remaining numbers. This isn't efficient and isn't predictable. The normal reliable practice is

  1. to generate the array [1..10]
  2. to shuffle it

Generating an array of the integers from 1 to N can be done with a simple loop or in a fancier way :

var arr = Array.apply(0,new Array(N)).map(function(_,i){ return i+1 });

Shuffling an array is usually done with the Fisher-Yates algorithm, for which you'll easily find JS implementations (it's easy to write anyway). A fast (theoretically not guaranteed to work with all future sort implementations) alternative is this one :

arr = arr.sort(function(a,b){ return Math.random()>0.5 });

The whole program

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Your approach means to check over all the array in each step, looking if your random number is already inside the array, which means a lot lost time.

Best approach is disordering an ordered array. In each loop, we generate a random number (in the example, a number between 0 and 1) and with a 50% probability we change the item in the current position for other item in a random position (between 0 and the length of the array).

Hope it helps.

function disorder(arg) {
  for (var i = 0; i < arg.length; i++) {
      if (Math.random() < 0.5) {
          var aux = arg[i];
          var rndPos = Math.floor(Math.random()) * arg.length;
          arg[i] = arg[rndPos];
          arg[rndPos] = aux;
      }
  }
  return arg;
}

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var myNewArray = disorder(myArray);

myNewArray.forEach(function(item) {
  console.log(item);
});
adripanico
  • 1,026
  • 14
  • 32