Skip to content

36.随机数

js
// [0, 1);
Math.random();

// [min, max]
Math.random() * (max - min + 1) + min;
// [1, 5]
Math.randow() * 5 + 1;

// [min, max)
Math.random() * (max - min) + min;
Math.randow() * 4 + 1;

// [min, max)
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}

已知 1-5 随机数方法,生成 1-7 随机数

js
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
const isRandom15 = getRandomIntInclusive(1, 5);
const getTarget = isRandom15 +  (isRandom15 - 1) * 5; // 0 5 10 15

怎么定义 21

已知 1-3 随机数方法,生成 1-9 随机数

js
const target = isRandom13 +(issRandom13 - 1)\* 3
return (1 + target % 9)

已知 1-5 随机数方法,生成 1-7 随机数

js
const target = isRandom15 +(issRandom15 - 1)\* 5 // [1, 25], 限制 // [1, 21]
return (1 + target % M) //

已知 1-7 随机数方法,生成 1-9 随机数

js
const target = isRandom17 +(issRandom17 - 1)\* 7 // [1, 42], 限制 // [1, 36]

return (1 + target % M) //9 列 (36/9 = 4排)

已知 1-N 随机数方法,生成 1-M 随机数

js
const target = isRandom1N +(issRandom1N - 1)\* N
return (1 + target % M)

在 MIT 许可下发布