Search code examples
csh

how to get either 0 or 1 randomly in csh


In bash to produce 1 and 0 random numbers I am using

#!/bin/bash
for i in `seq 1 100000`; do

    let rand=$RANDOM%2
    echo $i  $rand >> r-test.dat
done

and also using,

set randm = awk -v min=1000 -v max=10000 'BEGIN{srand(); print int(min+rand()*(max-min+1))}'

To produce random number, for example between 1000 and 10000 in csh. Now my question is how I can modify this command or use a more efficient way to produce 0 and 1 randomly in csh like what I am getting from first code in bash?

Thanks in advance for your comments.


Solution

  • set RAND = `od -vAn -N1 -tu1 < /dev/urandom` ; @ RAND01 = ( $RAND % 2 ) ; echo $RAND01
    

    Or, as a loop to generate 100,000 0s and 1s, like your bash script:

    #!/bin/csh
    
    cat /dev/urandom      # read from kernel's random number generator \
      | head -c 100000    # take the first 100,000 bytes \
      | od -vAn -tu1      # transform the raw bytes into integer numbers \
      | tr ' ' '\n'       # put every number on its own line (transform all [SPACE] characters to [LF] characters) \
      | grep -v '^ *$'    # filter out lines that are blank or only spaces \
      > r-test.tmp        # store the resulting 100,000 numbers in a temp file
    
    rm -f r-test.dat                       # reset the output file
    foreach RAND ( "`cat r-test.tmp`" )    # for each line in the temp file
        @ RAND01 = ( $RAND % 2 )           # use modulo 2 to map every input number to '0' or '1'
        echo $RAND01  >> r-test.dat        # store the results in an output file
    end                                    # end of loop
    

    Here is a bash version, for people working in bash instead of csh, since the commenting, looping, and arithmetic are a bit different:

    #!/bin/bash
    
    cat /dev/urandom   |  # read from kernel's random number generator
      head -c 100000   |  # take the first 100,000 bytes
      od -vAn -tu1     |  # transform the raw bytes into integer numbers
      tr ' ' '\n'      |  # put every number on its own line (transform all [SPACE] characters to [LF] characters)
      grep -v '^ *$'   |  # filter out lines that are blank or only spaces
      cat > r-test.tmp    # store the resulting 100,000 numbers in a temp file
    
    rm -f r-test.dat                  # reset the output file
    for RAND in `cat r-test.tmp`; do  # for each line in the temp file
        RAND01=$(( $RAND % 2 ))       # use modulo 2 to map every input number to '0' or '1'
        echo $RAND01  >> r-test.dat   # store the results in an output file
    done                              # end of loop