[Question]
  [
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
 
 
As a little joke in the office someone wanted a script that randomly picks a name, and said person will make a round of drinks. 
Let's call the people John, Jeff, Emma, Steve and Julie.
I thought it would be funny to make a script that seems random at a quick glance, but actually always gives the same person as the output (Up to you who you choose). 
Highest voted answer wins after a week
And the winner is....
Paul R with (currently) 158 votes.
The answers here are great, and if anyone else has any other ideas what haven't been posted yet, please add them, I love reading through them.
  
[Answer]
# C
It's important to decide who is buying as quickly as possible, so as not to waste precious drinking time - hence **C** is the obvious choice in order to get maximum performance:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
    const char *buyer;
    int n;
    srand(time(NULL)); // make sure we get a good random seed to make things fair !
    n = rand();
    switch (n % 5)
    {
        case 0: buyer = "John";
        case 1: buyer = "Jeff";
        case 2: buyer = "Emma";
        case 3: buyer = "Steve";
        case 4: buyer = "Julie";
    }
    printf("The person who is buying the drinks today is: %s !!!\n", buyer);
    return 0;
}
```
Explanation:
> 
>  This would work just fine if there was a `break;` after each case in the switch statement. As it stands however each case "falls through" to the next one, so poor Julie always ends up buying the drinks.
> 
> 
> 
[Answer]
# PHP
Couldn't let this go, so here is another one:
```
$f = fopen('/dev/random','r');
$s = fread($f, 4);
fclose($f);
$names = ['John', 'Jeff', 'Emma', 'Steve', 'Julie'];
echo $names[$s % count($names)];
```
> 
>  This is actually not guaranteed to produce john, but chances are
>  very good. PHP will happily take whatever /dev/random have to offer
>  see that it (probably) can't parse it and come up with the very
>  reasonable number 0 instead. After all, alerting the programmer to
>  a potential error is considered a deadly sin in PHP.
> 
> 
> 
[Answer]
# Haskell
It's too transparent if it always returns the same name so try the following
```
import Control.Monad
import System.Exit
import Control.Concurrent
import Control.Concurrent.MVar
data Person = John | Jeff | Emma | Steve | Julie deriving (Show, Enum)
next Julie = John
next p = succ p
rotate :: MVar Person -> IO ()
rotate mp = modifyMVar_ mp (return . next) >> rotate mp
main :: IO ()
main = do
    mp <- newMVar John
    forkIO $ rotate mp
    putStrLn "Shuffling"
    readMVar mp >>= print
    exitWith ExitSuccess
