[source]Custom random number generator 05-09-2013, 12:08 AM
#1
Hi!
Inspired by this video:
I wanted to make a pseudo random number generator, where the numbers wouldn't repeat.
I got close to it.
The following object is powered by mt_rand(). I might update it so we get cryptographically stronger numbers later on.
Usage:
First argument is min number, second is max number. Third argument (if supplied) will be used as seed. All arguments are optional.
If min isn't set, the min will be set to 0.
If max isn't set, it will be set to maximum mt_rand() value (mt_getrandmax()).
If seed isn't set, PHP will generate it.
So here is the object:
example code:
Inspired by this video:
I wanted to make a pseudo random number generator, where the numbers wouldn't repeat.
I got close to it.
The following object is powered by mt_rand(). I might update it so we get cryptographically stronger numbers later on.
Usage:
PHP Code:
<?php $rand_gen = new irand;
$rand = $rand_gen->rand(0, 100);?>If min isn't set, the min will be set to 0.
If max isn't set, it will be set to maximum mt_rand() value (mt_getrandmax()).
If seed isn't set, PHP will generate it.
So here is the object:
PHP Code:
<?php
class irand{
private static $arr = array(NULL); //Holds the information of already generated numbers
/*
* Outputs the number.
*/
public function rand($min = 0, $max = FALSE, $seed = false){
if($seed) mt_srand($seed);
if(!$max) $max = mt_getrandmax(); //If it isn't set.
$return = $this->generate(mt_rand($min, $max), $min, $max);
if(!$return && !is_numeric($return)){ //Everything was tested. Start again.
self::$arr = array(NULL);
return $this->generate(mt_rand($min, $max), $min, $max);
}
return $return;
}
/*
* Checks if a the variable was generated already.
*/
private function exists($num){
foreach(self::$arr as $val){
if($val == $num) return TRUE; //Tests if the number was already generated
}
return FALSE;
}
/*
* Generates the number.
*/
private function generate($rand, $min, $max){
if (empty(self::$arr[0]) && !is_numeric(self::$arr[0])){
self::$arr[0] = mt_rand($min, $max);
return self::$arr[0];
}
while($this->exists($rand)){
if(count(self::$arr) == (($max - $min) +1)) return FALSE;
$rand = mt_rand($min, $max);
}
self::$arr[] = $rand;
return $rand;
}
}
?>example code:
PHP Code:
<?php require_once 'object.php';
$rand_gen = new irand;
$num = array();
for($temp = 0; $temp <= 100; $temp++){
$rand = $rand_gen->rand(0, 100);
if(isset($num[$rand])) $num[$rand] += 1;
else $num[$rand] = 1;
}
arsort($num);
foreach($num as $key=>$val){
echo "The number $key has occured $val times.<br/>";
}?>Staff will never ever ask you for your personal information.
We know everything about you anyway.
We know everything about you anyway.
![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)


![[Image: a8Wp2g3_460sa.gif]](http://d24w6bsrhbeh9d.cloudfront.net/photo/a8Wp2g3_460sa.gif)
