[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Something fun...



At 7:59 pm 4/4/96, Tim Broderick wrote:
>The thing I'm looking for is a way to generate a random number, but also to
>limit the range of numbers. Something like 1-52 for a card game or 1-6 for
>craps.

        $number = 1 + int(rand(52));

will do it for you.

The 'rand' generates a random number between 0 and 51 (i.e. a random number
no larger than the argument you give it, in this case, 52), the 'int' chops
it down to an integer ('rand' generates floating-point numbers) and the '+
1' pushes it back into the range you want (1 .. 52). For your dice game,
obviously you simply substitute '6' for the '52'.

Incidentally, seeding the random number generator (which is to say, priming
it to produce a new sequence of random numbers) seems to work somewhat
differently on MacPerl than UNIX. The old UNIX standbys of:

        srand($$|time)

or

        srand(time)

or

        srand($$)

always cause the random number generator to generate identical sequences of
numbers (presumably MacPerl always has the same process number but I'm at a
loss as to why seeds based on 'time' should produce the same results on
every occasion, unless 'srand' is looking only at the high byte(s) of the
number).

On MacPerl, simply call 'srand()' before your first invocation of 'rand'
and you should get a suitably random set of random numbers each time.

>I'm sorry if this is easy to find on the net somewhere.  My wife and I
>recently had twins ... and I've found my surfing time to be limited.

That's no excuse. What kind of a hacker *are* you? <grin> Wait a couple of
years, give 'em each a Mac with a modem, and think of them as two more
research assistants ...

                        A

--
angus@aegypt.demon.co.uk  angus@pobox.com  http://www.tardis.ed.ac.uk/~angus/

    "If the times don't demand the best from you, invent other times."
        ["Baol: una tranquilla notte di regime", Stefano Benni]