Random non-repetitive javascript number generation between two limits

Is there any method besides splicing an array that I can use to generate a random number between two numbers without repeating at all until all numbers between these two numbers are generated? It would be extremely useful to use shuffling methods or any other array methods other than splicing.

+4
source share
3 answers

First, we use the fisherYates implementation (credit goes to @ChristopheD) and extends the prototype array to have the 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, using the pop method, we get the 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 start and end range, 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 an example on jsfiddle

UPDATE: add fisheryates algo for more efficient use

+2
source

What I usually do when working with smaller arrays sorts the array randomly:

 yourArray.sort(function() { return 0.5 - Math.random() }); 
0
source

Try http://jsbin.com/imukuh/1/edit :

 function randRange(min, max) { var result = []; for (var i=min; i<=max; i++) result.push(i); return result.map(function(v){ return [Math.random(), v] }) .sort().map(function(v){ return v[1] }); } console.log(randRange(1,5)); // [4, 3, 1, 5, 2] // [3, 5, 2, 4, 1] // [1, 5, 2, 3, 4] // [3, 2, 5, 1, 4] // ... 
-1
source

Source: https://habr.com/ru/post/1482503/


All Articles