0

I need to pull the values from an array in a random order. It shouldn't pull the same value twice.

R=$(($RANDOM%5))
mixarray=("I" "like" "to" "play" "games")
echo ${mixarray[$R]}

I'm not sure what to do after the code above. I thought of putting the first pulled value into another array, and then nesting it all in a loop that checks that second array so it doesn't pull the same value twice from the first array. After many attempts, I just can't get the syntax right.

The output should be something like: to like I play games

Thanks,

  • 1
    Does this answer your question? [Simple method to shuffle the elements of an array in BASH shell?](https://stackoverflow.com/questions/5533569/simple-method-to-shuffle-the-elements-of-an-array-in-bash-shell) – pjh Nov 27 '20 at 20:05
  • 1
    See [how to randomly loop over an array (shuffle) in bash](https://stackoverflow.com/q/53229380). – pjh Nov 27 '20 at 20:08

1 Answers1

0

Would you please try the following:

#!/bin/bash

mixarray=("I" "like" "to" "play" "games")
mapfile -t result < <(for (( i = 0; i < ${#mixarray[@]}; i++ )); do
    echo -e "${RANDOM}\t${i}"
done | sort -nk1,1 | cut -f2 | while IFS= read -r n; do
    echo "${mixarray[$n]}"
done)
echo "${result[*]}"
  • First, it prints a random number and an index starting with 0 side by side.
  • The procedure above is repeated as much as the length of mixarray.
  • The output will look like:
13959   0
6416    1
6038    2
492     3
19893   4
  • Then the table is sorted with the 1st field:
492     3
6038    2
6416    1
13959   0
19893   4
  • Now the indices in the 2nd field are randomized. The field is extracted with the cut command.
  • Next rearrange the elements of mixarray using the randomized index.
  • Finally the array result is assigned with the output and printed out.
tshiono
  • 21,248
  • 2
  • 14
  • 22