Interview Questions

I need a random true/false value ...

C Interview Questions and Answers


(Continued from previous question...)

I need a random true/false value ...

Q: I need a random true/false value, so I'm just taking rand() % 2, but it's alternating 0, 1, 0, 1, 0...

A: Poor pseudorandom number generators (such as the ones unfortunately supplied with some systems) are not very random in the low-order bits. (In fact, for a pure linear congruential random number generator with period 2**e, and this tends to be how random number generators for e-bit machines are written, the low-order n bits repeat with period 2**n.) For this reason, it's preferable to use the higher-order bits:

(Continued on next question...)

Other Interview Questions