Last active
August 20, 2018 21:17
-
-
Save xergioalex/0f8271d873bc9565e2c4 to your computer and use it in GitHub Desktop.
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
Utils = { | |
// Shuffle array | |
shuffle: function (o) { | |
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); | |
return o; | |
}, | |
// Get random number in range | |
getRandomInt: function (min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
}, | |
// Random numbers | |
// Requirements | |
// * You need a set of random numbers | |
// * The numbers need to be unique | |
// * The order of the returned numbers needs to be random (optional) | |
getRandomNumbers: function (count, min, max, shuffle) { | |
max += 1; | |
// Input parameters must meet these conditions | |
if (max <= min || count < 0 || (count > max - min && max - min > 0)) { | |
return false; | |
} | |
// initialize set S to empty | |
// for J := N-M + 1 to N do | |
// T := RandInt(1, J) | |
// if T is not in S then | |
// insert T in S | |
// else | |
// insert J in S | |
// | |
var candidates = {}; | |
for (var top = max - count; top < max; top++) { | |
var candidate = this.getRandomInt(min, top); | |
if (!candidates[candidate]) { | |
candidates[candidate] = true; | |
} else { | |
candidates[top] = true; | |
} | |
} | |
var candidatesArray = Object.keys(candidates); | |
// Shuffle candidates only if shuffle var is true | |
if (shuffle) { | |
candidatesArray = this.shuffle(candidatesArray); | |
} | |
return candidatesArray; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment