Created
November 20, 2012 21:12
-
-
Save ircmaxell/4121166 to your computer and use it in GitHub Desktop.
Predictable Sequence Generator
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 | |
class PseudoRandomGenerator { | |
protected $state = null; | |
public function __construct($seed) { | |
$this->state = $seed; | |
} | |
public function next($max) { | |
$bits = (int) floor(log($max, 2) + 1); | |
$bytes = (int) max(ceil($bits / 8), 1); | |
$mask = (int) (pow(2, $bits) - 1); | |
do { | |
$test = $this->gen($bytes); | |
$result = hexdec(bin2hex($test)) & $mask; | |
} while ($result > $max); | |
return $result; | |
} | |
protected function gen($bytes) { | |
$this->state = hash('sha512', $this->state, true); | |
return substr($this->state, 0, $bytes); | |
} | |
} | |
$gen = PseudoRandomGenerator(1); | |
var_dump($gen->next(5)); | |
var_dump($gen->next(5)); | |
var_dump($gen->next(5)); | |
var_dump($gen->next(5)); | |
var_dump($gen->next(5)); | |
var_dump($gen->next(5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nitpicking: Forgot the
new
keyword when instantiating the object :P