Last active
August 21, 2023 07:44
-
-
Save EvanHsieh0415/fd59b0a517327d64f02fe0db1ae21464 to your computer and use it in GitHub Desktop.
[JS] Simple Math Functions (without class)
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
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