@thi.ng/random
Version:
Pseudo-random number generators w/ unified API, distributions, weighted choices, ID generation
31 lines • 1.35 kB
TypeScript
import type { Fn0 } from "@thi.ng/api";
import type { IRandom } from "./api.js";
/**
* Returns a no-arg function which produces a random choice of given weighted
* `choices` and using given {@link IRandom} instance (default {@link SYSTEM}.
* If `weights` are given, it must be the same size as `choices` (else missing
* weights will be assumed zero). If omitted entirely, each choice will have
* same probability.
*
* @remarks
* Throws an error if the `choices` array is empty (requires at least 1 item).
* If the total sum of `weights` is <= 0 a warning is printed to the console and
* the resulting function will only ever return the first `choice`.
*
* Based on:
* https://www.electricmonk.nl/log/2009/12/23/weighted-random-distribution/
*
* @param choices -
* @param weights - optional weights
*/
export declare const weightedRandom: <T>(choices: Array<T>, weights?: ArrayLike<number>, rnd?: IRandom) => () => T;
/**
* Alt version of {@link weightedRandom}, accepting an object of weights
* instead. The returned function will return keys of given `choices` object,
* taking into account the weights given for each key.
*
* @param choices
* @param rnd
*/
export declare const weightedRandomKey: <T extends Record<string, number>>(choices: T, rnd?: IRandom) => Fn0<keyof T>;
//# sourceMappingURL=weighted-random.d.ts.map