34 lines
879 B
TypeScript
34 lines
879 B
TypeScript
/**
|
||
* 生成指定范围内的随机整数 [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 个不重复元素
|
||
*/
|
||
export function randomPickN<T>(arr: T[], n: number): T[] {
|
||
const shuffled = [...arr].sort(() => Math.random() - 0.5);
|
||
return shuffled.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;
|
||
}
|