Last active
August 29, 2015 13:56
-
-
Save allanesquina/9105239 to your computer and use it in GitHub Desktop.
JavaScript function that returns an array of random numbers without repetition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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