我想创建一个整数数组,其中数字从 1...N 开始。每个数字在此数组中出现一次。例如,当 N = 5 时,数组 = {1, 3, 5, 2, 4}。
为了生成这个数组,我使用 shuffle 方法:
array=($(shuf -i 1-$N -n $N ))
效果很好。但是,我想向此代码添加种子,以确保每次使用相同的种子运行代码时,都会得到相同的数组。是否可以使用 shuffle 方法来做到这一点?
最佳答案
shuf
的 GNU 实现有一个 --random-source
参数。使用具有已知内容的文件名传递此参数将产生一组可靠的输出。
请参阅Random sources GNU coreutils 手册中的文档,其中包含以下示例实现:
get_seeded_random() { seed="$1" openssl enc -aes-256-ctr -pass pass:"$seed" -nosalt \ </dev/zero 2>/dev/null } shuf -i1-100 --random-source=<(get_seeded_random 42)
要以不依赖字符串分割(以及 IFS 的当前值)的方式将结果加载到 bash 数组中,您的实现可能如下所示:
# with bash 4.0 or newer
readarray -t array < <(shuf -i1-100 --random-source=<(get_seeded_random 42))
# or, supporting bash 3.x as well
IFS=$'\n' read -r -d '' -a array \
< <(shuf -i1-100 --random-source=<(get_seeded_random 42) && printf '\0')
关于bash - 使用种子在 bash 中对数字进行洗牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962359/