Ronophobia - 1 year ago 60

Javascript Question

Is there any method apart from array splicing that I can use to generate a random number between two numbers without repeating at all until all the numbers between those two numbers have been generated? Shuffling techniques or any other array methods apart from splicing would be extremely helpful.

Answer Source

First we use the fisherYates implementation (credit goes to @ChristopheD) and extend the array prototype to have a shuffle function available

```
function arrayShuffle () {
var i = this.length, j, temp;
if ( i === 0 ) return false;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
}
Array.prototype.shuffle =arrayShuffle;
var numbers = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
numbers.shuffle();
```

Now with the use of the `pop`

method we get a number from our seed until it is empty

```
numbers.pop(); //returns a number
```

To make sure we have an array filled with numbers in the range of `start`

and `end`

we use a simple loop to create our seed.

```
var start = 1;
var end = 5;
var numbers = new Array();
for (var i = start; i <= end; i++) {
numbers.push(i);
}
```

here is a sample on jsfiddle

UPDATE: put fisherYates algo to shuffle more efficient