Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate a random sequence of two words

How can I generate a random sequence of two words?

E.g. I want output like

act apt act act apt act act apt apt apt apt act

for words "apt" and "act" and sequence length 12

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I came up with

 repeat 12 { if [ $(($(($RANDOM%10))%2)) -eq 1 ] ; then echo act ; else echo apt ; fi }

but it is quite long, especially the coin toss, is there a more elegant way?

>Solution :

With shuf from GNU coreutils (in my case version 8.32):

shuf -r -n 12 -e act apt | tr '\n' ' '

From man shuf:

shuf – generate random permutations
-e, –echo : Treat each ARG as an input line
-r, –repeat : Output lines can be repeated
-n, –head-count=COUNT : Output at most COUNT lines

shuf alone prints one word per line, so we use tr to put all words into a single line by replacing the linebreaks by spaces.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading