Expected # of flips to get 10 heads in a row?

Pages: 12
Use bit masking.
1
2
3
4
5
6
// assuming `std::mt19937 generator;`
auto num = generator();
for (int i = 0; i < 32; ++i) {
    bool isHead = num & (1 << i);
    // do something with isHead
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
bool rand_bool()
{
    static std::mt19937 twister( std::time(nullptr) );
    static std::uint_fast32_t number = twister() ;
    static unsigned int bit_cnt = 0 ;

    const bool result = number & 1U ;
    
    ++bit_cnt ;
    if( bit_cnt == 31 ) { bit_cnt = 0 ; number = twister() ; }
    else number >>= 1U ;

    return result ;
}

bool rand_bool64()
{
    static std::mt19937_64 twister( std::time(nullptr) );
    static std::uint_fast64_t number = twister() ;
    static unsigned int bit_cnt = 0 ;

    const bool result = number & 1U ;
    
    ++bit_cnt ;
    if( bit_cnt == 64 ) { bit_cnt = 0 ; number = twister() ; }
    else number >>= 1U ;

    return result ;
}

coliru:
---------- clang++/libc++ ---------
std::mt19937, modulo division: 1550 msecs.
std::mt19937, use all 32 bits: 560 msecs.
std::mt19937, use all 64 bits: 670 msecs.
----------- g++/libstdc++ ---------
std::mt19937, modulo division: 750 msecs.
std::mt19937, use all 32 bits: 500 msecs.
std::mt19937, use all 64 bits: 470 msecs.

http://coliru.stacked-crooked.com/a/9f8b328c82c3a965

rextester:
---------- microsoft version: 190023506 ----------------
std::mt19937, modulo division: 652 msecs.
std::mt19937, use all 32 bits: 650 msecs.
std::mt19937, use all 64 bits: 677 msecs.

http://rextester.com/MVVIK56965
Topic archived. No new replies allowed.
Pages: 12