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

Re: Generating Random Integers

by I0 (Priest)
on Jan 03, 2001 at 03:14 UTC ( [id://49417]=note: print w/replies, xml ) Need Help??


in reply to Generating Random Integers

$array[rand @array]

Replies are listed 'Best First'.
Re: Re: Generating Random Integers
by Blue (Hermit) on Jan 03, 2001 at 03:23 UTC
    Nice and easy solution IO. Since --OutpostMir-- mentioned he was a beginner a bit of detail might help him understand your answer.

    An array can take a non-integer subscript. It just uses the integer part. So you don't need to make it an integer. if you want to make it an integer for other reasons, you could use int() to make it an integer.

    Also the rand @array is taking @array in a scalar context. An array in scalar context returns the number of elements. So that rand @array calls rand with the number of element.

    In this case, replace $array and @array with the actual name of your array.

    =Blue
    ...you might be eaten by a grue...

      the rand @array is taking @array in a scalar context. An array in scalar context returns the number of elements

      Doesn't an array in scalar context return the index of the last element? i.e. if @array is a list of 10 values, I0's examples will be the equivalent of $array[rand 9]. rand 9 will effectively produce a random number between 0 and 8. This would mean that the last element in the array would never appear.

      Update: I'm wrong as per tilly's comment below. See my humble-pie-eating act below that one. <half-grin>
        An array in scalar context returns the number of elements in the array.

        As usual, I0 was both concise and correct.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://49417]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-03-29 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found