note 39690 deleted from function.rand by tomsommer
| From: | tomsommer@php.net | Date: | Sat, 07 Feb 2004 17:37:56 +0000 |
| Subject: | note 39690 deleted from function.rand by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-64786@lists.php.net to get a copy of this message | ||
Note Submitter: raz0
----
If you need a way to select a random number between 1 and X and need 1 to be the number most likely
to be selected and X to be the least likely, well .. here is the solution. :)
<?php
function randomNumber($max, $exp)
{
$maxValue = pow($max, $exp);
srand((double)microtime()*1234567);
$rand = rand(1, $maxValue);
for($i=1; $i<=$max; $i++)
{
$values[$i] = pow($i, $exp);
}
$count = count($values);
$number = $max;
for($i=1; $i<=$count; $i++)
{
if ($rand <= $values[$i])
{
return $number;
}
$number--;
}
}
?>
Description: int randomNumber ( int max, float exp)
Example: $value = randomNumber(10, 2)
This will select a number between 1 and 10, where 10 is rather unlikely.
You can use the code below to test this function. It's rather messy, but who cares - It works.
;)
<?php
$array = array("", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
for ($i=0; $i<=30000; $i++)
{
$array[randomNumber(10, 1.5)]++;
}
$sum = array_sum($array);
unset($array[0]);
foreach ($array as $number => $entry)
{
print "$number - " . ((int) ($entry*100/$sum)) . "%\n";
}
?>