Reputation: 259
I have an array defined say @Array(1..31)
. Now I have a code where I randomly select a number for a certain number of times and store the results in another array. Example below :
$a1 = $Array[rand(@Array)];
push (@a2, $a1);
Now when I execute this script multiple times, I see that the new array contains very different patter everytime. But I do not want that, I want to generate a similar pattern everytime- where seed comes into picture.
Can someone please help me in how to incorporate seed to randomly select elements from array which can be predictable.?
Upvotes: 0
Views: 689
Reputation: 740
You do not replace rand
with srand
: you use srand
to initialize the seed for rand
: so call srand(0)
once and then use rand
as you had been.
From your comment, you can use:
srand(0);
sub random {
my $random_select = $_[rand(@_)];
print " The random number selected is $random_select\n";
return $random_select;
}
or back to your original code just add the first line to it:
BEGIN { srand(0) }
$a1 = $Array[rand(@Array)];
push (@a2, $a1);
Upvotes: 1