```
Whenever you want it to be random:
```
[~]$ runghc prog.hs
Shuffling
Steve
[~]$ runghc prog.hs
Shuffling
Julie
```
And for your unfortunate target:
```
[~]$ runhugs prog.hs
Shuffling
John
[~]$ runhugs prog.hs
Shuffling
John
```
> 
>  Hugs only implements cooperative multitasking, so the `rotate` thread
>  will never run
> 
> 
> 
[Answer]
# Bash - maximum simplicity
A very simple example - let's avoid any problems by doing it the textbook way. Don't forget to seed the generator from the system clock for a good result!
```
#!/bin/bash
names=(John Jeff Emma Steve Julie)   # Create an array with the list of names
RANDOM=$SECONDS                      # Seed the random generator with seconds since epoch
number=$((RANDOM % 5))               # Pick a number from 0 to 4
echo ${names[number]}                # Pick a name
```
> 
> This relies on the user not knowing what the `$SECONDS` builtin actually does; it returns the number of seconds since the current shell started.
> 
> As it's in a script, the shell always started zero seconds ago, so the generator is always seeded with `0` and Julie always buys the beer.
> 
> 
> 
Bonus:
> 
> This one stands up to scrutiny quite well; If you enter the same code on the commandline instead of in a script, it will give random results, because `$SECONDS` will return the length of time the user's interactive shell has been running.
> 
> 
> 
[Answer]
## C#
```
using System;
using System.Linq;
namespace PCCG {
    class PCCG31836 {
        public static void Main() {
            var names = new string[]{ "John", "Jeff", "Emma", "Steve", "Julie" };
            var rng = new Random();
            names.OrderBy(name => rng.Next());
            Console.WriteLine(names[0]);
        }
    }
}
```
> 
>  This might not fool people who are familiar with the .Net API, but people who don't know it might believe that `OrderBy` modifies the object you call it on, and it's a plausible error for a newbie to the API to make.
> 
> 
> 
[Answer]
## PowerShell
```
$names = @{0='John'; 1='Jeff'; 2='Emma'; 3='Steve'; 4='Julie'}
$id = random -maximum $names.Length
$names[$id]
```
This will always output `John`.
> 
>  `$names` is a `System.Collections.Hashtable` which doesn't have a `Length` property. Starting with PowerShell v3, `Length` (and also `Count`) can be used as a property on any object. If an object does not have the property, it will return `1` when the object is not null, else it will return `0`. So in my answer, `$names.Length` evaluates as 1, and `random -maximum 1` always returns 0 since the maximum is exclusive.
> 
> 
> 
[Answer]
# Q
```
show rand `John`Jeff`Emma`Steve`Julie;
exit 0;
```
> 
>  Q always initialises its random number seed with the same value.
> 
> 
> 
[Answer]
# Perl
```
use strict;
my @people = qw/John Jeff Emma Steve Julie/;
my @index = int(rand() * 5);
print "Person @index is buying: $people[@index]\n";
```
> 
> Prints: `Person X is buying: Jeff` (where X is from 0-4)  
>   
> 
> Abusing scalar context a bit. `@index = int(rand() * 5)` places a random integer from 0 - 4 in the 0th position of the `@index` list. When printing the array, it properly prints the random integer in @index, but when using as an array index in `$people[@index]`, @index uses scalar context, giving it the value of the list size, i.e. `1`.
> 
> Interestingly enough, `@people[@index]` makes it index properly.
> 
> 
>  Interestingly enough `@people[@index]` is a hash slice in Perl, so `@index` is evaluated in the list context; in this case, it's a single entry list and that's why it works correctly
> 
> 
> 
> 
> 
> 
> 
[Answer]
## ECMAScript
```
// Randomly pick a person on only one line!
var people = [('John', 'Jeff', 'Emma', 'Steve', 'Julie')];
console.log(people[new Date() % people.length | 0]);
```
It **always** picks Julie. 
> 
>  It has brackets inside the square brackets, and [the comma operator](http://www.ecma-international.org/ecma-262/5.1/#sec-11.14) returns the value of its right operand.  
> 
>  It's also very easy to miss. I've missed it before in **real** code.
> 
> 
> 
[Answer]
# C#
```
using System;
namespace LetsTroll {
    class Program {
        static void Main() {
            var names = new string[]{ "John", "Jeff", "Emma", "Steve", "Julie" };
            var random = new Random(5).NextDouble();
            var id = (int)Math.Floor(random);
            Console.WriteLine(names[id]);
        }
    }
}
```
> 
>  The trick is, the method `new Random().NextDouble()` returns a double between 0 and 1. By applying `Math.Floor()` on this value, it will always be 0.
> 
> 
> 
[Answer]
## C#
```
var names = new string[] {"John", "Jeff", "Emma", "Steve", "Julie"};
var guidBasedSeed = BitConverter.ToInt32(new Guid().ToByteArray(), 0);
var prng = new Random(guidBasedSeed);
var rn = (int)prng.Next(0, names.Length);
Console.WriteLine(names[rn]);
```
Hint:
> 
> Generate seed from GUID. Guids have 4 × 10−10 chance of collision. Super random. 
> 
> 
> 
Answer:
> 
> At least when you use `Guid.NewGuid()`, whoops! (Sneaky way to make seed always 0). Also pointless (int) for misdirection.
> 
> 
> 
[Answer]
# bash / coreutils
This is taken almost verbatim from a script I wrote for a similar purpose.
```
#!/bin/bash
# Sort names in random order and print the first
printf '%s\n' John Jeff Emma Steve Julie | sort -r | head -1
```
> 
>  Even forgetting to use an upper case R is a mistake I have occasionally made in real life scripts.
> 
> 
> 
[Answer]
# Ruby
```
names = ["John", "Jeff", "Emma", "Steve", "Julie"]
puts names.sort{|x| rand()}.first
```
> 
>  This would work correctly with `sort_by`, but `sort` expects a comparison function that works like `<=>`. rand()'s result will always be positive, so it will always produce equivalent results provided your Ruby implementation's `sort` algorithm is deterministic. My Ruby 1.9.3 always outputs Julie.
> 
> 
> 
[Answer]
# Ruby
```
names = ["John", "Jeff", "Emma", "Steve", "Julie"]
puts names[rand() % 5]
```
> 
>  `rand()` with no arguments produces a random float between 0 and 1. So modulo 5 does nothing, and when slicing into an array with a float argument Ruby just rounds it down, so this always returns John.
> 
> 
> 
[Answer]
# Perl
three `srand`s will make it three times more random!
```
#!perl
use feature 'say';
sub random_person {
    my ($aref_people) = @_;
    srand; srand; srand;
    return $aref_people->[$RANDOM % scalar @$aref_people];
}
my @people = qw/John Jeff Emma Steve Julie/;
my $person = random_person(\@people);
say "$person makes next round of drinks!";
```
explanation
> 
>  there is no $RANDOM in perl, it's an undefined variable. the code will always return the first element from the list - drinks on John :)
> 
> 
> 
edit:
after going through the code, one of the five guys has decided to fix the obvious error, producing the following program:
```
#!perl
use feature 'say';
sub random_person {
    my ($aref_people) = @_;
    return $aref_people->[rand $#$aref_people];
}
my @people = qw/John Jeff Emma Steve Julie/;
my $person = random_person(\@people);
say "$person buys next round of drinks!";
```
can you tell who did it just by looking at the code?
explanation:
> 
>  in Perl, `$#array` returns the index of last element; since arrays are zero-based, given a reference to an array with five elements, `$#$aref_people` will be `4`.  
> 
> `rand` returns a random number greater or equal to zero and less than its parameter, so it will never return `4`, which effectively means Julie will never buy drinks :)
> 
> 
> 
[Answer]
# Python
Everybody knows that you can't trust randomness in such a small sample space; to make it truly random, I've abandoned the outdated method of picking a name from a list, and instead my program will spell out a completely random name. Since most of the names in the office had 4 letters, we'll settle for that.
```
import random
def CHR (n):
    # Just easily convert a number between 0 and 25 into a corresponding letter
    return chr(n+ord('A'))
# Seed the RNG with a large prime number. And multiply it by 2 for good measure.
random.seed (86117*2)
# Now, let's see what COMPLETELY RANDOM name will be spelled out!
totallyRandomName = ''
for i in range(4) :
    totallyRandomName += CHR(int(random.random()*26))
    
print (totallyRandomName)
```
> 
>  Naturally, I did some preparation work to make sure I pick the right seed.
> 
> 
> 
[Answer]
# C
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
char *name[]={"John", "Jeff", "Emma", "Steeve", "Julie"};
int i;
int n=rand()%10000;
int r=3;
for (i=0; i<10000+n; i++) // random number of iteration
    {
    r=(r*r)%10000; // my own PRNG (square and mod)
    }
