ndrwnaguib
ndrwnaguib

Reputation: 6115

PHP - Generating random numbers within an interval with respect to the mode X

I am trying to generate random numbers that their mode is equal to X (any real number). As a way of illustration, I expect a function whose header is rand(int min, int max, int mode), and when I call it with the following parameters rand(min: 1, max: 6, mode: 4) generates the following:

(1,2,4,4,4,5,3) // not exact, but similar

I am searching for an optimized way of doing so (although doing it manually would be the worst case, I am out of thoughts).

I have checked mt_rand(), rand, and other random generation functions, but have not found what I am looking for.

Any suggests?

Upvotes: 0

Views: 70

Answers (1)

nice_dev
nice_dev

Reputation: 17805

<?php 

function generateRandomWithMode($min,$max,$mode,$size){
    if(!($mode >= $min && $mode <= $max)){
        throw new Exception("Mode $mode is not between $min and $max range");       
    }

    $half_count = intval($size / 2);

    /* 
        set mode frequency as half of the size + any random value generated between 0 and half_count. This ensures
        that the mode you provided as the function parameter always remains the mode of the set of random values.
    */
    $mode_frequency = $half_count + rand(0,$half_count);

    $random_values = [];
    $size -= $mode_frequency;

    while($mode_frequency-- > 0) $random_values[] = $mode;
    while($size-- > 0) $random_values[] = rand($min,$max);

    shuffle($random_values);
    return $random_values;
}

print_r(generateRandomWithMode(1,100,4,10));

OUTPUT

Array
(
    [0] => 4
    [1] => 63
    [2] => 4
    [3] => 4
    [4] => 24
    [5] => 4
    [6] => 4
    [7] => 4
    [8] => 12
    [9] => 4
)

Upvotes: 2

Related Questions