Expand a random range from 1–5 to 1–7

前端 未结 30 2833
一个人的身影
一个人的身影 2020-11-22 07:29

Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.

  1. What is a simple so
30条回答
  •  逝去的感伤
    2020-11-22 08:21

    int randbit( void )
    {
        while( 1 )
        {
            int r = rand5();
            if( r <= 4 ) return(r & 1);
        }
    }
    
    int randint( int nbits )
    {
        int result = 0;
        while( nbits-- )
        {
            result = (result<<1) | randbit();
        }
        return( result );
    }
    
    int rand7( void )
    {
        while( 1 )
        {
            int r = randint( 3 ) + 1;
            if( r <= 7 ) return( r );
        }
    }
    

提交回复
热议问题