printf("%s", name[r%5] );
}
```
Sorry, Jeff!
> 
>  After a few iteration r==1 mod 5, because of math. Morality : don't write your own PRNG if you're bad at math. :)
> 
> 
> 
[Answer]
**C++x11**
```
#include <vector>
#include <iostream>
int main () {
  std::srand(time(NULL));
  std::vector<std::string> choice{("jen","moss","roy")};
  std::cout << choice[rand()%choice.size()] << std::endl;
}
```
> 
>  Size of vector is actually 1 due to the parenthesis used in the initializer list. Comma operator will discard all the names and return the last one, hence the buyer is always Roy.
> 
> 
> 
[Answer]
## Scala
I know my users will be skeptical, so I have included a proof that my randomness is truly fair!
```
object DrinkChooser {
  
  def main(args: Array[String]): Unit = {
    proveRandomness()
    val names = List("John","Jeff","Emma","Steve","Julie")
    val buyer = names(randomChoice(names.size))
    println(s"$buyer will buy the drinks this time!")
  }
  
  def proveRandomness(): Unit = {
    val trials = 10000
    val n = 4
    val choices = for (_ <- 1 to 10000) yield randomChoice(n)
    (choices groupBy(identity)).toList.sortBy(_._1) foreach { case (a, x) =>
      println(a + " chosen " + (x.size * 100.0 / trials) + "%")
    }
  }
  
