gpt4 book ai didi

arrays - 如何在bash中随机循环数组(shuffle)

转载 作者:行者123 更新时间:2023-12-02 08:17:17 25 4
gpt4 key购买 nike

给定一个元素数组(服务器),如何对数组进行洗牌以获得随机的新数组?

inarray=("serverA" "serverB" "serverC")

outarray=($(randomize_func ${inarray[@]})

echo ${outarray[@]}
serverB serverC serverA

有一个命令shuf ( man page ) 但它并不存在于每个 Linux 上。

这是我第一次尝试在 stackoverflow 上发布 self 回答的问题,如果您有更好的解决方案,请发布。

最佳答案

这是另一个纯 Bash 解决方案:

#! /bin/bash

# Randomly permute the arguments and put them in array 'outarray'
function perm
{
outarray=( "$@" )

# The algorithm used is the Fisher-Yates Shuffle
# (https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle),
# also known as the Knuth Shuffle.

# Loop down through 'outarray', swapping the item at the current index
# with a random item chosen from the array up to (and including) that
# index
local idx rand_idx tmp
for ((idx=$#-1; idx>0 ; idx--)) ; do
rand_idx=$(( RANDOM % (idx+1) ))
# Swap if the randomly chosen item is not the current item
if (( rand_idx != idx )) ; then
tmp=${outarray[idx]}
outarray[idx]=${outarray[rand_idx]}
outarray[rand_idx]=$tmp
fi
done
}

inarray=( 'server A' 'server B' 'server C' )

# Declare 'outarray' for use by 'perm'
declare -a outarray

perm "${inarray[@]}"

# Display the contents of 'outarray'
declare -p outarray

这是 Shellcheck -干净,并使用 Bash 3 和 Bash 4 进行了测试。

调用者从 outarray 中获取结果,而不是将它们放入 outarray 中,因为 outarray=如果要打乱的任何项目包含空白字符,则 ( $(perm ...) ) 不起作用,并且如果项目包含全局元字符,它也可能会中断。没有什么好方法可以从 Bash 函数返回重要值。

如果从另一个函数调用perm,那么在调用者中声明outarray(例如使用local -a outarray)将避免创建(或破坏)全局变量。

可以通过无条件地进行交换来安全地简化代码,但代价是对项目本身进行一些毫无意义的交换。

关于arrays - 如何在bash中随机循环数组(shuffle),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com