FAQ 4.11 How do I get a random number between X and Y?
  Home FAQ Contact Sign in
comp.lang.perl.misc only
 
Advanced search
POPULAR GROUPS

more...

comp.lang.perl.misc Profile…
 Up
FAQ 4.11 How do I get a random number between X and Y?         


Author: PerlFAQ Server
Date: May 1, 2008 18:03

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

4.11: How do I get a random number between X and Y?

To get a random number between two values, you can use the "rand()"
built-in to get a random number between 0 and 1. From there, you shift
that into the range that you want.

"rand($x)" returns a number such that "0 <= rand($x) < $x". Thus what
you want to have perl figure out is a random number in the range from 0
to the difference between your *X* and *Y*.

That is, to get a number between 10 and 15, inclusive, you want a random
number between 0 and 5 that you can then add to 10.

my $number = 10 + int rand( 15-10+1 ); # ( 10,11,12,13,14, or 15 )

Hence you derive the following simple function to abstract that. It
selects a random integer between the two given integers (inclusive), For
example: "random_int_between(50,120)".
Show full article (2.17Kb)
no comments