use of rand and srand 
Author Message
 use of rand and srand

hey..
I'm new to perl, about half way thru the llama book, and I'm trying to
use what I know to write a basic program of the following nature: one
that will give me the sender, time of message, and subject of all new
mail messages in a user's new incoming mail folder.  If there's mail
to be read, what I just described happens, otherwise, I want to grab a
random quote from a file of quotes.  Going by an example I saw in the

number in the range of the size of the array.. well, is there a better
way to seed srand ( if this is even possible ), to produce more random
results? It runs, but it's repeating itself often, not too random.
There's about 10-15 or so quotes in the file. Any help via email
would be greatly appreciated!

-mark
--
====================================================================

Offer good while supplies last.   | Boston University
Mark Thomas                       | CS Cluster Terminal Assistant

Phone: (Home) 617-352-6385        | Computer Science Undergraduate
       (Work) 617-353-5225        | Learning Perl!
:) :) :)

====================================================================



Tue, 18 Jun 1996 14:22:51 GMT  
 use of rand and srand


Quote:
> It runs, but it's repeating itself often, not too random.
> There's about 10-15 or so quotes in the file.

It's repeating itself often because there are so few quotes.  Get more
quotes.

Or you could make it store the number of the last quote you saw, and
not show you that one again the next time.



Sat, 22 Jun 1996 08:25:28 GMT  
 use of rand and srand


Quote:
>Going by an example I saw in the llama book, it says that using srand,

>array.. well, is there a better way to seed srand ( if this is even
>possible ), to produce more random results? It runs, but it's repeating
>itself often, not too random.

I've had various tasks where I needed some random bits, and kept running
into the same problem. I dunno what's the proper solution; as best I can
tell, srand() doesn't work very well at all. This may be a function of how
Perl is built; I have found it useless on sun4c/4.1.1 gcc-2.5.5.

I've taken to massaging my random bits in different ways, depending on the
task. For instance, here's my mkcookie, for MIT-MAGIC-COOKIE-1:

        #!/usr/local/bin/perl

        # Collect some bits
        $key = join('', `(ps -agxlww;pstat -afipSsT)|compress`);

        # Get Perl to treat ^ as bit-string op
        $discard = vec($key, 0, 128);

        while (length($key) >= 32) {
                $newlen = int(length($key)/2);
                $key = (substr($key, 0, $newlen) ^ substr($key, $newlen, $newlen));
        }

        $key = substr($key, 0, 16);
        print unpack("%H*", $key), "\n";

That's just grabing some random bits (from ps and pstat, fed through
compress) then repeatedly folding them with xor.

