'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?
Solution 1:[1]
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;
Solution 2:[2]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sergey Martynov |
