/** * * @param {number[]} array - 要操作的数组 * @param {number} a - 要操作的下标 * @param {number} b - 要操作的下标 * @description 交换数组中两个数的位置 */ export function swap(array, a, b) { let temp = array[a] array[a] = array[b] array[b] = temp } /** * @param {Array} array - 待操作的数组 * @returns {number[]} - 打乱后的数组 * @description 打乱数组内容 */ function shuffle(arr) { // 创建数组的副本,以防止修改原始数组 const shuffledArray = arr.slice(); // Fisher-Yates 洗牌算法 for (let i = shuffledArray.length - 1; i > 0; i--) { const a =Math.random() * (i + 1) console.log(a); const j = Math.floor(a); // 交换元素 [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]]; } return shuffledArray; } /** * @description 生成指定长度的随机数组。 * * @param {number} len - 数组的长度。 * @param {boolean} decimal - 是否生成包含小数的随机数,默认为 true。 * @param {number} decimals - 保留的小数位数,默认为 2。 * @returns {number[]} - 生成的随机数组。 */ export function generateRandomArray(len, decimal = false, decimals = 2) { const randomArray = []; for (let i = 0; i < len; i++) { const randomNumber = decimal ? parseFloat((Math.random() * 10000).toFixed(decimals)) : Math.floor(Math.random() * 10000); randomArray.push(randomNumber); } return randomArray; } export function measureTime(func, ...args) { // 记录函数开始执行的时间戳 const startTime = performance.now(); // 执行传入的函数,使用 apply 或 call 传入参数 func(...args); // 计算函数执行所花费的时间 const endTime = performance.now(); const elapsedTime = endTime - startTime; // 打印执行时间 console.log(`Function execution time: ${elapsedTime} milliseconds`); }