jaafar fawzi
jaafar fawzi

Reputation: 1

How we take just two numbers in Perl using rand?

In Perl using rand can we exclude number between max and min except some number.

Max 3 Min 1

X = Int (rand(max - min + 1) + min )

Result will be 1 and 2 and 3

I want to except 2 how did it in Perl?

Upvotes: 0

Views: 127

Answers (2)

Sergey Martynov
Sergey Martynov

Reputation: 446

If I understood correctly from comments, you want to select randomly from two possible values, right?

You can do it using a ternary operator like this:

$x = rand > 0.5 ? $min : $max;

In your particular example it can be:

$x = rand > 0.5 ? 1 : 3;

Upvotes: 0

ikegami
ikegami

Reputation: 385590

Simple, extensible approach:

my @nums = grep { $_ != $exclude } $min..$max;
my $n = int( rand( @nums ) );

Avoids building an array:

my $n = int( rand( $max - $min ) );
$n += $min;
++$n if $n >= $exclude;

For picking between two values:

my $n = rand() >= 0.5 ? $min : $max;

Upvotes: 1

Related Questions