  def randomChoice(n: Int): Int = {
    var x = 1
    for (i <- 1 to 1000) { // don't trust random, add in more randomness!
      x = (x * randomInt(1, n)) % (n + 1)
    }
    x
  }
  
  // random int between min and max inclusive
  def randomInt(min: Int, max: Int) = {
    new scala.util.Random().nextInt(max - min + 1) + min
  }
}
```
One example run:
```
1 chosen 25.31%
2 chosen 24.46%
3 chosen 24.83%
4 chosen 25.4%
John will buy the drinks this time!
```
Unless someone else gets extremely lucky, John will always buy the drinks.
> 
>  The "proof" of randomness relies on the fact that `rand(1, 4) * rand(1, 4) % 5` is still evenly distributed between 1 and 4, inclusive. But `rand(1, 5) * rand(1, 5) % 6` is degenerate. There's the possibility you get a 0, which would then make the final result 0 regardless of the rest of the "randomness".
> 
> 
> 
[Answer]
# Javascript (with [Underscore.js](http://underscorejs.org/))
Since javascript does not have a built in shuffle we'll be using [Underscore.js](http://underscorejs.org/)
```
var people = ['John', 'Jeff', 'Emma', 'Steve', 'Julie'];
_.shuffle(people); // Shuffle the people array
console.log("Next round is on", people[0]);
```
> 
>  [\_.shuffle](http://underscorejs.org/#shuffle) returns the shuffled array, it does not modify in place as [Array.prototype.sort()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), sorry John
> 
> 
> 
[Answer]
## JavaScript
Second try, this one's a little trickier:
```
var getRandomEntry = function(args){
    return args[Math.floor(Math.random() * arguments.length)]; 
}
alert(getRandomEntry(["peter","julie","samantha","eddie","mark"]));
```
> 
>  The `arguments` variable is locally accessible for functions and is an array of all arguments passed in to the function. By using simple naming and passing in an array to the function itself, you can spoof that we're not taking the length of the array, but in fact the length of the arguments list (which is 1). This can be even better executed by using special chars or a font type.
> 
> 
> 
[Answer]
# C++
To be fair we should run many, many trials and pick whomever is selected the most often.
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <map>
static const char *names[] = { "John", "Jeff", "Emma", "Steve", "Julie" };
int main() {
    srand(time(NULL));
    std::map<int, int> counts;
    // run 2^31 trials to ensure we eliminate any biases in rand()
    for (int i = 0; i < (1<<31); i++) {
        counts[rand() % (sizeof(names)/sizeof(*names))]++;
    }
    // pick the winner by whomever has the most random votes
    int winner = 0;
    for (std::map<int, int>::const_iterator iter = counts.begin(); iter != counts.end(); ++iter) {
        if (iter->second > counts[winner]) {
            winner = iter->first;
        }
    }
    printf("%s\n", names[winner % (sizeof(names)/sizeof(*names))]);
}
```
> 
>  What's the value of `1<<31`? Sorry, John.
> 
> 
> 
[Answer]
## T-SQL (2008+)
```
SELECT TOP 1 name
FROM
 (VALUES('John'),('Jeff'),('Emma'),('Steve'),('Julie')) tbl(name)
ORDER BY RAND()
```
Explanation:
> 
>  In MS SQL Server, `RAND()` only evaluates once per execution. Every name always gets assigned the same number, leaving the original ordering. John is first. Sucks for John. 
> 
> 
> 
Suggested improvement:
> 
> T-SQL can produce decent quality, per-row random numbers with `RAND(CHECKSUM(NEWID()))`.
> 
> 
> 
[Answer]
# Lua
```
buyer={'John', 'Jeff', 'Emma', 'Steve', 'Julie'}
   -- use clock to set random seed
math.randomseed(os.clock())
   -- pick a random number between 1 and 5
i=math.random(5)
io.write("Today's buyer is ",buyer[i],".\n")
```
> 
>  `os.clock()` is for timing purposes, `os.time()` is what ought to be used with `math.randomseed` for good RNG. Sadly, Julie always buys (at least on my computer).
> 
> 
> 
[Answer]
# Idiomatic C++11
When drinks are involved, it's especially important to be up to date with the latest standards and coding styles; this is a great example of a highly efficient and idiom-compliant C++11 name picker.
It is seeded from the system clock, and outputs the seed along with the name for verification each time.
```
#include <vector>
#include <chrono>
#include <random>
#include <iostream>
auto main()->int {
  std::vector<std::string> names;           // storage for the names
  names.reserve(5);                         // always reserve ahead, for top performance
  names.emplace_back("John");               // emplace instead of push to avoid copies
  names.emplace_back("Jeff");
  names.emplace_back("Emma");
  names.emplace_back("Steve");
  names.emplace_back("Julie");
  std::mt19937_64 engine;                   // make sure we use a high quality RNG engine
  auto seed((engine, std::chrono::system_clock::now().time_since_epoch().count()));  // seed from clock
  std::uniform_int_distribution<unsigned> dist(0, names.size() - 1);     // distribute linearly
  auto number(dist(engine));                // pick a number corresponding to a name
  std::string name(names.at(number));       // look up the name by number
  std::cout << "Seed: " << seed << ", name: " << name << std::endl;  // output the name & seed
  return EXIT_SUCCESS;                      // don't forget to exit politely
}
```
Try this live: <http://ideone.com/KOet5H>
> 
> Ok so this actually is pretty good code overall; there are a lot of red herrings to make you look too closely at the code to notice the obvious - that the RNG is never actually seeded :) In this case `seed` is just an integer, and while it looks like `engine` is passed as a parameter to a seeding function, it's actually just ignored. The seed variable really is set from the clock, so it can be output at the end along with the name to add insult to injury, but it'll still always be Steve who buys the drinks.
> 
> 
> 
[Answer]
# JavaScript
```
console.log(["Jeff", "Emma", "Steve", "Julie"][Math.floor(Math.random(5))]);
```
> 
>  Well, sorry, [`Math.random`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) doesn't take a parameter, and will always return a number from [0, 1). Still, it is a happy [variadic function](https://en.wikipedia.org/wiki/Variadic_function) and doesn't complain about arguments!
> 
> 
> 
[Answer]
# Python
```
names=["John", "Jeff", "Emma", "Steve", "Julie"]
import random # Import random module
random.seed(str(random)) # Choose strictly random seed
print(random.choice(names)) # Print random choice
```
> 
>  str(random) gives a constant string; not a random value
> 
> 
> 
[Answer]
# Perl
Emma had better not forget her purse! Runs under `strict` and `warnings`.
```
use strict;
use warnings;
# Use a hash to store names since they're more extendible
my %people;
$people{$_}++ for qw/John Jeff Emma Steve Julie/;
print +(@_=%people)[rand@_];  # 'cos (keys %people)[rand( keys %people )]
                              # is just too long-winded.
```
> 
>  Explanation [here](https://stackoverflow.com/q/8554060/133939).
> 
> 
> 
[Answer]
JavaScript
```
function getDrinksBuyer(){ 
    var people = ["Jeff", "Emma", "Steve", "Julie"];
    var rand = Math.random(0,4)|0;
    return people[rand];
}
```
> 
>  The `|0` results in 0 all the time but looks like it's doing some other rounding.
> 
> 
> 
[Answer]
# J
```
;(?.5) { 'John'; 'Jeff'; 'Emma'; 'Steve'; 'Julie'
```
Poor Julie...
Trivia: this might've been the cleanest J I've ever written...
> 
> This code is actually correct, except for one thing. `?.` is the uniform rng: `?.5` will always return 4. `?5` would've been correct.
> 
> 
> 
]