生成随机数组并排序

用 JavaScript 生成指定范围的随机数数组并排序

问题

用 JavaScript 实现随机选取 10–100 之间的 10 个数字,存入一个数组,并排序。

解答

基础实现

// 生成 min 到 max 之间的随机整数(包含 min 和 max)
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 生成随机数组
function generateRandomArray(count, min, max) {
  const arr = [];
  for (let i = 0; i < count; i++) {
    arr.push(randomInt(min, max));
  }
  return arr;
}

// 生成 10 个 10-100 之间的随机数
const arr = generateRandomArray(10, 10, 100);
console.log('原数组:', arr);

// 升序排序
const ascending = [...arr].sort((a, b) => a - b);
console.log('升序:', ascending);

// 降序排序
const descending = [...arr].sort((a, b) => b - a);
console.log('降序:', descending);

简洁写法

// 一行生成随机数组
const arr = Array.from({ length: 10 }, () => 
  Math.floor(Math.random() * 91) + 10
);

// 排序
arr.sort((a, b) => a - b);
console.log(arr);

生成不重复的随机数

function generateUniqueRandomArray(count, min, max) {
  // 检查范围是否足够
  if (max - min + 1 < count) {
    throw new Error('范围内的数字不足');
  }
  
  const set = new Set();
  while (set.size < count) {
    set.add(Math.floor(Math.random() * (max - min + 1)) + min);
  }
  return [...set];
}

const uniqueArr = generateUniqueRandomArray(10, 10, 100);
uniqueArr.sort((a, b) => a - b);
console.log(uniqueArr);

关键点

  • Math.random() 返回 [0, 1) 范围的小数,需要转换为指定范围的整数
  • 生成 [min, max] 范围整数的公式:Math.floor(Math.random() * (max - min + 1)) + min
  • sort() 默认按字符串排序,数字排序必须传入比较函数
  • 需要不重复的随机数时,用 Set 去重
  • Array.from({ length: n }, fn) 可以快速生成数组