Robson » Little Red Book » Random Numbers #3

Chapter 7 - Question 4

Extend an available random function to create a new function of two integer values, a lower-bound and an upper-bound, and return an integer such that:

    lower-bound <= random-integer <= upper-bound

Produce a program to test the function.

Solution 1

PHP:

<?    // returns a random number between the lowest and highest numbers specificed, inclusive    function random_number($lowest, $highest)    {        // well, that was easy!        return mt_rand($lowest, $highest);    }      // generate some random lower and upper bounds    $lower_bound = mt_rand(0, 10);    $upper_bound = mt_rand(11, 20);        // perform a random number of tests to ensure the function works    for ($n = 0; $n < mt_rand(5, 15); $n++)    {        // generate a random number using the custom function        $x = random_number($lower_bound, $upper_bound);        // show the lower/upper boundaries, the random number        // and if it is valid (1) or invalid (0)        echo $lower_bound . ' &lt;= ' . $x . ' &lt;= ' . $upper_bound . ' : ' .             ($x >= $lower_bound && $x <= $upper_bound) . '<br/>';    }     ?>

Which produces:

1 <= 9 <= 17 : 1
1 <= 9 <= 17 : 1
1 <= 16 <= 17 : 1
1 <= 5 <= 17 : 1
1 <= 11 <= 17 : 1
1 <= 13 <= 17 : 1
1 <= 12 <= 17 : 1
1 <= 12 <= 17 : 1
© 2004-20 robson | cc unless stated