Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive function that returns array with random X values

Is there any way I can write a function that only takes $size as an argument and returns an array with $size random values?

My approach so far using an initial array as parameter:

function rand_vector (array $arr, int $size): array {
    if (count($arr) == $size) return $arr;
    array_push($arr, random_int(0, 30));
    return rand_vector ($arr, $size);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If recursion is not required, you could create a one-liner where you give a max value and a count.

$randomSize = fn($size, $max) => array_map(fn($max) => random_int(0, $max), range(1, $size));

print_r($randomSize(20, 10));

Output

20 values from 0-10

Array
(
    [0] => 0
    [1] => 1
    [2] => 3
    [3] => 4
    [4] => 2
    [5] => 0
    [6] => 4
    [7] => 0
    [8] => 2
    [9] => 7
    [10] => 7
    [11] => 3
    [12] => 10
    [13] => 4
    [14] => 8
    [15] => 1
    [16] => 3
    [17] => 5
    [18] => 10
    [19] => 3
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading