首页 > 试题广场 >

用rand5()实现rand7()

[编程题]用rand5()实现rand7()
  • 热度指数:977 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个函数 rand5()可生成 [1,5] 范围内的均匀随机整数,请你试写一个方法 rand7 生成 [1,7] 范围内的均匀随机整数。
1.你只能调用 rand5() 且不能调用其他随机函数的方法。比如请不要使用系统的random() 方法,不要用题目里面类似于rand5的方法。
2.每个测试用例将有一个内部参数 n,表示你实现的函数 rand7() 在测试时将被调用的次数,但是这个参数不会被你看见,你可以在自测的时候使用。
3.该题判断你的代码是否正确的依据是:
3.1 你的代码不会陷入死循环,导致超时或者其他情况
3.2 你生成的数据是否都在[1,7]内
3.3 你生成的数据的期望是否接近4
3.4 你生成的数据在[1,7]是不是接近均匀分布

数据范围:

示例1

输入

1

输出

[2]
示例2

输入

2

输出

[1,5]
示例3

输入

3

输出

[1,3,7]
别打我
import java.util.*; 
 public class Solution { 
    public int rand5() { 
        return 1+(int)(Math.random()*5); 
    }

    public int rand7 () { 
        // write code here
        return 1+(int)(Math.random()*7); 
    } 
 }


发表于 2025-01-08 18:21:49 回复(0)
import java.lang.Math;

public class Solution {
    public int rand5() {
        return 1 + (int)(Math.random() * 5);
    }

    public int getRandomInt(int i, int j) {
        int a = i + (int)(Math.random() * (j - i));
        return a;
    }

    public int rand7 () {
        return getRandomInt(1, 8);
    }
}

发表于 2022-06-20 21:39:12 回复(0)
    public int rand7 () {
        // write code here
        int v = 5 * rand5() + rand5() - 5;
        if(v > 21) {
            return rand7();
        }
        return v % 7 + 1;
    }

发表于 2022-03-02 18:08:13 回复(0)