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