vendredi 7 avril 2017

Random element from an array bigger than 32k in bash

Having:

mapfile -t words < <( head -10000 /usr/share/dict/words)
echo "${#words[@]}" #10000
r=$(( $RANDOM % ${#words[@]} ))
echo "$r ${words[$r]}"

This select a random word from the array of 10k words.

But having the array bigger as 32k (e.g. whole file 200k+ words), it stops work because the $RANDOM is only up to 32k.

mapfile -t words < /usr/share/dict/words
echo "${#words[@]}" # 235886
r=$(( $RANDOM % ${#words[@]} )) #how to change this?
echo "$r ${words[$r]}"

Don't want use some perl like perl -plE 's/.*/int(rand()*$_)/e', not every system have perl installed. Looking for the simplest possible solution - and also don't care about the true randomness - it isn't for cryptography. :)




Aucun commentaire:

Enregistrer un commentaire