Here's a qotd script I wrote, which I use to croak out random fortunes from
a _huge_ database:

        #!/usr/local/bin/perl
        ($progname=$0)=~s#.*/##;
        $syntax = "syntax: $progname [-d]\n";
        require 'getopts.pl';
        &Getopts('d') || die $syntax;
        ($#ARGV == -1) || die $syntax;


        require 'dbwhere.pl';

        $off = int(((-s $idx)/4)*(unpack("%32L*",join('',`ps -agxlww`))/0xffffffff));
        print "#$off:\n" if $opt_d;

        open(IDX, "<$idx") || die "$progname: can't open $idx: $!\n";
        seek(IDX, $off*4, 0) || die "$progname: can't seek $idx to $off: $!\n";
        (read(IDX, $tmp, 4) == 4) || die "$progname: can't read 4 bytes from $idx at offset $off: $!\n";
        close(IDX);

        $off = unpack("L", $tmp);

        open(TXT, "<$txt") || die "$progname: can't open $txt: $!\n";
        seek(TXT, $off, 0) || die "$progname: can't seek $txt to $off: $!\n";
        while (<TXT>) {
                /^#(\d+)$/ && last;
                print;
        }
        close(TXT);

That's using the ps bits, feeding them through Perl's builtin checksum
function, then scaling to the desired range. Since this example seems pretty
close to what you're looking for, I'll go ahead and include the rest of my
qotd system.

dbwhere.pl just contains the pathnames of the files defining the database:

        $lib = '/usr/local/lib/qotd';
        $txt = "$lib/quotations";
        $idx = "$lib/quotations.idx";
        1;

$lib/quotations is the actual database; I used one from cs.utah.edu, which
looks like this:

Quote:
>                            A Day Off
>So you want a day off. Let's look at what you are asking for. There are 365
>days per year available for work. There are 52 weeks per year, inwhich you
>already have two days off, leaving 261 days available for work. Since you spend
>16 hours each day away from work, you have used up 170 days, leaving only 91
>days available, You spend 30 min. each day on coffee break, that accounts for
>23 more days each year, leaving only 68 days. With a one hyour lunch each day,
>you use up another 48 days, leaving only 22 days available for work. You
>normally spend 2 days per year on sick leav. This leaves only 20 days available
>for work. We offer 5 holidays per year, leaving only 15 days. We generously
>give you 14 days vacation per year leaving you only 1 day available for work
>and I'll be dammed if you're going to take that day off!!!
>#0
>                       -- NEWSFLASH --
>Russian tanks steamrolling through New Jersey!!!!  Details at eleven!
>#1
>                       -Gifts for Men -
>Men are amused by almost any idiot thing - that is why professional
>ice hockey is so popular - so buying gifts for them is easy.  But you
>should never buy them clothes.  Men believe they already have all the
>clothes they will ever need, and new ones make them nervous.  For
>example, your average man has 84 ties, but he wears, at most, only
>three of them.  He has learned, through humiliating trial and error,
>that if he wears any of the other 81 ties, his wife will probably laugh
>at him (You're not going to wear THAT tie with that suit, are you?).
>So he has narrowed it down to three safe ties, and has gone several
>years without being laughed at.  If you give him a new tie, he will
>pretend to like it, but deep inside he will hate you.

>If you want to give a man something practical, consider tires.  More
>than once, I would have gladly traded all the gifts I got for a new set
>of tires.
>                    -Dave Barry, Christmas Shopping: A Survivor's Guide
>#2

...

Quote:
>man who aim high get wall wet.
>#9554
>n + 1 trivial tasks take twice as long as n trivial tasks, for n
>sufficiently large.
>                    -Ed Logg
>#9555
>panic: can't find /
>#9556
>pi seconds is a nanocentury.
>                    -Tom Duff

The $lib/quotations.idx file contains 4-byte binary integers, one per quote,
with the offset of the start of the quote in the text file quotations. So,
the random lookup procedure is:

        1. Look at quotations.idx, note its length, divide by 4, that's how
           many quotes are available. Call the number of available quotes
           ``N''.
        2. Pick a random number in the range [0,N). Call that ``x''.
        3. Seek x*4 into quotations.idx, read 4 bytes, interpret them as a
           binary integer.
        4. Seek that far into quotations, and commence to print, contining
           until you see a match for ^#\d+$, which separates quotes.

Alternatively, I could have picked out two neighboring lengths from the idx
file, and computed how much to read and slurped the whole quote in one suck.
But then I'd have needed to be a bit cleverer about dealing with the last
quote. I decided I had invested enough cleverness in this thing already:-).

I built quotations.idx with this script, which I call mkidx:

        #!/usr/local/bin/perl
        ($progname=$0)=~s#.*/##;

        require 'dbwhere.pl';

        open(TXT, "<$txt") || die "$progname: can't open $txt: $!\n";
        $cur = 0;

        while (<TXT>) {
                /^#(\d+)$/ || next;
                ($cur == $1) || die "$progname: expected $cur, found $1 at line $.\n";
                $cur++;

        }
        close(TXT);

        open(IDX, ">$idx") || die "$progname: can't open $idx: $!\n";

        close(IDX);

-Bennett



Sun, 23 Jun 1996 03:38:38 GMT  
 use of rand and srand
: I've had various tasks where I needed some random bits, and kept running
: into the same problem. I dunno what's the proper solution; as best I can
: tell, srand() doesn't work very well at all. This may be a function of how
: Perl is built; I have found it useless on sun4c/4.1.1 gcc-2.5.5.
:
: I've taken to massaging my random bits in different ways, depending on the
: task. For instance, here's my mkcookie, for MIT-MAGIC-COOKIE-1:

That's funny, I got good results with:

        srand(time|($$*$$));

The X-Tagline you see after my sig is generated from my .profile, and
so far (about 3 months) I think that I didn't have a repetition.

This is in a NeXTStation running NS 2.2, don't know about SunOS 4.
--
Regards,
.--------------------------------------------------.  .-------------.
| Antonio Vasconcelos at The Lisbon $tock Exchange |  | sysadmin &  |
|           "I DO NOT SPEAK FOR BVL !!!"           |  | perl rookie |
|-------------------------------------------------------------------|


`-_________________________________________________________________-'
X-Tagline: I have no mouth, and I must burp.



Tue, 25 Jun 1996 19:03:22 GMT  
 
 [ 4 post ] 

 Relevant Pages 

1. rand and srand

2. srand or rand question

3. Broken rand() and srand() on perl5.005 ??

4. srand and rand fx

5. RAND/SRAND query

6. srand and rand on NTPerl 5.001-1L-091

7. rand() and srand() busted on SVR4?

8. Rand (or not to Rand)

9. Is rand() really rand ?

10. How do I ? .. rand/srand champs read this

11. How many significant digits in srand?

12. Problem with srand(time^$$)

 

 
Powered by phpBB® Forum Software