如何在csh中随机获得0或1

时间:2018-05-24 20:28:11

标签: csh

在bash中产生1和0个随机数 我正在使用

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

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

并且还使用,

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

在csh中生成随机数,例如1000到10000之间。现在我的问题是如何修改此命令或使用更有效的方法在csh中随机生成0和1,就像我从bash中的第一个代码获得的那样?

提前感谢您的意见。

1 个答案:

答案 0 :(得分:1)

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

或者,作为生成100,000 0和1的循环,就像你的bash脚本一样:

#!/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

这是一个bash版本,适用于bash而不是csh的人,因为评论,循环和算术有点不同:

#!/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