用种子重击随机?


8

我一直在使用$((1 + RANDOM % 1000))生成一个随机数。

是否可以做类似的事情但提供种子?

这样,给定相同的种子,总是会输出相同的随机数吗?

Answers:


14

将种子值分配给 RANDOM

$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$ 

注意,使用了单引号。双引号运行违反外壳插值规则:

$ bash -c 'RANDOM=42; echo $RANDOM $RANDOM $RANDOM'
19081 17033 15269
$ RANDOM=42
$ bash -c "RANDOM=640; echo $RANDOM"
19081
$ bash -c "RANDOM=640; echo $RANDOM"
17033
$ bash -c "RANDOM=640; echo $RANDOM"
15269
$ 

因为它$RANDOM是在bash -c ...运行子进程之前由父外壳插入的。使用单引号关闭插值(如上所示),或者防止插值:

$ RANDOM=42
$ SEED_FOR_MY_GAME=640
$ bash -c "RANDOM=$SEED_FOR_MY_GAME; echo \$RANDOM"
28612
$ bash -c "RANDOM=$SEED_FOR_MY_GAME; echo \$RANDOM"
28612
$ 

手册中RANDOM提到了此功能bash(1)

   RANDOM Each time this parameter is referenced, a random integer between
          0 and 32767 is generated.  The sequence of random numbers may be
          initialized by assigning a value to RANDOM.  If RANDOM is unset,
          it loses its special properties,  even  if  it  is  subsequently
          reset.

如果我跑步random=$(bash -c "RANDOM=640; echo $RANDOM"),不是每次都会返回相同的值吗?还是因为$(bash ...不会将b视为bash的新实例?
菲利普·柯比布莱德

1
双引号是可能不是你想要什么就有什么
thrig

1
观看以下操作会发生什么:set -x; FOO=42; bash -c "FOO=999; echo $FOO"。双引号允许将外壳替换$RANDOM为外壳的随机变量。内部bash外壳只是在回显一个整数。
杰夫·谢勒

@thrig我需要双引号,因为就我而言,它实际上是random=$(bash -c "RANDOM=$mac; echo $RANDOM")
Philip Kirkbride

当然,它应该bash -c 'RANDOM=42; echo "$RANDOM" "$RANDOM" "$RANDOM"'
G-Man说'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.