Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用可用的binaryrandom(返回0或1)函数生成整数随机数_C_Algorithm_Random - Fatal编程技术网

C 使用可用的binaryrandom(返回0或1)函数生成整数随机数

C 使用可用的binaryrandom(返回0或1)函数生成整数随机数,c,algorithm,random,C,Algorithm,Random,在最近的一次采访中,我问了以下问题 给定一个随机返回0或1的函数BinaryRandom(),创建 一个函数int MyRandom(int),它创建一个小于或等于的随机数 使用BinaryRandom()等于给定的输入 由于我是一名每日堆栈溢出和Geeksforgeks用户,我回忆起Geeksforgeks上类似的问题,请参见下面的链接 唯一的区别是Geeksforgeks的范围是0-6,在我的例子中是0-6 给定一个返回0或1的函数BinaryRandom() 创建一个函数intMyRan

在最近的一次采访中,我问了以下问题

给定一个随机返回0或1的函数BinaryRandom(),创建 一个函数int MyRandom(int),它创建一个小于或等于的随机数 使用BinaryRandom()等于给定的输入

由于我是一名每日堆栈溢出和Geeksforgeks用户,我回忆起Geeksforgeks上类似的问题,请参见下面的链接

唯一的区别是Geeksforgeks的范围是0-6,在我的例子中是0-6 给定一个返回0或1的函数BinaryRandom() 创建一个函数int
MyRandom(int)
,该函数创建一个小于或等于给定输入的随机数

  • 查找
    max
    -->
    bitwidth
    的位宽度。也许数到右移直到0。例如,对于
    max==42
    ,我们需要6位

  • 通过调用
    binarydrandom()
    形成随机数。例如,使用6位,将形成一个数字
    [0…63]

    int r = 0;
    // Double the value each iteration and add new bit.
    for (i = 0; i<bitwidth; i++) r = 2*r + BinaryRandom();  
    
    intr=0;
    //每次迭代将值加倍并添加新位。
    对于(i=0;i max
    ,重复步骤2

  • 返回
    r


  • 有一些方法(未显示)可以减少重做步骤2的可能性,但我们希望通过执行类似于“从多到多”的r_迭代来避免结果偏差%42

    基于chux的答案这里是一个简单的实现:

    int MyRandom(int max){
    对于(;;){
    int r=0;
    对于(m=max;m>0;m>>=1){
    r+=r+BinaryRandom();
    }
    
    如果(r),你需要声明一个下限。例如,如果N是3,则有无穷多个小于N的整数:2,1,0,−1.−2.−3,…您的下限可能是0或1(含),但在您声明之前,我们无法知道是哪一个。“我发现很难理解”这不是一个非常精确的陈述。你能试着找到一个更精确的陈述吗?答案中是否有某个地方你读了一个句子却不能完全理解它?你能把它变成一个你可以问的具体问题吗?
    int r = 0;
    // Double the value each iteration and add new bit.
    for (i = 0; i<bitwidth; i++) r = 2*r + BinaryRandom();