Robson » Little Red Book » Random Numbers #1

Chapter 7 - Question 2

Construct a program that contains a function, with a single non-zero positive integer parameter not greater than the largest permitted integer, that computes and returns a random integer in the range 1 to the given value.

The main program should call and test the function with various values.

The function should use any available random number generator.

Solution 1

PHP:

<?    // returns a number between 1 and the parameter    function ic_random($highest)    {        // use the mt random function for improved randomness and reduced time        return mt_rand(1, $highest);    }        // perform a random number of tests    for ($n = 0; $n < mt_rand(10, 20); $n++)    {        // generate a random highest value        $highest = mt_rand(1, 20);        // send the highest value to the random function        $result = ic_random($highest);        // show the range and the result        echo 'Random number from 1 to ' . $highest . ': ' . $result;        // check if it matches the rules        if ($result >= 1 && $result <= $highest)            // show the user this was a valid number            echo ' - <span style="color:green">True</span>';        else        {            // this number doesn't match the rule, show that to the user            echo ' - <span style="color:red">False</span>';            // increment failed counter            $failed++;        }        echo '<br/>';    }        // check the number of failures    if (!$failed)        echo '<br/><span style="color:green">All tests passed successfully!</span>';    else        echo '<br/><span style="color:red">Failed tests: ' . $failed . '</span>'; ?>

Which produces:

Random number from 1 to 15: 2 - True
Random number from 1 to 11: 9 - True
Random number from 1 to 5: 3 - True
Random number from 1 to 19: 17 - True
Random number from 1 to 19: 11 - True
Random number from 1 to 9: 2 - True
Random number from 1 to 6: 2 - True
Random number from 1 to 4: 4 - True
Random number from 1 to 8: 6 - True
Random number from 1 to 9: 7 - True
Random number from 1 to 2: 2 - True
Random number from 1 to 8: 1 - True
Random number from 1 to 19: 12 - True
Random number from 1 to 4: 2 - True
Random number from 1 to 12: 11 - True

All tests passed successfully!

Log

© 2004-20 robson | cc unless stated