Files
doodle-mini/miniprogram/core/utils/random.ts
T
2026-03-27 17:31:52 +08:00

43 lines
1.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 生成指定范围内的随机整数 [min, max]
*/
export function randomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* 从数组中随机选取一个元素
*/
export function randomPick<T>(arr: T[]): T {
return arr[Math.floor(Math.random() * arr.length)];
}
/**
* 从数组中随机选取 n 个不重复元素(Fisher-Yates,无 sort 偏置)
*/
export function randomPickN<T>(arr: readonly T[], n: number): T[] {
return sampleWithoutReplacement(arr, n);
}
/**
* 无放回抽样,不改变入参数组
*/
export function sampleWithoutReplacement<T>(
arr: readonly T[],
n: number,
): T[] {
return shuffle([...arr]).slice(0, Math.min(n, arr.length));
}
/**
* 打乱数组(Fisher-Yates
*/
export function shuffle<T>(arr: T[]): T[] {
const result = [...arr];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}