Skip to content

Instantly share code, notes, and snippets.

@ircmaxell
Created November 20, 2012 21:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ircmaxell/4121166 to your computer and use it in GitHub Desktop.
Save ircmaxell/4121166 to your computer and use it in GitHub Desktop.
Predictable Sequence Generator
<?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));
@cspray
Copy link

cspray commented Nov 21, 2012

Nitpicking: Forgot the new keyword when instantiating the object :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment