Skip to content

Instantly share code, notes, and snippets.

@allanesquina
Last active August 29, 2015 13:56
Show Gist options
  • Save allanesquina/9105239 to your computer and use it in GitHub Desktop.
Save allanesquina/9105239 to your computer and use it in GitHub Desktop.
JavaScript function that returns an array of random numbers without repetition
/*
* xRandom
* Returns an array of random numbers without repetition
* array range, int limit
*/
function xRandom( range, limit ) {
if( --limit >= range[1] || limit < 0 ) return;
return (function _xr( i, r, result ) {
var max = range[1], min = range[0], j = r.length, c=0,
rand = Math.floor(Math.random() * (max - min + 1) + min);
while( j-- ) {
( r[j] === rand ) ? c += 1 : c;
}
if( c === 0 ) {
result.push( rand );
r.push( rand );
return ( i ) ? _xr( --i, r, result ) : result;
} else {
return _xr( i, r, result );
}
}(limit,[],[]));
}
// How to use
var rand = xRandom( [1,10], 5 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment