The fastest way to obtain a random integer number in a certain range [a, b]
, excluding one value c
, is to generate it between a
and b-1
, and then increment it by one if it's higher than or equal to c
.
Here's a working function:
function randomExcluded(min, max, excluded) {
var n = Math.floor(Math.random() * (max-min) + min);
if (n >= excluded) n++;
return n;
}
This solution only has a complexity of O(1).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…