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

Re: Needing a random number generator for scripting



On Thu, Sep 27, 2001 at 09:00:26AM +0200, A.R. (Tom) Peters wrote:
| On 27 Sep 2001, Jeremy Whetzel wrote:
| 
| > I'm in the process of writing up a script that I need to be able to
| > "randomly" switch around the lines in a text file.  (ala a random mp3
| > playlist) Would anyone have any suggestions?  I was originally thinking
| > of using a random number generator for it, but if there's a tool that
| > would work better...?
| 
| /dev/random gives random bits.  I don't know where it is documented.
| There is a system call random() (see man 3 random).  You could write a
| wrapper C program to use it in scripts.

Naw, just use python :-).


#!/usr/bin/env python

def my_randint() :
    """
    This is a custom randomizer that uses the Linux /dev/random.
    It returns a random integer in an unknown range.  (Use modulo
    division to scale it down to the intended range)
    """
    # used to convert the raw bits to a Python int
    import struct

    dev_random = open( "/dev/random" , "r" )
    # use a 4-byte integer
    raw_index = dev_random.read( 4 )
    # 'unsigned int' however this returns a Python Long
    return struct.unpack( "I" , raw_index )[0]


Or you can use the standard built-in random functions :

#!/usr/bin/env python
import random
print random.random() # this gives a float between 0 and 1
print random.randint( 0 , 10 ) # this gives an int between 0 and 10
                               # (the arguments)


-D



Reply to: