Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rand() not so random in perl

Tags:

random

perl

I have a Perl script that gives me a 50 character string of random numbers, letters and some special characters. I am inputting them in a database. Now, given the length of the string and the amount of characters, I wouldn't think that duplicates would be easily created.

Here's the nifty nugget of code that creates the string:

my $random_id='';
my @c = ( "A" .. "Z", "a" .. "z", 0 .. 9, qw(! @ $ % ^ & *) );
$random_id = join '', map $c[rand @c] , 1 .. 50;

It produces strings like:

C1Qt8L7E7QUD%lkxnh9yjZ2njF0iMj!1o^4DmTbVNhQB9%dke@

The problem is it will duplicate an exact string every once and a while among unique ones, and more than once on some strings. And this is out of say 20 strings. It's bizarre. I can work around it and find a solution... but this perplexes me a bit. Would like to know why. Anybody have an idea?

like image 330
Paul Carlton Avatar asked Dec 06 '10 04:12

Paul Carlton


People also ask

Why is rand () giving me the same number?

This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up. If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.

What is difference between rand () and Srand ()?

The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.

Does rand () include 1?

rand produces numbers from the open interval (0,1) , which does not include 0 or 1, so you should never get those values..

How do I randomize in Perl?

Perl | rand() Function rand() function in Perl returns a random fractional number between 0 and the positive number value passed to it, or 1 if no value is specified. Automatically calls srand() to seed the random number generator unless it has already been called.


2 Answers

You need to use srand to seed the random number generator otherwise it will generate the same number series.

http://perldoc.perl.org/functions/srand.html

Edit:

According to the doc atthe url, if the perl version is before 5.004 then it won't automatically call that function. So check the perl version you're running under.

like image 83
Paul Avatar answered Oct 12 '22 23:10

Paul


you can also see String::Random - for generating random strings based on a pattern.

like image 35
Nikhil Jain Avatar answered Oct 12 '22 23:10

Nikhil Jain