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 2: 1 - True
Random number from 1 to 2: 2 - True
Random number from 1 to 13: 8 - True
Random number from 1 to 16: 16 - True
Random number from 1 to 10: 2 - True
Random number from 1 to 10: 4 - True
Random number from 1 to 6: 1 - True
Random number from 1 to 4: 1 - True
Random number from 1 to 14: 5 - True
Random number from 1 to 12: 2 - True
Random number from 1 to 6: 5 - True
Random number from 1 to 13: 6 - True

All tests passed successfully!

Log

© 2004-17 robson | cc unless stated