Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP random number generation with condition

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?

like image 369
Muhammad Raheel Avatar asked Dec 26 '22 10:12

Muhammad Raheel


2 Answers

function getMoreRandom()
{
    do {
        $temp = 5 * (getRandom() - 1) + getRandom();
    } while ($temp > 21);

    return $temp % 7 + 1;
}
like image 132
epicdev Avatar answered Jan 13 '23 13:01

epicdev


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).

like image 42
Felix Wessendorf Avatar answered Jan 13 '23 13:01

Felix Wessendorf