I was recently given a task to accomplish which i failed. I don't usually ask for logic but today i am compalled to ask.Here is the task.
I am not allowed to use rand() function of php. instead i can use this function.
function getRandom()
{
return rand(1,5);
}
OK i tried this function but it is bound to return value from 3 to 7.
function getMoreRandom()
{
$value = getRandom();
return $value + 2;
}
Now i have to define a php function which can return me random number with the range 1 to 7. How can i do this?
function getMoreRandom()
{
do {
$temp = 5 * (getRandom() - 1) + getRandom();
} while ($temp > 21);
return $temp % 7 + 1;
}
flov's Answer is correct:
function getMoreRandom()
{
do {
$temp = 5 * (getRandom() - 1) + getRandom();
} while ($temp > 21);
return $temp % 7 + 1;
}
Testing it with:
$aryResults = array_pad(array(),8,0);
foreach(range(0,100000) as $i) $aryResults[getMoreRandom()]++;
$intSum = array_sum($aryResults);
foreach($aryResults as $intValue => $intCount) printf("Value %d Count %d (%.2f)\n",$intValue,$intCount,$intCount/$intSum);
Produces rectangular distribution
Value 0 Count 0 (0,00)
Value 1 Count 14328 (0,14)
Value 2 Count 14316 (0,14)
Value 3 Count 14185 (0,14)
Value 4 Count 14197 (0,14)
Value 5 Count 14322 (0,14)
Value 6 Count 14361 (0,14)
Value 7 Count 14292 (0,14)
Sorry I did not comment on the answer. Obviously I can't due to my lack of reputation (I'm new here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With