Last active
August 29, 2015 14:03
-
-
Save stormbrew/ccf533c1263e02d0bbf7 to your computer and use it in GitHub Desktop.
Twitter algorithmic code review
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
<?php | |
function getRandomRangedBytes($length, $max) { | |
// inspired by: http://stackoverflow.com/a/2999130/3803650 | |
// This safely generates a series of random bytes that are all within | |
// the range [0,$max) with an even distribution | |
$divisor = intval(255/$max); | |
$results = array(); | |
// This looks like it could be a loop that never terminates, | |
// but that would only be true if openssl was not returning us | |
// a uniform distribution of bytes, in which case we probably have | |
// bigger problems. | |
while (count($results) < $length) { | |
// generate bytes | |
$input = unpack("C*", openssl_random_pseudo_bytes($length - count($results))); | |
foreach ($input as $byte) { | |
// reject any byte that's >= to $max as it would | |
// skew the distribution. | |
$val = intval($byte / $divisor); | |
if ($val < $max) { | |
$results[] = $val; | |
} | |
} | |
} | |
return $results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment