Created
May 6, 2015 08:27
-
-
Save markpapadakis/37a194a6ddb783f95203 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static inline uint8_t RHeight(void) | |
{ | |
// Assuming probability 1/2 of an element appearing in layer i also appearing in layer i + 1 | |
// We can do the usual toss-the-coin dance, or we can just use RNG once and count the trailing zeros. | |
// Instead of using a loop to count, we can isolate the rightmost 0-bit, turn off all bits and sets that bit to 1, and then | |
// just compute count of trailing zeros instead. | |
const auto r = rand(); | |
const auto v = ~r & (r + 1); | |
const uint8_t tz = __builtin_ctz(v); | |
// We can't return 0, and we don't want to use a branch here, so we have to be creative | |
return 1 ^ ((1 ^ tz) & -(1 < tz)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment