470.用Rand7()实现Rand10()
链接:470.用Rand7()实现Rand10()
难度:Medium
标签:数学、拒绝采样、概率与统计、随机化
简介:已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
题解 1 - typescript
- 编辑时间:2021-05-08
- 执行用时:140ms
- 内存消耗:46.3MB
- 编程语言:typescript
- 解法介绍:利用两次 rand7 进行值判断。
function rand10(): number {
  let row: number, col: number, idx: number;
  do {
    row = rand7();
    col = rand7();
    idx = col + (row - 1) * 7;
  } while (idx > 40);
  return 1 + ((idx - 1) % 10);
}
题解 2 - typescript
- 编辑时间:2021-09-05
- 执行用时:108ms
- 内存消耗:46.5MB
- 编程语言:typescript
- 解法介绍:rand7 转换为下标。
function rand10(): number {
  let num!: number;
  do num = (rand7() - 1) * 7 + rand7();
  while (num > 40);
  return (num % 10) + 1;
}