Skip to content

Instantly share code, notes, and snippets.

@ttback
Created May 27, 2015 21:34
Show Gist options
  • Save ttback/cf95cd9236aa702999a3 to your computer and use it in GitHub Desktop.
Save ttback/cf95cd9236aa702999a3 to your computer and use it in GitHub Desktop.
random bit
int unbiased_random_bit() {
int x1, x2, prev;
prev = 2;
x1 = rand() % 2;
x2 = rand() % 2;
for (;; x1 = rand() % 2, x2 = rand() % 2)
{
if (x1 ^ x2) // 01 -> 1, or 10 -> 0.
{
return x2;
}
else if (x1 & x2)
{
if (!prev) // 0011
return 1;
else
prev = 1; // 1111 -> continue, bias unresolved
}
else
{
if (prev == 1)// 1100
return 0;
else // 0000 -> continue, bias unresolved
prev = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment