Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markpapadakis/37a194a6ddb783f95203 to your computer and use it in GitHub Desktop.
Save markpapadakis/37a194a6ddb783f95203 to your computer and use it in GitHub Desktop.
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