note 92266 added to function.rand
| From: | Kaza55 at osu1 dot php dot net | Date: | Thu, 16 Jul 2009 21:08:58 +0000 |
| Subject: | note 92266 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158383@lists.php.net to get a copy of this message | ||
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%)
----
Server IP: 64.71.164.2
Probable Submitter: 169.237.97.215
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/92266
Del: integrated -- https://master.php.net/note/delete/92266/integrated
Del: useless -- https://master.php.net/note/delete/92266/useless
Del: bad code -- https://master.php.net/note/delete/92266/bad+code
Del: spam -- https://master.php.net/note/delete/92266/spam
Del: non-english -- https://master.php.net/note/delete/92266/non-english
Del: in docs -- https://master.php.net/note/delete/92266/in+docs
Del: other reasons-- https://master.php.net/note/delete/92266
Reject -- https://master.php.net/note/reject/92266
Search -- https://master.php.net/manage/user-notes.php