skip to Main Content

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);
}

2

Answers


  1. 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
    )
    
    Login or Signup to reply.
  2. Instead of comparing the input array to $size for the base case, use $size=0 as the base. Then you subtract 1 from $size when making the recursive calls. The function then generates one random number and pushes it onto the array returned by the recursive call.

    function rand_vector(int $size): array {
        if ($size == 0) {
            return [];
        }
        $temp = rand_vector($size-1);
        $temp[] = random_int(0, 30);
        return $temp;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search