note 92266 deleted from function.rand by danbrown
| From: | danbrown@php.net | Date: | Thu, 16 Jul 2009 22:04:41 +0000 |
| Subject: | note 92266 deleted from function.rand by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158385@lists.php.net to get a copy of this message | ||
Note Submitter: Kaza55
----
Random number generator, without using rand() or mt_rand(), etc.
Feel free to use, no credit required!
<?
function new_rand($min, $max){
if($min == $max){return $max;}
if($min > $max){return $min;}
$k=0;
for($i=$min;$i<=$max;$i++){
$thearray[$k]=$i;
$k++;
}
shuffle($thearray);
return $thearray[0];
}
?>
Let's try it and see if we get an even distribution:
<?
$NUM_RUNS = 10000;
$num_one = 0;
$num_two = 0;
$num_three = 0;
$num_four = 0;
$num_five = 0;
for ($i=1;$i<=$NUM_RUNS;$i++){
$answer = new_rand(1,5);
if($answer == 1){$num_one++;}
if($answer == 2){$num_two++;}
if($answer == 3){$num_three++;}
if($answer == 4){$num_four++;}
if($answer == 5){$num_five++;}
}
echo "<b>1:</b> $num_one (";
printf("%.1f",($num_one/$NUM_RUNS)*100);
echo "%)<br>";
echo "<b>2:</b> $num_two (";
printf("%.1f",($num_two/$NUM_RUNS)*100);
echo "%)<br>";
echo "<b>3:</b> $num_three (";
printf("%.1f",($num_three/$NUM_RUNS)*100);
echo "%)<br>";
echo "<b>4:</b> $num_four (";
printf("%.1f",($num_four/$NUM_RUNS)*100);
echo "%)<br>";
echo "<b>5:</b> $num_five (";
printf("%.1f",($num_five/$NUM_RUNS)*100);
echo "%)<br>";
?>
Sample output:
1: 1984 (19.8%)
2: 2032 (20.3%)
3: 1987 (19.9%)
4: 1984 (19.8%)
5: 2013 (20.1%)