bash - 使用种子在 bash 中对数字进行洗牌

标签 bash random gnu-coreutils

我想创建一个整数数组,其中数字从 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/

相关文章:

linux - 将文件名保存为递增数字

bash - 如何在 shell 脚本中进行整数比较的逻辑或运算?

c++程序寻找猜谜游戏的解决方案

python - 如何随机化现有的字节数组?

mysql 随机化结果和优化

filesize - 计算unix终端中特定文件的总空间消耗

linux - 语言环境如何在 Linux/POSIX 中工作以及应用了哪些转换?

bash - 检查传递给 Bash 脚本的参数数量

Linux bash 检查进程运行

bash - 使用 ed 操作 find 匹配的文件