Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

rand / srand

by jbrugger (Parson)
on Oct 24, 2006 at 07:17 UTC ( #580201=perlquestion: print w/replies, xml ) Need Help??
jbrugger has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks

I need your help again.
For a tracking number, i generate random keys, with a length of 8 characters. The code i use is the following:

# srand(); # Generates collisions (no true random codes, also tried a +t the beginning of the code (not in the sub) # srand(time); # Generates collisions (no true random codes) sub GenCode { my $args = { AvailableChars => "ACDEFHIJKLMNPQRTUVWXYZ234679", CodeLength => 8, @_, }; # srand(); # Generates collisions (no true random codes, also tri +ed at the beginning of the code (not in the sub) # srand(time); # Generates collisions (no true random codes) srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`); #seems to work +, but is slow. my $rndcode = ''; my @AvailableCharsA = split "", $args->{AvailableChars}; for (my $j=0;$j<$args->{CodeLength};$j++) { $rndcode .= $AvailableCharsA[int(rand(@AvailableCharsA-1))]; } return $rndcode; }
The problem is the following:
If i use srand at the beginning of the module, it will create the same keys after some time again.
If i use srand(time), this also happens, so i've put it in the sub Gencode.
As the documentation of srand says, i should not do this, and next, the same keys were generated after some time again.
I searched Pelmonks, google, and came up with the above solution, using srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`);
This is 'slow', and i wonder why (mod) perl does not genterate true random codes, in the above code there should be enough space to generate lots of different keys without having collisions.

So the question is, how do i properly create random keys as described above

Thanks for all your help, i'll have to look into one of the solutions.
The thing (i think!) makes it difficult, is the fact that we preload all our modules into apache.
If the process is started and srand is called, i think the child process of apache uses the same seed (please correct me if i'm wrong here), thus generates the same random keys again.

"We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.

Replies are listed 'Best First'.
Re: rand / srand
by BrowserUk (Pope) on Oct 24, 2006 at 07:51 UTC

    Don't use srand. It's purpose is to make thing less random (more determanistic), not more so.

    Update: For this purpose, random integers in the range 0 .. 35, even the paltry 15-bit standard rand on my system is perfectly up to this task.

    Try this. This implementation of GenCode() and test program happily produces 10e6 unique random strings, from the 2.8 trillion possibles, before exhausting my memory and trapping.

    #! perl -slw use strict; $|++; sub rndStr{ join'', @_[ map{ rand @_ } 1 .. shift ] } sub GenCode{ return rndStr 8, 'A'..'Z', 0..9 } my %hits; until( exists $hits{ $_ = GenCode() } ){ keys( %hits ) % 10_000 or printf "\r%d\t", scalar keys %hits; ++$hits{ $_ } ; } printf "Collision after %d generations\n", scalar keys %hits;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: rand / srand
by spadacciniweb (Deacon) on Oct 24, 2006 at 07:52 UTC
Re: rand / srand
by bingos (Vicar) on Oct 24, 2006 at 07:29 UTC

    I played with srand/rand quite a bit and in the end abandoned their use in favour of Math::Random

      I strongly suggest Math::Random::MT::Auto for any random number generation work.

      The Mersenne Twister is a fast pseudorandom number generator (PRNG) th +at is capable of providing large volumes (> 10^6004) of "high quality +" pseudorandom data to applications that may exhaust available "truly +" random data sources or system-provided PRNGs such as rand.


      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: rand / srand
by GrandFather (Sage) on Oct 24, 2006 at 07:45 UTC

    rand is generally the C standard library rand function which varys from C to C implementation. rand is a pseudo-random number generator and it does repeat its cycle after a period that is a function of the specific implementation.Even minimal implementations should use at least 16 bits with a cycle length of 64K.

    Much better generators are available and there is a vast quantity of material available describing the virtues and failings of different generators. For your purpose how many numbers do you require? Do they need to be random (derived from a "random seed"). Do they need to be independent or can a random starting point be used in a very long sequence? How many do you need to generate per second?

    Random_number_generator is a starting point for exploring the world of random number generators. You could look at Math::Random for a better pseudo random number generator.

    DWIM is Perl's answer to Gödel

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://580201]
Approved by GrandFather
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2016-09-29 03:50 GMT
Find Nodes?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:

    Results (546 votes). Check out past polls.