/** * 生成指定范围内的随机整数 [min, max] */ export function randomInt(min: number, max: number): number { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * 从数组中随机选取一个元素 */ export function randomPick(arr: T[]): T { return arr[Math.floor(Math.random() * arr.length)]; } /** * 从数组中随机选取 n 个不重复元素(Fisher-Yates,无 sort 偏置) */ export function randomPickN(arr: readonly T[], n: number): T[] { return sampleWithoutReplacement(arr, n); } /** * 无放回抽样,不改变入参数组 */ export function sampleWithoutReplacement( arr: readonly T[], n: number, ): T[] { return shuffle([...arr]).slice(0, Math.min(n, arr.length)); } /** * 打乱数组(Fisher-Yates) */ export function shuffle(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; }