Skip to content

Instantly share code, notes, and snippets.

@EvanHsieh0415
Last active August 21, 2023 07:44
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 EvanHsieh0415/fd59b0a517327d64f02fe0db1ae21464 to your computer and use it in GitHub Desktop.
Save EvanHsieh0415/fd59b0a517327d64f02fe0db1ae21464 to your computer and use it in GitHub Desktop.
[JS] Simple Math Functions (without class)
const MMath = {
/**
* Return a random integer N such that `a <= N <= b`.
* @param {Number} a
* @param {Number} b
* @returns {Number}
*/
randint: function (a, b) {
const min = b != undefined ? a : 0;
const max = b != undefined ? b : a;
return Math.floor(Math.random() * (max - min) + min);
},
/**
* Return a random element from the non-empty sequence seq
*
* @param {Array} array
* @returns {*}
*/
choice: function (array) {
return array[this.randint(array.length)];
},
/**
* Description placeholder
*
* @param {Array} array
* @param {Number} k
* @returns {Array}
*/
choices: function (array, k) {
const newArray = [];
for (let i = 0; i < k; i++)
newArray.push(array[this.randint(array.length)]);
return newArray;
},
/**
* Return a *k* length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
*
* @param {Array} array
* @param {Number} k
* @returns {Array}
*/
sample: function (array, k) {
const oldArray = array.slice();
const newArray = [];
const sampleTimes = k != undefined ? k : array.length;
let index
for (let i = 0; i < sampleTimes; i++) {
index = this.randint(oldArray.length);
newArray.push(oldArray[index]);
oldArray.splice(index, 1);
}
return newArray;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment