baskin-lib
Version:
baskin robbins 31 web game library
66 lines (65 loc) • 1.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.randomArray = exports.getRandomIntAsVec = exports.randomSampleOne = exports.getRandomInt = exports.getRandom = void 0;
const linarg_1 = require("./linarg");
/**
*
* @param min Min value.
* @param max Max value. Excluded.
* @returns Random float in interval [`min`, `max`)
*/
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
exports.getRandom = getRandom;
/**
*
* @param min Min value.
* @param max Max value. Excluded.
* @returns Random integer in interval [`min`, `max`).
*/
function getRandomInt(min, max) {
return Math.floor(getRandom(Math.ceil(min), Math.floor(max)));
}
exports.getRandomInt = getRandomInt;
/**
*
* @param vec Input vector
* @returns Random sample from the vector
*/
function randomSampleOne(vec) {
const pickedIdx = getRandomInt(0, vec.length);
return vec[pickedIdx];
}
exports.randomSampleOne = randomSampleOne;
/**
*
* @param chooseProb normalized vector of choose probability
* @returns random sample of index rate proportional to `vec`
*/
function getRandomIntAsVec(chooseProb) {
const cumsum = (0, linarg_1.vecCumSum)(chooseProb);
const rand = Math.random();
var i = 0;
var lower = 0;
var upper = cumsum[i];
while (i < cumsum.length) {
if (rand >= lower && rand < upper) {
return i;
}
i++;
lower = cumsum[i - 1];
upper = cumsum[i];
}
throw new Error("invalid parameters");
}
exports.getRandomIntAsVec = getRandomIntAsVec;
/**
*
* @param len length of the array
* @returns `len` of array filled with random number
*/
function randomArray(len) {
return Array.from(Array(len)).map((_) => Math.random());
}
exports.randomArray = randomArray;