要產生一段區間內的隨機整數,很多人直覺會寫 Math.random()*10,但立刻會遇到兩個問題:結果永遠取不到上界,而且幾乎都是小數。本文從最基礎的原理推導,最後收斂成一個可以傳入任意上下界的通用函式。
Math.random() 回傳一個大於等於 0、嚴格小於 1 的浮點數。乘上 10 之後範圍變成 [0, 10),仍然取不到 10。若希望 1 到 10 都能出現,加 1 即可:
Math.random() * 10 + 1; // 範圍 [1, 11)
這時結果是 1.xxx 到 10.xxx 的小數,需要取整。這裡有兩個函式可選:
Math.floor() 無條件捨去:10.99 會變成 10。Math.ceil() 無條件進位:10.00001 會變成 11。因為我們要的是「下界包含、上界排除」的均勻分布,應該用 floor:
Math.floor(Math.random() * 10 + 1); // 得到 1 ~ 10 的整數
依同樣道理,2 到 10 就是把跨度改成 9:
Math.floor(Math.random() * 9 + 2); // 得到 2 ~ 10
每次動手算跨度太麻煩,把它抽成函式即可。注意跨度要 +1,因為區間是閉區間:
function selectFrom(lowValue, highValue){
var choice = highValue - lowValue + 1;
return Math.floor(Math.random() * choice + lowValue);
}
console.log(selectFrom(3, 11)); // 3 ~ 11
console.log(selectFrom(4, 88)); // 4 ~ 88
如果需求是「從區間中取 n 個不重複的數字」,可以在每次抽中後把它從候選陣列裡移除:
function pickUnique(low, high, count){
var pool = [], result = [];
for(var i = low; i <= high; i++) pool.push(i);
count = Math.min(count, pool.length);
for(var j = 0; j < count; j++){
var idx = Math.floor(Math.random() * pool.length);
result.push(pool.splice(idx, 1)[0]);
}
return result;
}
掌握「跨度 + 1、結果 floor、下界相加」這三個要點,任何整數區間的隨機取值都能一次寫對。