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.
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 14: 1 - True
Random number from 1 to 9: 8 - True
Random number from 1 to 19: 9 - True
Random number from 1 to 17: 3 - True
Random number from 1 to 12: 7 - True
Random number from 1 to 19: 18 - True
Random number from 1 to 18: 8 - True
Random number from 1 to 19: 8 - True
Random number from 1 to 10: 10 - True
Random number from 1 to 19: 5 - True
Random number from 1 to 12: 4 - True
Random number from 1 to 16: 4 - True
Random number from 1 to 8: 7 - True
Random number from 1 to 15: 12 - True
All tests passed successfully!