On 3/16/07, Grant <[EMAIL PROTECTED]> wrote:
Hello, I need to generate two random numbers. One should be a 1, 2,
or 3, and the other should be a 1 or 2. How can I do that?
- Grant
That depends on your needs. The rand function creates decent quality
pseudo-random numbers (it calls srand with the time if it has not
already been called) greater than 0 and less than 1. Therefore you
can get a random 1, 2, or 3 like this
my $num = int rand 3 + 1;
Likewise you can get the other like this:
my $num = int rand 2 + 1;
If you need a better pseudo-random number than rand can provide and
you are using Linux (or possibly other unix like operating systems)
you can read from /dev/urandom
#!/usr/bin/perl
use strict;
use warnings;
open my $rand, '<', '/dev/urandom'
or die "could not open /dev/urandom:$!";
my $num;
{ local $/ = \1; $num = int ord(<$rand>) / 256 * 3 + 1 }
print "$num\n";
If you need better randomness than that you can read from /dev/random,
but be warned that file will block if the operating system has not
collected enough data to produce a good random number.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/