@ 2015-04-24T18:29:29Z <?php
class PseudoRandomSequence {
const STATE_HASH = "sha512";
// 1/2 STATE_HASH block size,
const STATE_SIZE = 32;
private $state;
public function __construct($state) {
$this->state = $state;
$this->mixState();
}
public function int($min = 0, $max = PHP_INT_MAX) {
$range = $max - $min;
if ($range <= 0 || is_float($range)) {
throw new Exception("Invalid min/max provided");
}
$bits = 0;
$tmp = $range;
while ($tmp >>= 1) {
$bits++;
}
$bytes = (int) max(ceil($bits / 8), 1);
$mask = pow(2, $bits) - 1;
do {
$rand = $this->bytes(8);
$result = hexdec(bin2hex($rand)) & $mask;
} while ($result > $range);
return $result + $min;
}
public function bytes($n) {
$ret = '';
do {
$ret .= $this->mixState();
} while (strlen($ret) < $n);
return substr($ret, 0, $n);
}
private function mixState() {
$hash = hash(self::STATE_HASH, $this->state, true);
$this->state = substr($hash, 0, self::STATE_SIZE);
return substr($this->state, self::STATE_SIZE);
}
}
$prng = new PseudoRandomSequence("test");
var_dump($prng->int(0, 10));
var_dump($prng->int(0, 10));
var_dump($prng->int(0, 10));
var_dump($prng->int(0, 10));
$prng = new PseudoRandomSequence("other");
var_dump($prng->int(0, 100));
var_dump($prng->int(0, 100));
var_dump($prng->int(0, 100));
var_dump($prng->int(0, 100));
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for 5.4.0 - 5.4.45 , 5.5.0 - 5.5.38 , 5.6.0 - 5.6.28 , 7.0.0 - 7.0.20 , 7.1.0 - 7.1.20 , 7.2.0 - 7.2.33 , 7.3.16 - 7.3.33 , 7.4.0 - 7.4.33 , 8.0.0 - 8.0.30 , 8.1.0 - 8.1.28 , 8.2.0 - 8.2.18 , 8.3.0 - 8.3.4 , 8.3.6 Process exited with code 137 . Output for 8.3.5 Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Process exited with code 137 . preferences:dark mode live preview
209.3 ms | 401 KiB | 273 Q