Skip to content

Instantly share code, notes, and snippets.

@xergioalex
Last active August 20, 2018 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xergioalex/0f8271d873bc9565e2c4 to your computer and use it in GitHub Desktop.
Save xergioalex/0f8271d873bc9565e2c4 to your computer and use it in GitHub Desktop.
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