Results 1 to 7 of 7
  1. #1
    Join Date
    Feb 2004
    Posts
    52

    Question Unanswered: Generating random numbers

    Hi everybody.

    I hope you can shed some light here.
    How can I generate random numbers inside one do-loop ?

    Here is what I have so far:

    # Random number
    for (( i=1; i<=500; i++)
    do
    j = random
    printf $j
    end

    The problem with this loop is that running this script twice,
    the same 500 'random' numbers are generated.
    I thought about using the date in seconds as a seed but
    I am not sure whether this is the most eficient way to do it.
    I appreciate any help

    Thanks,

    Serg

  2. #2
    Join Date
    Jan 2004
    Location
    Bordeaux, France
    Posts
    320
    Use $SECONDS as seed
    Code:
    RANDOM=$SECONDS
    for ( i=1; i<=500; i++))
    do
       j = random
       printf $j
    end
    Jean-Pierre.

  3. #3
    Join Date
    Jun 2002
    Location
    UK
    Posts
    525
    You can use the RANDOM environment variable to generate random numbers.

    echo ${RANDOM}

    If you wanted a number between say 1 and 500, you would use...

    echo $((RANDOM % 500 +1))

  4. #4
    Join Date
    Feb 2004
    Posts
    52

    Exclamation

    Thanks all.

    I tried to use $SECONDS but...this is my short script :

    random=$seconds
    for (( i=1; i<= 500; i++))
    do
    j=random
    printf "$i number is $j";
    end

    and the output is

    1 number is random
    2 number is random
    ...
    500 number is random

    Could be a typo ?

    Thanks again, Serg.
    Obs. I will check your suggestion too, Damien.

  5. #5
    Join Date
    Jan 2004
    Location
    Bordeaux, France
    Posts
    320
    typo error for me and for you
    Unix is case sensitive ...
    Code:
    RANDOM=$SECONDS
    for (( i=1; i<= 500; i++))
    do
       j=$RANDOM
       printf "$i number is $j";
    done
    Jean-Pierre.

  6. #6
    Join Date
    Feb 2004
    Posts
    52

    Cool

    Thanks, Jean Pierre.

    It was indeed those typos.
    Anyway, the generated random numbers are
    not really random because running the script
    twice create the same set of 500 random numbers.

    I am using bash shell. Do you
    know if bash recognize comand $seconds ?
    I solved this problem using

    random=$(date +%s)

    Thanks again for your help.

    Serg

  7. #7
    Join Date
    Jan 2004
    Location
    Bordeaux, France
    Posts
    320
    Extracted from 'bash' man page :
    `SECONDS'
    This variable expands to the number of seconds since the shell was
    started. Assignment to this variable resets the count to the
    value assigned, and the expanded value becomes the value assigned
    plus the number of seconds since the assignment.
    Jean-Pierre.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •