Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สุ่มตัวเลขในช่วงที่กำหนด - JavaScript

สุ่มตัวเลข n ตัว ในช่วง [min, max] ไม่ซ้ำกัน (Unique Random Numbers in Range)

ตัวอย่างโค้ด

const randomBetweenRange = (count, [min, max]) => {
  const res = [];
  const random = () => (Math.random() * (max - min) + min).toFixed(2);
  
  while (res.length < count) {
    const r = random();
    if (!res.includes(r)) res.push(r);
  }
  return res;
};

console.log(randomBetweenRange(10, [5, 15]));

ผลลัพธ์ตัวอย่าง

['13.25', '10.31', '11.83', '5.25', '6.28', '9.99', '6.09', '7.58', '12.64', '8.92']

ปัญหา: Infinite Loop Risk

ถ้า Range เล็กกว่า Count (เช่นสุ่ม 10 ตัวจาก 1-5) จะลูปไม่รู้จบ

เวอร์ชันปลอดภัย (Fisher-Yates Shuffle)

const randomBetweenRange = (count, [min, max]) => {
  const all = Array.from({ length: max - min + 1 }, (_, i) => (min + i).toFixed(2));
  // Shuffle
  for (let i = all.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [all[i], all[j]] = [all[j], all[i]];
  }
  return all.slice(0, count);
};

สร้างตัวเลขทั้งหมดในช่วง → Shuffle → เอา count ตัวแรก รับประกัน Unique และไม่ลูปตาย