Bash
#!/bin/bash
output="";
until [ -n "$output" ];do
output=`echo John Jeff Emma Steve Julie|sed 's/ /\n/'|shuf|head -n1|sed '/[^a-zA-Z]/d;'`;
done
echo $output
Portability
This isn't entirely portable. It works on Ubuntu 14.04 with GNU bash 4.3.11, GNU coreutils 8.21 and GNU sed 4.2.2. In OpenBSD, according to @kernigh, the \n
escape in the regex replacements doesn't work properly, and shuf
doesn't exist.
Explanation
This makes extra checks to ensure that its output is valid. It initialises a variable to the empty string, then obtains random names for it with a loop. The loop loops until the variable is not empty. Unless the name chosen in any iteration is valid (only contains letters a-z
and A-Z
), the variable is set to the empty string, causing the loop to run again.
So, if the large command in the loop produces invalid output, it is discarded, until valid output is produced. It is then printed.
The central command echoes the five names separated by spaces to sed 's/ /\n/'
, which turns the spaces into newlines to be passed to shuf
, which shuffles the lines in its input (only operates on lines, hence the sed
command is needed, head -n1
, which takes the first one, and sed '/[^a-zA-Z]/d;'
, which discards any invalid input it receives.
The first sed
command doesn't have the g
switch; only one substitution is made. Then, there are only two options:
John
and Jeff Emma Steve Julie
. The latter is discarded later on. Sorry, John.
Where should the output go? :) – Knerd – 2014-06-16T12:19:55.117
Erm, I'd say print to console if your language has one, if not echo/print it. – TMH – 2014-06-16T12:21:27.543
44http://xkcd.com/221/ – AstroCB – 2014-06-16T19:30:27.830
6@AstroCB one of my favourites. Right behind bobby tables. – Cruncher – 2014-06-16T20:08:28.697
50It seems like it would be sneakier if it was random, except for never picking one person. – Brendan Long – 2014-06-16T22:52:28.287
@AstroCB that's what I thought of immediately... Still trying to find a language that implements that. It'd take the cake :P – Jwosty – 2014-06-17T03:48:51.560
6
@AstroCB this one is also fantastic: http://dilbert.com/strips/comic/2001-10-25/
– gilbertohasnofb – 2014-06-18T10:08:07.0072
@AstroCB apparently, some large company cough - sony - cough did something similar
– iFreilicht – 2014-06-18T14:00:58.630ObRef: The original random-not-random story of Mel, the Real Programmer.
– Miserable Variable – 2014-07-15T19:11:44.4233I went through the first page: most answers always choose John, 2nd highest is Julie, Jeff is chosen rarely and Steve by 1. Even Ray got chosen by one but nobody chose Emma. Moral of the story: when standing in a line to decide randomly who will buy the drinks, name yourself Emma. – Miserable Variable – 2014-07-15T19:33:37.837