text:
Random script that isn't actually random
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.

Where should the output go? :)

Erm, I'd say print to console if your language has one, if not echo/print it.

http://xkcd.com/221/

@AstroCB one of my favourites. Right behind bobby tables.

It seems like it would be sneakier if it was random, except for never picking one person.

@AstroCB that's what I thought of immediately... Still trying to find a language that implements that. It'd take the cake :P

@AstroCB this one is also fantastic: http://dilbert.com/strips/comic/2001-10-25/

@AstroCB apparently, some large company cough - sony - cough did something similar

ObRef: The original random-not-random story of Mel, the Real Programmer.

I 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.

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.

+1 for performance -- much faster than rolling a physical die! ;)

I'm thinking about optimising it further, perhaps with SIMD or GPGPU, just to get a little more performance. ;-)

Absolutely real live applicable. No one would ever even question that it was an accident in the slightest.

Is it just me or is this one too obvious to spot?

@PaulR Congratulations, you're the highest voted answer after a week :).

@AlvinWong I didn't notice it immediately. Then again, I don't use C regularily, or any other language that descended from BCPL.

Damn! I knew about break statements (in C++) but still didn't realise they were missing. +1

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.

You got to love PHP - and even better, it will sometimes rarely choose someone else. So if you're lucky it will just seem a little biased at first

+1000 for "...alerting the programmer to a potential error is considered a deadly sin in PHP."

obligatory phpsadness

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

That's diabolical!

Feels like photographing a dice which has not yet stopped moving.

@Vi. That is a nice analogy. Luckily the use of MVars guarantee that the picture will not be blurry. :)

@monocell Well, technically, even a photo of a moving object can be clear.

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.

\o/  Mean!!! Really mean!!! $SECONDS ftw!  \o/

What happens if you source this, instead of just executing it? Will the shebang still trigger a new shell or something?

@jpmc26: if you execute it with source then it's exactly the same as if you'd typed the commands on the commandline yourself; #!/bin/bash is a comment so it's ignored.  This is true of any script.

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.

Even if OrderBy hypothetically modified the object, would that call actually sort the list randomly?  As someone unfamiliar with .NET, my first guess was that since rng.Next() is only called once, the array would be sorted by a constant, resulting in no change (or a change that depends only on the sorting algorithm).

@Brilliand The argument passed to OrderBy isn't a static value, it's executed every time an element is sorted, and in this case returns random values without comparing any values. It would actually work correctly if the line was names = names.OrderBy(name => rng.Next());

The => indicates that this is a C# lambda expression (closure).

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.

Q
show rand `John`Jeff`Emma`Steve`Julie;
exit 0;

 Q always initialises its random number seed with the same value.

so basically it's not random at all

@SamCreamer The purpose of the question is very much to make the output non-random. But this does look random so it definitely fits the bill

Sorry, I meant Q's random numbers aren't that random, this question does certainly meet the criteria. Didn't mean to come across that way!

Yeah, so you have to find your own way to generate a random seed every time you want to use rand? Sounds... useful.

Can set the random seed manually very easily...start the interpreter with the -S 1234 option or do \S 1234 from the interpreter

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

So in C(++) terms, there is an implicit conversion from list to scalar happening because when indexing, a scalar is expected?

@iFreilicht Correct. In Perl, expressions can be evaluated as a list or as a scalar, depending on where they appear. As a result, the same expression might mean different things, depending on context. A list variable (i.e. a variable with the @ prefix), in "list context," is interpreted as all its elements, but in "scalar context," is a scalar equal to the total number of elements in the list. Hence, inside the string, the list variable has list context and gets interpolated, and we get Person X is buying. But as an array index, it gets scalar context, and gets interpreted as 1.

Problem with this is that when a Perl programmer sees my @index = ..., he immediately wonders "WTF?!".

@derobert, Why would you wonder? You see code like that quite often... my @letters = 'a' .. 'z'; my @squares = map $_**2, 1..20; my @sorted = sort { lc $a cmp lc $b } @words; etc.

@Matthias because the line is to pick and store a single value, and instead of a scalar it's being stored in an array.

@derobert, OK I give you that. Although I still do not feel unfamiliar with that line (and I am working with perl quite often).

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 returns the value of its right operand.
 It's also very easy to miss. I've missed it before in real code.

This is delightful. Finally, a use for that terrible, terrible operator.

The comma in that context is technically an operator, rather than a separator. http://www.ecma-international.org/ecma-262/5.1/#sec-11.14 And it is terrible. Unless you want your code to be hard to read. As you do here. So, kudos.

@Cory Yes, I agree - although I use it all the time for Code Golf with function expressions (e.g. (a,b)=>(a=b[0],b)). I've clarified my 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.

It didn't withstand my quick glance. ;)

@m.buettner damn you ^^ Lets see how it is about other members :P

Would be more underhanded if there were something to suggest that the RNG knew you wanted a value up to 5.

@TimS. like that? :P

+1, Much better - I know what you're really doing, but it could fool someone not too familiar with the API.

I don't know about this. If you are going to specify a seed, why not just use the proper way of getting a "random" int: var random = new Random(5); var id = random.NextInt(5);

@clcto In my opinion, including it twice is more likely to make someone do a double take, ask why, and see the problem. Including it once, and then including unnecessary code afterward, gives a bit of redirection/underhandedness. Bonus: if someone fixes one of the bugs, another exists.

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.

The other way I might do it, is to get AddRange muddled with Concat when adding names to a List<string>. Did occur to me to have a Hashset with a sneaky IEqualityComparer, but it would be just far too unusual. In my credit there weren't many (if any) seed based answers when I posted this.

I'll guess you had the same idea as I did, but you were a bit faster and made it a bit harder to see. +1!

Seeding the random number generator is an obvious trick, but you've hidden it brilliantly here. Lovely work.

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.

could you give a better explanation? Your current one is really short and not helpful to someone who isn't really familiar with bash.

-r specifies reverse (lexicographic) sort, so Steve will always be picked. It could be seen as an innocent typo of -R for random sort

That's a good reminder not to trust comments, but to carefully read the code!

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.

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.

Perl
three srands 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 :)

$RANDOM is a real feature in bash, ksh and zsh (but not in perl).

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.

Seeding the random number generate with a constant is just too obvious..

@BrendanLong It would definitely raise eyebrows. People would want to test it to make sure its random. And when it's not, guess who's buying drinks.

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.  :)

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.

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".

Javascript (with Underscore.js)
Since javascript does not have a built in shuffle we'll be using Underscore.js
var people = ['John', 'Jeff', 'Emma', 'Steve', 'Julie'];
_.shuffle(people); // Shuffle the people array
console.log("Next round is on", people[0]);

 _.shuffle returns the shuffled array, it does not modify in place as Array.prototype.sort(), sorry John

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.

This wasn't the hardest to spot. Anyone who has constructed an arbitrary N-ary function in JavaScript knows about the arguments variable.

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.

The answer to your spoiler question is UB. I am undecided if that makes is better or worse.

@nwp Well, sure, but it holds anywhere that int is 32-bit 2's complement, which seems to be the case even on 64-bit (with gcc). I haven't tested on Clang, though.

No it doesn't hold anywhere where an int is 32-but 2's complement. The value of 1 << 31 is undefined. You are lucky though, undefined behavior makes the compiler chose whatever it feels like and since it is made for speed it will just decide to do nothing, which happens to be what you want.

@nwp 1<<31 == 0x80000000 no matter what, by the very definition of <<, and on 32-bit 2's complement, that's INT_MIN. Are you maybe thinking about 1<<32 which may or may not == 0? (Because on x86, 1<<32 usually evaluates to 1...)

@nwp It's actually implementation-defined. Now if we were talking about C, then it would be undefined.

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).

math.random() with no arguments also returns a number in the range [0,1). -1 for not catching that.

@mniip: Truly deserved too! I've fixed it now.

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())).

I think ORDER BY NEWID() will suffice (no need to CHECKSUM)

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.

It kills me that it doesn't use an initializer list for the names. At the very least, you've definitely succeeded in providing code that just feels over- engineered. I can't tell whether it's because of the "compliance" or all of the noise comments :P

JavaScript
console.log(["Jeff", "Emma", "Steve", "Julie"][Math.floor(Math.random(5))]);

 Well, sorry, Math.random doesn't take a parameter, and will always return a number from [0, 1). Still, it is a happy variadic function and doesn't complain about arguments!

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

A somewhat-irrelevant note: if you're using Python 3.2 or later, the second argument to random.seed() must be 2 (the default). If you pass version=1, the hash() of the string will be used as a seed instead of the entire string, and because Python randomly seeds strings' hash values starting in 3.2, you'll get an actually-random name.

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.

Perl 5.18 changed this a bit, by introducing hash key randomization (to avoid hash collision complexity attacks).

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.

I like it. Though I would do parseInt(Math.random(0, 4)) and maybe add comments like - Math.random returns a double, so convert it to an integer first

The trick is actually that Math.random cares nothing for our meager parameters. It chooses numbers its own way. the |0 is correctly rounding the unexpected result, and so is not a source of any trickery.

|0 is very obvious to some (all of us most likely), but I would bet there's a lot who have no idea what it does. That's the group I was relying on tricking.

@Matt I mean that |0, if you know what it does, looks like it's rounding down, and it is rounding down, so it's not a deception. (And if someone has no idea what |0 does, then there's no use for deceptive code; you can just tell them whatever you want them to believe.) Instead, the unexpected behavior in your answer is based on the fact that Math.random(0,4) is functionally identical to Math.random(), because Math.random doesn't use parameters.

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.

Java
Shh, don't tell anyone. Secretly call the second method in your code, then call the first method.
public String randomPerson() {
    String people[] = new String[]
    {"John", "Jeff", "Emma", "Steve", "Julie"};
    return people[Math.random()];
}

@SuppressWarnings("serial")
private void setUpRandomness() {
    try {
        Field field = Math.class.getDeclaredField("randomNumberGenerator");
        field.setAccessible(true);
        field.set(null, new Random() {
            @Override
            public double nextDouble() {
                return 4; // chosen by fair dice roll.
            }             // guaranteed to be random.
        });               // Proof: http://xkcd.com/221/
    }
    catch (final SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e)
    { /* Ignore */ }
}

Cudos on the xkcd reference :)

This "random" number generator is not funny. Plus, Anubian Noob did this about 16 hours before you did.

@KyleKanos I would argue that his script is not at all random while mine involves Math.random(), a Java standard method for getting a random double.

I am by no means even a capable Java programmer, but it seems to me that you are overriding Java's standard method of getting a random double and replacing it with a very tired joke.

Javascript
In order to make things as fair as possible, we'll simply outsource random-number generation to the random.org API. As you can see from this URL, the API can generate a random number between 0 and 4, inclusive, using extremely powerful entropy sources like atmospheric noise -- vastly superior to whatever your office laptop uses to generate /dev/random.
var xhr = new XMLHttpRequest();
xhr.open("GET",
    "http://www.random.org/integers/?num=1&min=0&max=4&col=1&base=10&format=plain&rnd=new");
xhr.send();

// convert string response to number
var index = +xhr.responseText;
var name = ["John", "Jeff", "Emma", "Steve", "Julie"][index];
alert(name);

 There is a misuse of asynchronous Ajax code (a perennial Stack Overflow "favorite"). xhr.responseText is by default the empty string, and is not populated until the load event fires, so +"" is coerced to 0, leaving poor John to get drinks for everyone.

I had thought about doing exactly this, since it's a genuine common error for new programmers, and going to random.org is a perfect excuse. Might I suggest replacing +xhr.responseText with xhr.responseText|0 so that it looks even more like a reliable integer coercion?

AWK
BEGIN {
    srand(n=split("John Jeff Emma Steve Julie.",A))
    print A[int(rand()*n+1)]
}

Sorry, Steve!!!  :-P

 Feeding srand() with a constant shall reproduce the same sequence of rand() values over and over again. On my system gawk and mawk selected Steve but this may not be globally immutable...

But now for something completely different with really seeding srand():
BEGIN {
    srand()
    split("John Jeff Emma Steve Julie.",A)
    print A[int(rand()+1)]
}

Sorry, John!

 srand() really seeds the rand() as expected and rand()+1 looks like correctly taking care of the names are stored in A[1] and following indices but because rand() always is smaller than 1, int(rand()+1) always will be 1.

Kona
> buyer:("john";"jeff";"emma";"steve";"julie")
> *buyer[4 _draw 1]
"john"

 x _draw y returns x number of values between 0 and y-1. To the untrained eye, this dyad appears to be pulling 1 value in the range 0 to 4, rather than 4 values in the range 0. Thus, buyer[4 _draw 1] is a vector with 4 elements that are all "john" (who sadly, again, is buying for everyone); the leading * picks the first element of the vector.

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.

This one is not portable. Here with OpenBSD, sed 's/ /\n/' changes the first space to a literal n, because \n is only a newline in regular expressions, not in replacements. (I wonder if I can exploit this?) Also, there is no shuf command. So $output is always empty and this script enters an infinite loop, which is proof that the [ -n "$output" ] check is an essential part of the script.

@kernigh Works fine on Ubuntu 14.04, GNU bash 4.3.11, GNU coreutils 8.21, GNU sed 4.2.2. shuf is in coreutils on my system. You could use sort -R instead of shuf, but it isn't quite the same (see manpages for details).

JavaScript
This answer is obvious but still, im giving a shot at it :
var arrName = ["Jeff", "Emma", "Steve", "Julie"];

randName.call.apply(getName, arrName)

function randName(){
    var names = Array.prototype.slice.call(arguments)

    this.call(names[Math.floor(Math.random() * names.length)]);
}

function getName(){
    alert(this)
}

Poor Jeff, he will always have to buy the drinks.

 The trick here is in the call.apply(). The function being called is not the randName, but directly getName where this this will be equal to the first cell in the array.

Very odd code with a good idea :-) But randName on itself should be working, and use its arguments instead of the global arrName variable.

@Bergi what a brain fart, even prepared that array! Thank anyway

Java
In college, I was told that this would normally distributed.
public static void main(String[] args)
{
    String names = {"John", "Jeff", "Emma", "Steve", "Julie"};
    Random r = new Random();
    double res = Math.abs(r.nextGaussian()) * 0.5;
    int resInt = Math.min(names.length() - 1, (int) res);
    System.out.println(names[resInt]);
}

 The nextGuassian() method picks a number from a pseudo normal distribution with mean 0 and standard deviation 1. So, basically the chances that it's not going to be John are 4.56%. Moreover, the chances it's going to be John or Jeff is approximately 100%.

So will it always choose John OR Jeff not only one or did I misunderstand?

Yes, it's going to be John or Jeff, it will be 95.44% of the time John and 4.56% of the time is it going to be Jeff.

Why are you taking the minimum? This looks suspicious.

Because mathematically, a Gaussian random number kan be anything, even 1000000. So that's not what we want.

I agree that it looks too suspicious. It can be anything, but you can't let people know that, and it will practically never by more than 4. If your code fails once every 20,000 runs, that's fine. So if you remove the min you should be okay.

C++
The idea is pretty simple: we generate n random numbers for each person (their score), add them together to get their total, and the person with the lowest total score has to buy the drinks.  To be scrupulously fair, we generate the random numbers in n rounds, with each person taking turns to be the first to roll the dice.
#include <random>
#include <algorithm>
#include <iostream>

int main() {
    const char* names[] = {"John", "Jeff", "Emma", "Steve", "Julie"};
    constexpr unsigned int NumNames = std::extent<decltype(names)>::value;
    unsigned int total[NumNames] = {};

    std::random_device rd;  // Seed with a real random value
    std::default_random_engine e1(rd());
    for (unsigned int i = 0; i != NumNames; ++i) {
        unsigned int score[NumNames];
        std::generate(std::begin(score), std::end(score), e1);
        for (unsigned int j = 0; j != NumNames; ++j)
            total[(i + j) % NumNames] += score[j];  // Eliminate any bias
    }

    auto loser = names[std::distance(std::begin(total),
            std::min_element(std::begin(total), std::end(total)))];
    std::cout << loser << " buys the drinks!\n";
}

Explanation:

 Unfortunately, std::generate takes its functor argument by value, not by reference, so modification to the internal state of the engine only affects the copy of e1 inside std::generate.  That means that each time round the loop score is filled with the same sequence of values, so after the loop everyone has exactly the same total.  When faced with a tie, std::min_element returns the first element with the minimum value, so John always buys the drinks!

This has resulted in real-world bugs: https://groups.google.com/a/isocpp.org/forum/#!topic/std-discussion/nsGPpmEVOns/overview

JavaScript
Two different flavors here.
var totallyFairAndRandomPersonPicker = function () {
    var people = ['John','Jeff','Emma','Steve','Julie'];
    var drawnLot = [0, 1, 2, 3, 4][Math.random()*people .length]|0;
    return people[drawnLot];
};

totallyFairAndRandomPersonPicker ();

 I think I accidentally put a ] in the wrong place! Sorry, John!

var chooseOne = function (list) {
    // We use double the random calls for double the randomness!
    var  i = Math.random()*Math.random()*list.length|0;
    return list[i];
};

chooseOne(['John','Jeff','Emma','Steve','Julie']);

 It's the answer you need, not the answer you want. Everybody has a chance of being selected, but it's still massively unfair to John. I apologize for any dismay it causes Julie to occasionally chip in.

Python
from random import random
names = ['John', 'Jeff', 'Emma', 'Steve', 'Julie']
index = int(random()) * len(names) # Get a random number in range 0-4 (length of the list)
print names[index]

 random.random() actually gives a value between 0.0-1.0, excluding 1.

C#
Okay, one more.
I don't want to make anyone think there's any trickery here with regard to how random my random numbers are.
So I've got to great efforts to avoid passing anything to Random() or Random.Next(). It's a bit slow, but worth it for the extra integrity.
public class RandomDrinks
{
    int buyerIndex;
    string[] names = new string[] { "John", "Jeff", "Emma", "Steve", "Julie" };
    Random random = new Random();

    public string PrintBuyer()
    {
        //Get Random until there is a valid index
        do
        {
            buyerIndex = GiveMeRandoms();
        } while (!IsValueIsInRange(out buyerIndex));

        var text = names[buyerIndex];
        return String.Format("{0} is buying", text);
    }

    public int GiveMeRandoms()
    {
        return random.Next();
    }

    bool IsValueIsInRange(out int index)
    {
        int chosen = buyerIndex;
        index = names.Length - 1;
        return !(chosen > index);
    }

}

 is the effect of the out too obvious?

Ruby
names = ['John', 'Jeff', 'Emma', 'Steve', 'Julie']
puts names[Time.new.sec % names.length]

It's not random if you run it at a right moment... ;)

So basically it's not random if you run it in exactly 5 second intervals?

Sure, for example, if you need to get Jeff all the time, just run it at any of these seconds: 1, 6, 11, 16...

JavaScript
function pick(names) {
  var r = Math.floor(Math.random * names.length);
  for (var i = 0; i < names.length; i++) { if (i >= r) { break; } }
  return names[i-1];
}
alert(pick(["John", "Jeff", "Emma", "Steve", "Julie"]));

The gods have spoken, Julie. Don't fight destiny.

 Like all fearlessly awesome languages, JavaScript not only forgoes an exception and returns a value when you "invoke" a function without parenthesis; but also when you multiply by something that is not a number.

This is fun, but a lot of languages fall sin to this, as Math.random returns the function itself, and it actually does let you know that the result of the multiplication doesn't make sense by returning NaN. The for loop looks suspect, so maybe you should consider doing this
var ix =(Math.random * names.length)|0; This is pretty well known paradigm in javascript to turn a double into a number, and also turns your NaN into zero :)

C++
#include <string>
#include <algorithm>
#include <iostream>

int main(){
    using namespace std;
    const char *names[] = { "John", "Jeff", "Emma", "Steve", "Julie"};
    random_shuffle(begin(names), end(names));
    cout << names[0] << '\n';
}

This one fools even me. Why does it print out Julie every time?

missing srand, glorious c++ ;)

Atari BASIC
It generates a random number R, and then READs the appropriate number of names from the DATA statement until it reaches the buyer.
10 DIM NAME$(10)
20 R=RND(5)
30 FOR I=0 TO R
40 READ NAME$
50 NEXT I
60 PRINT NAME$
70 END
99 DATA John,Jeff,Emma,Steve,Julie

 RND(x) always returns a floating-point number between 0 and 1; the parameter is ignored (but required because the BASIC parser can't deal with zero-arg functions).  So, the loop always executes exactly once, and John is the buyer.  The correct way to generate a random number between 0 and 4 is R=INT(5*RND(0)).

Sinclair BASIC
 10 LET r=INT RND*8
 20 LET n$=""
 30 IF r=0 THEN LET n$="John"
 40 IF r=1 THEN LET n$="Jeff"
 50 IF r=2 THEN LET n$="Jmma"
 60 IF r=3 THEN LET n$="Steve"
 70 IF r=4 THEN LET n$="Julie"
 80 PRINT "The person buying the drinks today is..."
 90 FOR d=0 TO 16 : REM Drum roll...
100 OUT 254,31
110 PAUSE 6-(d/4)
120 OUT 245,15
130 PAUSE 6-(d/4)
140 NEXT d
150 PRINT n$;"!"

Explanation:

 The INT function only evaluates the item immediately after it so it performs (INT RND)*8 rather than INT (RND*8) so John will always buy the drinks.

"IF r=0 THEN" for all names is what you really intended? It looks like the last "IF" will set the name... so Julie will have to pay...

F#
This solution is very flexible -- it allows you to pick people in batches, so you won't have to run it again for a little while. Supply the number as the first argument to the program:
[<EntryPoint>]
let main argv =
  let getRandom (min, max) = (new System.Random()).Next (min, max)
  let pickBuyers people times = List.init times (fun _ -> List.nth people (getRandom (0, List.length people)))
  printfn "%A" (pickBuyers ["John"; "Jeff"; "Emma"; "Steve"; "Julie"] <| System.Int32.Parse argv.[0])
  0

! Exploits a common mistake when learning random numbers, so you probably caught this if you know the basics of System.Random. Instantiating Random() uses the time as a seed, and calling it in quick succession will cause it to seed exactly the same over and over until the time changes.
However (as pointed out by @kernigh), the more elements you generate at once, the more likely it is to roll over to the next millisecond before it's finished. This will cause the next RNGs to get seeded with a different number, thus changing the resulting number. This will happen every millisecond(?).

The output looks suspicious: http://ideone.com/AHZVz5

I'm aware of that -- the more items you generate at once, the more likely it will be that it rolls over the millisecond, thus seeding the RNG differently. It's in the nature of this method, unfortunately.

C#
using System;
using ExtensionMethods;

namespace RandomBeerDrinker
{
    class Program
    {
        static void Main()
        {
            var generator = new Random();
            int person = generator.NextValue();
            var names = new[] {"John", "Jeff", "Emma", "Steve", "Julie"};
            Console.WriteLine(names[person]);
            Console.ReadLine();
        }
    }
}

 Everyone's using extension methods nowadays, so it's not suspicious to have a class called ExtensionMethods, is it?
 using System;
 namespace ExtensionMethods
    {
        public static class ExtensionMethods
        {
            public static int NextValue(this Random x)
            {
                return x.Next()%4; // Quite random, but excludes Julie
            }
        }
    }

In order to be reusable, it is best to use generic functions with single purposes only, to assemble the complete program.

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <string>

// generic function to randomize elements of any passed container
template<class C>
void randomize_container( C elements )
{
    std::random_shuffle(elements.begin(), elements.end() );
}

std::string pick_one( std::vector<std::string> names )
{
    randomize_container( names );
    return names[0];
}

int main(int argc, const char *argv[])
{
    // Do not forget to seed the rng, but only once!
    srand(time(nullptr));

    auto ret = pick_one( { "John", "Jeff", "Emma", "Steve", "Julie" } );
    std::cout << ret << " has to pay the next round\n";
}

 It should just simply have been C& instead of C to pass the container per reference.

Saw this one immediately, but still laughed because it would be easy to miss, especially if your coworkers aren't familiar with C or C++.

@BrendanLong: It is such a common mistake as you can see from the numerous questions on SO, that could be real world code ;)

Fortran 95
character(LEN=5), dimension(5) :: name=(/"John ","Jeff ","Emma ","Steve","Julie"/)
real :: ReallyReallyReallyRandomNumber = 0.

call RANDOM_NUMBER(ReallyReallyReallyRamdomNumber)

do i=1,5
    if (myReallyReallyRandomNumber <= real(i)/5.) then
        write(*,"(A,A)") "Selected name is: ", name(i)
        exit
    endif
enddo

end

I am assuming that your compiler generates a random seed which is different for every run. If not (which is the case of gfortran on my Windows machine), then you may like to add some code that generates a random seed before every run by using, for instance, the system's clock (see this link)

 The variable that receives the random value is named ReallyReallyReallyRamdomNumber while the variable that is used in the loop is named ReallyReallyReallyRandomNumber (note that the first one is misspelled). This last variable is given an "initial" value of 0., which never changes, thus being the same regardless of the RANDOM_NUMBER subroutine. So, unfortunately for John, he will be selected every single time on every single machine.

Obviously doing the safe thing of opening with implicit none would defeat this. I think this might be the first code to abuse variable names rather than the RNG seed. +1

@KyleKanos Thanks! Indeed this sort of code shows one more reason why implciit none should ALWAYS be present on a Fortran program.

C
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char *names[] = {"John", "Jeff", "Emma", "Steve", "Julie"};
    printf("%s\n", names[random() % 5]);
    return 0;
}

Always outputs Steve on my computer. (It might vary by computer, but will likely be consistent on one machine.)

 This works because random() is usually a pseudo-random number generator; you must seed it with some randomness, or it will always give the same numbers in the same order.

Python
#!/usr/bin/env python3

import random

# Create list of names.
names = ['John', 'Jeff', 'Emma', 'Steve', 'Julie']

# Define start and end of range, just in case we want to change it in the future.
start = names.index(names[-1]) - len(names)
end = len(names)

# Randomly choose name from list, using range specified above.
print(random.choice(names[start:end]))

 names[start:end] should be the same as names, but allows us to easily change the range in the future. However, instead of starting at 0, as we should, we sneakily start at -1. So, we actually pass names[-1:5] to random.choice, rather than names[0:5]. Thus, we always choose the last name in the list.

Perl
While playing code golf, I tested this simple shuffle algorithm.  It always picks Steve.
use strict;
use warnings;

# Randomness test for 0.5 - rand:
# perl -e 'for(1..10000){$x=0.5 - rand;$x<0&&$n++;$x>0&&$p++}' \
#      -e 'print "negative: $n, positive: $p\n"'

# Shuffle from alphabetical order to random order.
my @shuffled = sort { 0.5 - rand } qw(Emma Jeff John Julie Steve);
print "$shuffled[-1]\n";

 Perl expects the sort block to return an integer, not a float. My block { 0.5 - rand } returns a random float from -0.5 exclusive to 0.5 inclusive, but Perl truncates this float toward 0 before checking its sign. Every float from -0.5 to 0.5 becomes integer 0, so all names compare equal and stay in alphabetical order.

If we fix the bug, this program would perform a "Microsoft shuffle", which is not a fair shuffle. Microsoft used 0.5 - Math.random() in JavaScript for a comparison function. That shuffle had much bias, because 0.5 - Math.random() does not provide a consistent ordering.
Find more Perl answers by Zaid, chinese perl goth, Allen G.

TI-BASIC
No computer handy? This works on all TI-83/84/+/SE calculators.
PROGRAM:RANDOM
:"NEW ARRAY NAME:"
:"JOHN"
:"JEFF"
:"EMMA"
:"STEVE"
:"JULIE"
:Disp "NAMES[floor(rand*5)]"
:Disp "NAME: ",Ans

 The names are successively set into Ans (so JULIE would be the contents of Ans). Then, the NAMES[floor(rand*5)] is piped away as a useless string, and the last line looks line it is pulling one of the names from the array NAME (which doesn't exist, by the way). Instead, it will always display JULIE. The order of the names can be switched around to provide a different victim on demand.

JAVA
public class RandomBuyer{
    static String[] names = {"John", "Jeff", "Emma", "Steeve", "Julie"};

    public static void main(String[] args){
        String buyer = names[0]; //Initialize buyer
        setRandomBuyer(buyer);   //Set buyer to random
        System.out.println(buyer);
    }
    static void setRandomBuyer(String buyer){
        int random = new java.util.Random().nextInt(5);
        buyer = names[random];
    }
}

Explanation

 Why this doesn't work!

C#
private void randomizer()
    {
        string[] allName = {"John", "Jeff", "Emma", "Steve", "Julie"};
        Random getRandomNumber = new Random(0);
        Console.WriteLine(allName[getRandomNumber.Next(0,4)]);
    }

 Since I'm making a random with the seed of zero, the result will always be the same, in this special case it would be Emma.

C++
#include<iostream>
#include<climits>
#include<cstdlib>
#include<cmath>

using namespace std;

const string names[]={ "John", "Jeff", "Emma", "Steve", "Julie" };

int main(){
    srand(time(NULL));
    // Generate a random real number
    double r=(double)rand()/(RAND_MAX+1.);

    // Convert it back into an integer
    unsigned long long x=round(r * (ULLONG_MAX+1.));

    // Simply use the remainder is a bit waste. Add up the digits in base 5 instead
    while(x >= 5)
        x=x/5 + x%5;

    // Print the answer
    cout<<names[x]<<endl;
    return 0;
}

Assume RAND_MAX is 2147483647. This program almost always prints Julie, with chances to print John when r is generated exactly zero.
Firstly, the real things you get in x is r*2^33. Then the while loop in fact computes something like x mod 4. And 4 is a divisor of 2^33. It is not the correct way adding up all digits, either.

Ozone
(s1v1(1)n1n1s2v21v21s3v3(<+2n2v12+1n1v21v03>)v03)

The trick is in "+2n2".

This appears to be written in a language which doesn't support the generation of random numbers. How is it supposed to fool anyone?

Maybe you could explain what the code actually did?

Java
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
public class ExampleCode
{
    public static void main( String A[] )
    {
        String[] P = "John Jeff Emma Steve Julie".split( " " );
        P = new HashSet<String>(Arrays.asList( P )).toArray(P);//this should change order of names to random
        Random R = new SecureRandom();//let's use good random number generator
        int O = R.nextInt( P.length );//select random number O
        System.out.println(P[0]);//Show the results
    }
}

Explanation

 The line that changes order to "random" changes oreder, but not randomly. Variable with random number is called 'O' (uppercase 'o'), but when getting value from array '0' (result of 1-1) is used, which looks simillar to uppercase 'o'.

http://meta.codegolf.stackexchange.com/a/1657/20356

Simple solution using JavaScript
var randArrElement = function(arr){
   return arr[Math.ceil(Math.random()*(arr.length-1))];
   //arr[arr.length] is undefined because arrays are 0 indexed, so we subtract 1.
}
randArrElement(["John", "Jeff", "Emma", "Steve", "Julie"]);

First 10 results:
Steve, Steve, Jeff, Steve, Julie, Jeff, Emma, Emma, Steve, Julie
Expanation:

 Because I round using ciel, the only way that John could get chosen is if Math.random()*(arr.length-1) is exactly equal to 0.  Even if it is 0.0000001, ceil will round up to 1.  So John never gets chosen.

This is the wrong way around. You always exclude one instead of always picking that person. But I like the variant enough not to downvote :P

You know, Math.random can return exactly 0.

@ppperry but it almost surely don't.

PHP with microtime for extra randomisation
$names = array('John', 'Jeff', 'Emma', 'Steve', 'Julie');
$choosenPerson = false;
while($choosenPerson === false){
    // Use microtime for a very random value:
    $uid= substr(microtime(true), 0, 1);
    if( isset($names[$uid]) ){ $choosenPerson = $names[$uid]; }
}

 Im going for the microtime misconception. Microtime suggests that we have a very random factor, but im taking the first character which is 1. So for the upcomming years, Jeff will loose a lot of money. After that it'll be Emma :)

Python 2
import random
names = ["John, Jeff, Emma, Steve, Julie"]
print random.choice(names)[:3]

Surprised nobody did something like this before.

 "John, Jeff, Emma, Steve, Julie" is one string. Super obvious but whatevs

This doesn't print John, it prints Joh

Python
def iterate(names):
    for name in names:
        yield lambda:name
import random
print random.choice(list(iterate("John Jeff Emma Steve Julie".split())))()

Sorry, Julie!

The name variable int the iterate function is the same one as in the lambdas, so every lambda evaluates the the last name, Julie.

BASH / Coreutils
Quite a beginner at CG, but worth a shot:
RANDOM=$$;
a=$RANDOM
b=9
c=`expr $a % $b `
echo $c

 $$ is the PID of the running shell, so the number should be always the same

What happens when you restart the shell?

Another number is printed, but always the same for that session

This does not work because I saved these commands in a script, and bash pick-someone-b.bash uses a different PID each time.

Sorry... while doing the &&->$$$$ change the preview of the hidden text fooled me and showed only 2 $s... now there are 4 of then... can you check what happens in your browser with the preview of $$ while editing? If it is not a local browser problem, maybe StackExchange should get a hint about this... (Plus Megawink vom Niederrhein!)

Maybe it went wrong because I did it on the phone. Now it seems to work. Grüße an den Niederrhein ;)

JavaScript:
function ActuallyNotRandom() {
    this.names = ["John", "Jeff", "Emma", "Steve", "Julie"];

    this.choose = function()
    {
        return this.names[Math.random(this.names.length) * 0];
    }

    return this.choose();
}

console.log("Random person: " + ActuallyNotRandom());

Pretty straightforward, takes a list of names, makes a random number between 0 and the number of names in the list, and then multiplies it by 0 to always return 0. Will therefore actually always return the first name in the list and display it to console.

The *0 is very obvious. I suggest Math.floor(Math.random()) to hide it just a bit better

Not that it matters after multiplying by 0, but Math.random(n) doesn't return return what you think it does.


text:
Travelling Salesman

You are given, as a list or vector or whatever, a bunch of 3-tuples or whatever, where the first two things are strings, and the third thing is a number. The strings are cities, and the number is the distance between them. The order of the cities in the tuple is arbitrary (i.e. it doesn't matter which comes first and which comes second) since it is the same distance each way. Also, there is exactly one tuple for each pair of connected cites. Not all cities may be connected. Also, the distance is always positive (not 0). You do not need to check these conditions, you may assume input will be well formed.  Your job is to return the cities in a cyclic sequence, such that, if you start at any one city, and go around the sequence back to the same city, the total of the distances between the cities will be minimum (exactly and in all cases.) You may assume a solution exists. For example, let us say you are given
[("New York", "Detroit", 2.2), ("New York", "Dillsburg", 3.7), ("Hong Kong", "Dillsburg", 4), ("Hong Kong", "Detroit", 4), ("Dillsburg", "Detroit", 9000.1), ("New York", "Hong Kong", 9000.01)]

You could output any of the following (but you only need to output one):
["Detroit","Hong Kong","Dillsburg","New York"]
["Hong Kong","Dillsburg","New York","Detroit"]
["Dillsburg","New York","Detroit","Hong Kong"]
["New York","Detroit","Hong Kong","Dillsburg"]
["Dillsburg","Hong Kong","Detroit","New York"]
["New York","Dillsburg","Hong Kong","Detroit"]
["Detroit","New York","Dillsburg","Hong Kong"]
["Hong Kong","Detroit","New York","Dillsburg"]

because it is the shortest trip: 13.9
but not
["Dillburg","Detroit","New York","Hong Kong"]

because it is not the shortest.
See en.wikipedia.org/wiki/Travelling_salesman_problem
Scoring
This is where it gets interesting. You take the number of characters you have, and then plug them into the bare worst case O-notation formula. For example, let us say you write a brute force program that is 42 characters. As we all know, the worst case is n! where n is the number of cities. 42!=1405006117752879898543142606244511569936384000000000, so that is your score. The lowest score wins.
Note: I relieved this afterwards too, but wasn't sure how to solve it and hoped that no one would notice. People did, so I will go with issacg's suggestion:

the only options are O(n!) and O(b^nn^aln(n)^k), and all bounds must
  be as tight as possible given that notation

But how do you say someone's code is O(n!) but not O(sqrt(n)*n^n/e^n) nor O(n!/100000000000000000000)?

@user23013 One solution is to say the only options are O(n!) and O(b^n*n^a*ln(n)^k), and all bounds must be as tight as possible given that notation. OP should clarify, though.

@Geobits As shown in the comic, the dynamic programing solution is O(n^2*2^n), which is much less than O(n!) for large n.

@proud haskeller okay (it's actually been out for a while and i just wanted to accept it because it was the best despite having nearly no votes, but if you get something better go ahead.)

@PyRulez well whatever I try I convince myself it has complexity of O(n!)... it's complex

well now I'm convinced my code has complexity of O(n^2*2^n) and I Just noticed that the solutions that were shorter had worse complexity, so I have the best score overall!

What if answer do extra work that make complexity larger but smaller on the n?

require a,b,k>=0?

@l4m2 yes``````

So is O(2.00000000000000000000000001^n) fine lol with extra code

Haskell, 259
I thought I would be able to get it shorter. maybe I will.
this has time complexity of O(n^2*2^n)* so score is about 6.2e82
*i'm not actually sure, but if there is any "addition" to the complexity it's not more than polynomial, so this shouldn't change the score much.
import Data.List
g e=tail$snd$minimum[r|r@(_,b)<-iterate(\l->nubBy((.f).(==).f)$sort[(b+d,c:a)|(b,a)<-l,c<-h\\init a,d<-a!!0%c])[(0,[h!!0])]!!length h,b!!0==h!!0]where h=sort$nub$e>>= \(a,b,_)->[a,b];a%b=[z|(x,y,z)<-e,x==a&&y==b||x==b&&y==a]
f(_,x:b)=x:sort b

it's been a while, but is there a 'non-minified' (perhaps annotated) version available? I'm curious how you solved this issue with Haskell.

Python 2, 237 231 228 225 characters
Since this is a naive algorithm, its score is probably about 225! ≈ 1.26e433.
from itertools import*
a=input()
n=lambda*a:tuple(sorted(a))
d=dict((n(*x[:2]),x[2])for x in a)
print min(permutations(set(chain(*[x[:2]for x in a]))),key=lambda x:sum(d.get(n(x[i],x[i+1]),1e400)for i in range(-1,len(x)-1)))

from itertools import* would be shorter.

Oh, good idea..!

I can't test now, so I'm just throwing ideas. Is the set necessary?

The set is used to eliminate duplicates in the list of cities. Since the input does not contain entries like ("a", "a", 0), there would need to be extra logic somewhere to skip zero-length edges. (And if you're on the web, you can always test with something like http://codepad.org.)

I don't know much about Python, but apparently you have called sum on each item of a permutation. Wouldn't that be O(n!*n)?

Julia, 213 chars
Probably goes like n!n, so ~2e407.
a=[("New York", "Detroit", 2.2), ("New York", "Dillsburg", 3.7), ("Hong Kong", "Dillsburg", 4), ("Hong Kong", "Detroit", 4), ("Dillsburg", "Detroit", 9000.1), ("New York", "Hong Kong", 9000.01)]
f(a)=(
d(x,y)=(r=filter(z->x in z&&y in z,a);r==[]?Inf:r[1][3]);
m=Inf;
q=0;
c=unique([[z[1] for z=a],[z[2] for z=a]]);
n=length(c);
for p=permutations(c);
    x=sum([d(p[i],p[mod1(i+1,n)]) for i=1:n]);
    x<m&&(m=x;q=p);
end;
q)
f(a)

For readability and to demonstrate use I left in some unscored newlines and tabs as well as example input and a call to the function. Also I used an algorithm that requires n! time, but not n! memory, its slightly more feasible to run.

Called sum on each item of a permutation. Wouldn't that be O(n!*n)?

Yeah I think you're right.

Python 3 - 491
I did not count the length of the input graph variable g. This solution uses dynamic programming, and has a complexity of n^2 * 2^n, for a total score of ~6.39e147. I am still pretty new to golfing, so please chime in if you see a big waste of code somewhere!
g=[("New York", "Detroit", 2.2), ("New York", "Dillsburg", 3.7), ("Hong Kong", "Dillsburg", 4), ("Hong Kong", "Detroit", 4), ("Dillsburg", "Detroit", 9000.1), ("New York", "Hong Kong", 9000.01)]
s=''
c={s:1}
D={}
for t in g:c[t[0]]=1;c[t[1]]=1;D[(t[0],t[1])]=t[2];D[(t[1],t[0])]=t[2];D[('',t[0])]=0;D['',t[1]]=0
V={}
y=[x for x in c.keys() if x!='']
f=''
def n(z,p):
 if(len(p)==len(y)-1):
  global f;f=z
 if(0==len(p)):
  return (D[(z,f)] if (z,f) in D else float('inf'))
 Y=[(float('inf'),'')]
 for P in p:
  if((z,P) in D):
   Y.append((D[(z,P)] + n(P,[m for m in p if m!=P]), P))
 V[(z,tuple(p))]=min(Y)
 return min(Y)[0]
n('',y)
for i in range(len(c)-1):
 N=V[(s,tuple(y))][1]
 print(N)
 s=N
 y.remove(N)

Mathematica, 66 bytes
Most@Last@FindShortestTour@Graph[#<->#2&@@@#,EdgeWeight->Last/@#]&

No idea on the complexity, so the score is somewhere between 10^23 and 10^93.

Ruby, 198 180 bytes
G=eval(gets.tr("()","[]"))
C=G.map{|t|[t[0],t[1]]}.flatten.uniq
D=Hash.new(+1.0/0)
G.map{|p|D[[p[0],p[1]]]=D[[p[1],p[0]]]=p[2]}
p C.permutation.map{|l|d=0;p=l[-1];l.map{|c|d+=D[[p,c]];p=c};[d,l]}.sort[0][1]

The first line that reads the input is unscored, as that seems to be what everyone else is doing. Also, there is no final newline needed for ruby.
It just dumbly generates all permutations of cities, so put me down for O(n!*n). Actually, on second thoughts, it's slower even than that, because it sorts all O(n!) paths rather than keeping track of the best so far.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Mastermind strategy
I could only find code-golf challenges for Mastermind, so here's a code-challenge version that I would have liked to take on myself.
An optimal strategy for the normal Mastermind game, MM(4,6), was found by Koyama and Lai in 1993, having an average # of guesses = 5625/1296 ~ 4.34. MM(5,8) is still unsolved, but is estimated to have an average # of guesses ~ 5.5.
Your task is to create an MM(5,8) strategy, that is for 5 holes and 8 colors, covering all pow(8,5) = 32768 possible distinct solutions. Obviously, it doesn't have to be an optimal one. You have two choices:

Post a deterministic program that generates the strategy. The program must be compileable/runnable on Windows 7, Mac OS X or Linux without any extra non-free software.
Publish your strategy (along with your StackExchange name) somewhere on the Internet and post the URL here.

In both cases, state the score (see below) in the answer's header.
The strategy must be encoded according to the following grammar:
strategy : guessing-strategy | known-solution-strategy
guessing-strategy : '{' guess ':' branches '}'
known-solution-strategy : guess
guess : color color color color color
color : 'A'..'H'
branches : '{' branch (',' branch)* '}'
branch : reply ':' strategy
reply : number-of-blacks number-of-whites
number-of-blacks : number-of-key-pegs
number-of-whites : number-of-key-pegs
number-of-key-pegs : '0'..'5'

The algorithm used to decide the number of black/white key pegs is described in http://en.wikipedia.org/wiki/Mastermind_(board_game)
Note that the reply "50" (i.e. correct guess) is implied and not part of the grammar.
Scoring: N = the sum of the number of guesses for each of the 32768 paths/solutions. The strategy with the lowest N wins. First tie-break: The lowest maximum number of guesses. Second tie-break: The first posted answer. The competition ends August 1, 2014 0:00 GMT.

An example of a strategy for MM(2,3) with score = 21:
{AB:{10:{AC:{10:AA,01:CB,00:BB}},02:BA,01:{BC:{01:CA}},00:CC}}

Using this strategy, the 9 possible games will go like this:

AB 20
AB 10, AC 20
AB 10, AC 10, AA 20
AB 10, AC 01, CB 20
AB 10, AC 00, BB 20
AB 02, BA 20
AB 01, BC 20
AB 01, BC 01, CA 20
AB 00, CC 20

I will soon post a Java-based MM(5,8) strategy verifier for your convenience.

I'm having a difficult time understanding how the example strategy of MM(2,3) is applied. Can you post a sample game explaining the strategy?

@tolos I added all 9 :)

It would be great if your verifier could output a score, too!

@Charles Will do!

How is the verifier going? :)

Would you be willing to change your grammar to allow the same response to multiple key peg combinations? Like {AB:{10|01:BB}}? I do have an answer, but it's pretty naive and due to the tree-structure of the grammar it doesn't scale well at all (4 holes, 3 colours, generates a 147MB strategy, which I could cut down significantly by combining parts of the tree).

For information, a MM(5,8) strategy was implemented scoring 179929 with a maximum depth of 8 as detailed here (github site): Optimal MM(5,8) strategy This strategy is "mathematically optimal" with the restriction of only making possible guesses (not impossible ones) and takes a few days to complete.

Java
My algorithm for MM(5,8) scores with 177902 178006 182798 182697 with a maximum depth of 8 9 and needs only a few seconds (on my slow computer).
An example output of a strategy for MM(2,3) with score = 21 found by this algorithm looks like this:
{BC:{00:AA,01:AB:{01:CA},02:CB,10:AC:{00:BB,01:BA,10:CC}}}

There is nothing exciting with my algorithm. No invention. I just followed recipes found in the net and compressed them into this Java code.
The only optimization I did is trying to optimize the lines of code (in a way). It goes like this:

Create the initial set S0 of all possible codes to be the current set S.
Codebreaker finds a (greedy) good guess for S. Each guess leads to a partition P of S, where each subset S' collects all codes (from S) having the same reply on the guess. A good guess has a good partition, as the one giving most information for the guess.
Take the good guess and its P. For each nonempty S' in P apply codebreaker recursive (step 2).

@MrBackend: Writing a verifier is hard, I guess. ;-)
import java.util.TreeMap;
import java.util.Vector;

public class MM {
    Vector<String> codeset = new Vector<String>();
    String guess;
    TreeMap<Integer, MM> strategy = new TreeMap<Integer, MM>();

    public String toString() {
        String list="";
        for (Integer reply: strategy.keySet()) {
            if (strategy.get(reply)!=null) list+=(list.length()>0?",":"")+(reply<10?"0":"")+reply+":"+strategy.get(reply);
        }
        if (list.length()>0) return guess+":{"+list+"}"; else return guess;
    }

    MM() { }

    MM(int h, int c) {
        for (int i = 0; i < Math.pow(c, h); i++) {
            String code = "";
            for (int j = 0, p=i; j < h; j++) {
                code+="ABCDEFGH".charAt(p%c);
                p/=c;
            }
            codeset.add(code);
        }
    }

    int replyAccordingToDonaldKnuth(String secret, String guess) {
        int black=0;
        int totalHitsBlackAndWhite=0;
        for (char n = 'A'; n <= 'H'; n++) {
            int a=0, b=0;
            for (int i = 0; i < secret.length(); i++) {
                if (secret.charAt(i)==n) a++;
                if ( guess.charAt(i)==n) b++;
            }
            totalHitsBlackAndWhite+=Math.min(a, b);
        }
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) == guess.charAt(i)) black++;
        }
        return 10 * black + (totalHitsBlackAndWhite-black);
    }

    int reply(String secret, String guess) {
        return replyAccordingToDonaldKnuth(secret, guess);
    }

    MM codebreaker(Vector<String> permuts) {
        int fitness=0;
        MM protostrategy=null;
        for (int greedy = 0; greedy < Math.min(permuts.size(), 200); greedy++) {
            MM tmp=partition(permuts, permuts.get(greedy));
            int value=tmp.strategy.size();
            if (fitness<=value) {
                fitness=value;
                protostrategy=tmp;
                protostrategy.guess=permuts.get(greedy);
            }
        }
        if (protostrategy!=null) {
            for (Integer reply: protostrategy.strategy.keySet()) {
                protostrategy.strategy.put(reply, codebreaker(protostrategy.strategy.get(reply).codeset));
            }
        }
        return protostrategy;
    }

    MM partition(Vector<String> permuts, String code) {
        MM protostrategy=new MM();
        for (int c = 0; c < permuts.size(); c++) {
            int reply=reply(permuts.get(c), code);
            if (!protostrategy.strategy.containsKey(reply)) protostrategy.strategy.put(reply, new MM());
            if (permuts.get(c)!=code) protostrategy.strategy.get(reply).codeset.add(permuts.get(c));
        }
        return protostrategy;
    }

    public static void main(String[] args) {
        MM mm = new MM(5,8);
        System.out.println("{"+mm.codebreaker(mm.codeset)+"}");
    }
}

Some remarks:

No consistency check is needed because sets S and their partitions are build in a (auto-)consistent way.
Picking a good guess out of S0 (instead of S) makes sense. But I don't follow this approach in the current code.
My greedy search is artificially pruned to 200 tries.
I know, "giving most information for the guess" is not very precise. The simple idea is to pick the partition with the most number of subsets.
The result heavily depends on how you calculate the reply(..). Finally I adapted Donald Knuth's expression.

The strategy for MM(5,8) can be found here. GitHub has some issues displaying lines that long, so click on the Raw button.

hi how to pretty print the github
text so that the results can be turned into a lookup guide.. from the first starting point 'HHCAA'.. and next step depending on the reply... and to next and so on. The current raw text format it is not easier for manual scanning.. the technique i am after is how to parse the nested brackets and get a nice table layout that is easier to follow through till the end, similar to the bulleted list in the question for MM(2,3). Thank you. Hope you can understand what I am after. (prefer python to parse str)

Ruby
EDIT: Added some logic to exclude impossible guesses. Hence, the strategies now comply with the given format and are much more manageable.
So here is one attempt to get this going. It's pretty naive (and not very legible - it helps to read the if/elsif/else branch from bottom to top).
Holes, Colors = ARGV.map &:to_i

ColorChars = ('A'..'H').to_a

def is_possible(guess, blacks, result)
    blacks == guess.chars.zip(result.chars).count {|chars| chars[0] == chars[1]}
end

def print_strategy(known_colors, remaining_permutations, next_color)
    char = ColorChars[next_color]
    if remaining_permutations
        guess = remaining_permutations[0]
        print guess
        if remaining_permutations.length > 1
            print ':{'
            (Holes-1).times do |i|
                new_permutations = (remaining_permutations - [guess]).select { |perm| is_possible(guess, i, perm) }
                next if new_permutations.empty?
                print "#{i}#{Holes-i}:"
                print '{' if new_permutations.length > 1
                print_strategy(known_colors, new_permutations, next_color)
                print '}' if new_permutations.length > 1
                print ',' if i < Holes-2
            end
            print '}'
        end
    elsif known_colors.length == Holes
        print_strategy(known_colors, known_colors.chars.permutation.map(&:join).uniq, next_color)
    elsif next_color == Colors-1
        print_strategy(known_colors+char*(Holes - known_colors.length), remaining_permutations, next_color+1)
    else
        print char*Holes, ':{'

        (Holes - known_colors.length + 1).times do |i|
            break if i == Holes
            print "#{i}0:"
            print '{' if next_color < Colors-2 || i > 0 || known_colors.length > 0
            print_strategy(
                known_colors+char*i,
                remaining_permutations,
                next_color+1
            )
            print '}' if next_color < Colors-2 || i > 0 || known_colors.length > 0
            print ',' if i < (Holes - known_colors.length) && i < Holes-1
        end
        print '}'
    end
end

print '{'
print_strategy('', nil, 0)
puts '}'

First, I try 5 of each colour: AAAAA, BBBBB, etc. From that I figure out which colours are actually used in the pattern. And then I simply try all permutations of the given colours, omitting those which have been ruled out by the black pegs already.
Here is the MM(2,3) strategy:
{AA:{00:{BB:{00:CC,10:{BC:{02:CB}}}},10:{BB:{00:{AC:{02:CA}},10:{AB:{02:BA}}}}}}

The strategy for MM(5,8) takes 376KB and can be found here. GitHub has some issues displaying lines that long, so click on the Raw button.
Now if I get a verifier, I can also tell you what my actual score is. :)

Feeling bad about the verifier not published yet, but it´s on its way...  There is something wrong with your (first) MM(2,3) strategy, for example if the solution is AB: Guess=AA; reply=10; guess=BB; reply=10, for which there is no strategy.  I´ll look into your suggestion of grouping replies, but it should not be necessary for good strategies, since the set of possible solutions are disjoint for different replies.

@MrBackend Good catch, I skipped a case there. It should be fixed now. As for the grammar, of course it's not necessary for good strategies, but I thought you might be willing to lower the bar a bit. ;) If people can submit simpler entries (like mine) you might have a bit more luck getting interesting submissions that gradually improve, instead of having to include all of the combinatorics right from the start.

Here's the deal: I'll finish the current verifier and publish it (as a web app - it is too large to paste here). Unfortunately, it might be too strict, as it considers impossible replies an error. Afterwards, I'll adapt it to support multiple replies and just emit warnings for impossible replies.  Having said that, your 1.3G MM(4,4) strategy has to contain a lot of impossible replies and/or non-reducing guesses, as the estimated size of a decent MM(5,8) strategy is a handful of megs.

@MrBackend Of course my strategies contain a ton of impossible replies. That's what I meant by "I'm not doing the combinatorics". ;) If it's too much of a hassle for you to support that and grouping replies, don't worry, then I'll have a look into omitting impossible guesses.

@MrBackend Good news, I fixed it. :) I hope the strategy is valid now. Let me know if there are still any problems with it.

authors: สมศักดิ์ สุทธิชาติ

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Help me with differential calculus!
I love programming and know every language, but I suck at math. Unfortunately, my school requires that computers students must take a year of calculus. There's a test next week, and I don't know any of the formulas for derivatives!
Please help me find the formulas. I need a cheat sheet - a program (as short as possible so my teacher won't notice it) that takes an expression (like 4*x^3-2) as input and outputs the derivative. (I don't care if the input and output uses command line arguments, STDIN, STDOUT, or whatever, since I'm doing all of the calculation in my head anyway.)
The test covers the following types of functions:

Constants, like -3 or 8.5
Power functions, like x^0.5 or x^-7
Exponential functions, like 0.5^x or 7^x (the base is always positive)
A constant multiplied by a  function, like 3*x^5 or -0.1*0.3^x
The sum and difference of multiple functions, like -5*x^2+10-3^x

My teacher always formats his questions in the exact same way, as shown above. He also doesn't use any fractions, numbers like pi or e, or really big numbers (bigger than 1,000). He never uses parentheses, and always shows multiplication using an asterisk (*). The only variable used is always x.
On the other hand, my teacher is pretty lenient about answers. They don't need to be simplified at all or formatted exactly as shown above, as long as it's clear what the answer is saying.
While I can use any language, remember that I can't figure out derivatives by myself. So if the program uses built-in functions to deal with equations or calculate derivatives, I won't be able to use it.
During the test, I won't have access to the Internet or any files other than the program on the cheat sheet.
Note: This scenario is entirely fictional. In real life, cheating and helping others cheat is wrong and should never be done.

Can we expect that x is always the variable to differentiate?

Must the answer be simplified? Do we need to add like terms?

Will any numbers be in scientific notation?

Will there be any product rule?

I guess it's time for my calculus project at http://scrblnrd3.github.io/Javascript-CAS/ to shine if I can actually golf it

Should we assume there are no parens?

I've answered most of these questions in my edit. There is no scientific notation or product rule.

Oh. So no chain rule.

I'm sure a math language such as Maple would make short work of this problem.

@MBraedley However: http://meta.codegolf.stackexchange.com/a/1078/9498

Can x^x appear?

Also, is -2^x to be interpreted as -(2^x) or as (-2)^x?

@celtschk x^x will not appear (since it requires using techniques other than the ones listed). -2^x means -(2^x) (since, as mentioned, the base will never be negative).

--Views hot network questions: Help me with differential calculus! "I know differential calculus, maybe I can help this guy." --Reads question --Reviews answers "WTH, these answers are all terrible." On a serious note, I think it's an indication of a good question setup that two separate posters were convinced your situation was real.

Wolfram 136 134 109[Thanks to Calle for his comment below]
Limited support for product and chain rules.
n=n_?NumberQ;d[v_Plus]:=d/@v;d[v_]:=v/.{x_^n:>x^(n-1)d[x]n,n^x_:>Log[n]d[x]n^x,x_*y__:>d[x]y+d[y]x,n:>0,x:>1}

Example:
d[3^(x^2)*(x^3+2*x)^2]
>> 2*3^x^2*(2+3*x^2)*(2*x+x^3) + 2*3^x^2*x*(2*x+x^3)^2*Log[3]

Note that this does not use any "built-in functions to deal with equations or calculate derivatives": only pattern-matching is involved*.
[*Well... technically the interpreter also parses and builds a sort of AST from the input too]

Ungolfed:
d[expr_Plus] := d /@ expr;
d[expr_] := expr /. {
   Power[x_, n_?NumberQ] :> n Power[x, n - 1] d[x],
   Power[n_?NumberQ, x_] :> Log[n] Power[n, x] d[x],
   Times[x_, y__] :> d[x] y + d[y] x,
   n_?NumberQ :> 0,
   x :> 1
}

This is another version. You don't have to write Power, Times etc. IDK how much that will improve your golfed version though, but you have at least one Times in there so you can def. save some characters. Also note that in your ungolfed version it says d[expr_]:= v/....

@Calle "IDK how much that will improve your golfed version" -- 25 bytes! Cheers!

Perl - 121 122
(+2 for -p)
s/(?<![-\d.*^])-?[\d.]+(?![*^\d.])/0/g;s/(?<!\^)x(?!\^)/1/g;s/x\^(-?[\d.]+)/"$1*x^".($1-1)/ge;s/([\d.]+)\^x/ln($1)*$&/g

Test:
$ perl -p diff.pl << EOF
> -3
> 8.5
> x^0.5
> x^-7
> 0.5^x
> 7^x
> 3*x^5
> -0.1*0.3^x
> -5*x^2+10-3^x
> EOF
0
0
0.5*x^-0.5
-7*x^-8
ln(0.5)*0.5^x
ln(7)*7^x
3*5*x^4
-0.1*ln(0.3)*0.3^x
-5*2*x^1+0-ln(3)*3^x

Yet another reason for me to learn regex...

@KyleKanos Don't. Regex is bad, regex is terrific.

Meh, beat me to it. Not bad! (PS: regex is beautiful)

I have no idea what's going on here. +1

Explanation: Constant --> 0, x --> 1, x^n --> n*x^(n-1), a^x --> ln(a)*a^x

I'm pretty sure that -p can count as one character since it's a flag and flags can be combined like -alFe

@professorfish i'm pretty sure the first flag costs 2. There's a meta post somewhere

@Cruncher The most 'definitive' post seems to be this one by J B, which doesn't actually specify the cost of the first flag (just that each additional flag costs one). I typically count it as one, although traditional Perl Golf rules would count it as three (one for each byte in -p, plus the necessary whitespace). One thing I disagree with in that post, is that -M5.01 should be free (in Perl, enables 'special features' that were added in v5.010).

Haskell 38 Chars
The function d takes a function and returns a function. It is inputted in the form of a power series, and is outputted the same way (which is a type of whatever.)
d=zipWith(*)[1..].tail

For example, if we input x->x^2, we get x->2*x.
λ <Prelude>: d [0,0,1]
[0,2]

And for the exponential function.
λ <Prelude>: take 10 exp --exp redefined above to be in power series notation
[1.0,1.0,0.5,0.16666666666666666,4.1666666666666664e-2,8.333333333333333e-3,1.388888888888889e-3,1.984126984126984e-4,2.48015873015873e-5,2.7557319223985893e-6]
λ <Prelude>: let d=zipWith(*)[1..].tail in take 10 $ d exp
[1.0,1.0,0.5,0.16666666666666666,4.1666666666666664e-2,8.333333333333333e-3,1.388888888888889e-3,1.984126984126984e-4,2.48015873015873e-5,2.7557319223985893e-6]

But the OP doesn't know any maths! Can we expect him to express his exponential input as a power series?

Well he obviously knows notation. He just doesn't know how to do the derivative operation.

Can this handle 2^x?

@KyleKanos Yep, just put x*ln 2 into e^x. It will still be a power series.

What witchcraft is this?

@ChristoferOlsson: http://en.wikipedia.org/wiki/Taylor_series

I don't see where it "takes an expression (like 4*x^3-2) as input", as required by the OP.

@Gabe You put the expression into d. It does take string arguments though.

It looks like d takes a list of numbers and returns a list of numbers. I don't see how you'd put an expression like 4*x^3-2 into d.

@Gabe You input 4*x^3-2 in the format of [-2,0,0,4]. Also, I meant it doesn't take string arguments, the above is a typo.

I see. Do you expect the OP to convert from a Taylor polynomial to an algebraic expression, or is he supposed to answer all his test questions as polynomials?

@Gabe As polynomials. He just writes the first term in 1 second and 1 cm long, the second in half a second and half a cm long, the third in a forth second and a forth cm long, and so on. He will finish in 2 seconds and it will fit in any blank 2 cm long or less time and length.

@PyRulez Lol! I get that infinite series joke!

Prolog 176
d(N,0):-number(N).
d(x,1).
d(-L,-E):-d(L,E).
d(L+R,E+F):-d(L,E),d(R,F).
d(L-R,E-F):-d(L,E),d(R,F).
d(L*R,E*R+L*F):-d(L,E),d(R,F).
d(L^R,E*R*L^(R-1)+ln(L)*F*L^R):-d(L,E),d(R,F).

Supported operators: binary +, binary -, binary *, binary ^, unary -. Note that unary + is not supported.
Sample run:
49 ?- d(-3,O).
O = 0.

50 ?- d(8.5,O).
O = 0.

51 ?- d(x^0.5,O).
O = 1*0.5*x^ (0.5-1)+ln(x)*0*x^0.5.

52 ?- d(x^-7,O).
ERROR: Syntax error: Operator expected
ERROR: d(x
ERROR: ** here **
ERROR: ^-7,O) .
52 ?- d(x^ -7,O).
O = 1* -7*x^ (-7-1)+ln(x)*0*x^ -7.

53 ?- d(x,O).
O = 1.

54 ?- d(0.5^x,O).
O = 0*x*0.5^ (x-1)+ln(0.5)*1*0.5^x.

55 ?- d(7^x,O).
O = 0*x*7^ (x-1)+ln(7)*1*7^x.

56 ?- d(3*x^5,O).
O = 0*x^5+3* (1*5*x^ (5-1)+ln(x)*0*x^5).

57 ?- d(-0.1*0.3^x,O).
O = 0*0.3^x+ -0.1* (0*x*0.3^ (x-1)+ln(0.3)*1*0.3^x).

58 ?- d(-5*x^2+10-3^x,O).
O = 0*x^2+ -5* (1*2*x^ (2-1)+ln(x)*0*x^2)+0- (0*x*3^ (x-1)+ln(3)*1*3^x).

Prolog is confused when it runs into ^- sequence. A space must be inserted between ^ and - for it to parse the expression correctly.
Hope your teacher doesn't mind the mess of equation.
Crazy time:
59 ?- d(x^x,O).
O = 1*x*x^ (x-1)+ln(x)*1*x^x.

60 ?- d((x^2-x+1)*4^ -x,O).
O = (1*2*x^ (2-1)+ln(x)*0*x^2-1+0)*4^ -x+ (x^2-x+1)* (0* -x*4^ (-x-1)+ln(4)* - 1*4^ -x).

C, 260 248 bytes
−12 bytes thanks to ceilingcat
Hey, I think I know your teacher! Isn't it that one who has the supernatural ability to detect students executing library pattern-matching functions in their head?
So, using sscanf is out of question... But don't worry:
#define P,s--||printf(
q=94,s,c,t;main(a){char*p,i[999],*e=p=i;for(gets(i);q=c=*p++,t=q^94|c^45?c%26-16?c/46:c%16/3:1,s=(a="30PCqspP#!C@ #cS` #!cpp#q"[s*5+t])/16-3,p[-1]*=~a&1,!t?0 P"*0")P"/x")P"/x*%s",e)P"*ln(%s)",e),s=0:0,e=a&2?p:e,printf(&c););}

Running examples (input on stdin; output goes to stdout):

4*x^3-2

4*x^3/x*3-2*0

This format is much better than just 12*x^2, because this way your teacher can be sure that you calculated the answer yourself and didn't cheat by copying it from someone else!

x+2^x

x/x+2^x*ln(2)

The output has a slight domain problem at x=0, but it's correct almost everywhere!
For reference, here is an ungolfed, readable (by mere mortals) version. It uses a state machine with 5 states and 5 categories of input characters.
void deriv(char* input)
{
    char* p = input; // current position
    char* exp = p; // base or exponent
    char q = '^'; // previous character

    // State machine has 5 states; here are examples of input:
    // state 0: 123
    // state 1: 123*
    // state 2: 123*x
    // state 3: 123*x^456
    // state 4: 123^x
    int state = 0;

    // Control bits for state machine:
    // bit 0: special action: stop recording base or exponent
    // bit 1: special action: start recording base or exponent
    // bits 4-7: if first column, specify how to calculate the derivative:
    //              3 - multiply the constant term by 0
    //              4 - divide x by x
    //              5 - divide x^n by x and multiply by n
    //              6 - multiply n^x by ln(n)
    // bits 4-7: if not first column, specify the next state
    //              (plus 3, to make the character printable)
    const char* control =
        "\x33\x30\x50\x43\x71"
        "\x73\x70\x50\x23\x21"
        "\x43\x40\x20\x23\x63"
        "\x53\x60\x20\x23\x21"
        "\x63\x70\x70\x23\x71";

    for (;;) {
        int c = *p++;

        // Convert a char to a category:
        // category 0: // - +
        // category 3: // *
        // category 2: // x
        // category 4: // ^
        // category 1: // numbers: 0...9 and decimal point
        int category;
        int action;

        if (q == '^' && c == '-')
            category = 1; // unary minus is a part of a number
        else
            category = c%26==16?c%16/3:c/46; // just does it

        // Load new state and action to do
        action = control[state * 5 + category];

        if (action & 1)
            p[-1] = 0;
        state = (action >> 4) - 3;
        if (category == 0)
        {
            if (state == 0)
                printf("*0");
            if (state == 1)
                printf("/x");
            if (state == 2)
                printf("/x*%s", exp);
            if (state == 3)
                printf("*ln(%s)", exp);
            state = 0;
        }
        if (action & 2)
            exp = p;

        if (c == 0 || c == '\n') // either of these can mark end of input
            break;

        putchar(c);
        q = c;
    }
}

P.S. Watch out for that gets function: it has a security vulnerability that can let your teacher execute a rootkit in your mind by providing too long input...

@ceilingcat Fail on -x^-1 what does *0-x^/x*-1*0 mean?

Oh you assume input 0-x^-1 but 0*0-x^/x*-1*0 still has a ^/

Lua 296 268 263
function d(a)l=""i=a:find"x" if i then if a:sub(i-1,i-1)=="^"then l="log("..a:sub(1,i-2)..")*"..a elseif a:sub(i+1,i+1)=="^"then l=a:sub(i+2).."*"..a:sub(1,i)p=a:sub(i+2)-1 if p~=1 then l= l..a:sub(i+1,i+1)..p end else l=a:sub(1,i-2)end else l="0"end return l end

Not very golfed and cannot currently handle multiple terms (you can just run it a few times, right?), but it can handle n^x, x^n and n as input.

Ungolfed...
function d(a)
   l=""
   i=a:find"x"
   if i then
      if a:sub(i-1,i-1)=="^" then
         l="log("..a:sub(1,i-2)..")*"..a
      elseif a:sub(i+1,i+1)=="^" then
         l=a:sub(i+2).."*"..a:sub(1,i)
         p=a:sub(i+2)-1 -- this actually does math here
         if p~=1 then
            l= l..a:sub(i+1,i+1)..p
         end
      else
         l=a:sub(1,i-2)
      end
   else
      l="0"
   end
   return l
end

str.func(str,...) == str:func(...), that's why strings got the metatable after all...

@mniip: Still learning Lua. Thanks for the tip.

Since the OP is only looking for code "he can calculate in his head", I wouldn't bother with defining a function and declaring l local. Just expect the input to be stored in a and say the output will be stored in l.

You can omit parentheses in a:find("x"), also note that 1then only works in Lua 5.2

@mniip: Whoa, that's pretty cool that () is optional. The 1then was just fixed as I don't have 5.2 (not doing any CPU updates until after dissertation is done b/c I don't want to mess anything up).

ECMAScript 6, 127 bytes
Here is my regex attempt (using a single regex and some logic in the replacement callback):
i.replace(/(^|[*+-])(\d+|(?:([\d.]+)\^)?(x)(?:\^(-?[\d.]+))?)(?![.*^])/g,(m,s,a,b,x,e)=>s+(b?'ln'+b+'*'+a:e?e--+'*x^'+e:x?1:0))

This expects the input string to be stored in i and simply returns the result. Try it out in an ECMAScript 6 compliant console (like Firefox's).

sed, 110
Taking very literally "They don't need to be simplified at all or formatted exactly as shown above, as long as it's clear what the answer is saying":
s/.*/__&_/;s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g;s/([0-9.]+)\^/ln\1*\1^/g;s/([^(][-+_])[0-9.]+([-+_])/\10\2/g;s/_//g

The byte count includes 1 for the r flag.
Ungolfed, with comments:
# Add underscores before and after the string, to help with solo-constant recognition
s/.*/__&_/
# Power rule: replace x^c with c*x^(c-1) where c is a number
s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g
# Exponentials: replace c^ with lnc*c^ where c is a number
# (This assumes that there will be an x after the ^)
s/([0-9.]+)\^/ln\1*\1^/g
# Constants: replace ?c? with ?0? where c is a number and ? is +, -, or _
# Except if it's prededed by a parenthesis then don't, because this matches c*x^(c-1)!
s/([^(][-+_])[0-9.]+([-+_])/\10\2/g
# Get rid of the underscores
s/_//g

Sample run:
$ cat derivatives.txt
-3
8.5
x^0.5
x^-7
0.5^x
7^x
3*x^5
-0.1*0.3^x
-5*x^2+10-3^x

$ sed -re 's/.*/__&_/;s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g;s/([0-9.]+)\^/ln\1*\1^/g;s/([^(][-+_])[0-9.]+([-+_])/\10\2/g;s/_//g' derivatives.txt
-0
0
0.5*x^(0.5-1)
-7*x^(-7-1)
ln0.5*0.5^x
ln7*7^x
3*5*x^(5-1)
-0.1*ln0.3*0.3^x
-5*2*x^(2-1)+0-ln3*3^x

I bet this could be golfed further; it's my first try at sed.  Fun!

Ruby, 152
...or 150 if you don't need to print... or 147 if you also are ok with an array that you need to join yourself.
run with ruby -nal
p gsub(/(?<!\^)([-+])/,'#\1').split(?#).map{|s|s[/x\^/]?$`+$'+"x^(#{$'}-1)":s[/-?(.*)\^(.*)x/]?s+"*ln(#{$1}*#{$2[0]?$2:1})":s[/\*?x/]?($`[0]?$`:1):p}*''

ungolfed:
p gsub(/(?<!\^)([-+])/,'#\1').split(?#). # insert a # between each additive piece, and then split.
map{ |s|
    if s[/x\^/]                          # if it's c*x^a
        $` + $' + "x^(#{$'}-1)"          #      return c*ax^(a-1)
    elsif s[/-?(.*)\^(.*)x/]             # if it's c*b^(a*x)
        ln = $1 + ?* + ($2[0] ? $2 : 1)  #      return c*b^(a*x)*ln(b*a)
        s+"*ln(#{ln})"
    elsif s[/\*?x/]                      # if it's c*x
        ($`[0] ? $` : 1)                 #      return c
    else                                 # else (constant)
        nil                              #      return nil
    end
}*''

My main problem with this one is the number of characters proper splitting takes.  The only other way I could think of was split(/(?<!\^)([-+])/) which gives + and - as their own results.  Any hints for a better solution?
Also, is there a shorter way to return s if it's not empty, but otherwise return y? I've used s[0]?y:s?  In JS I'd just do s||y, but "" is truthy in Ruby.

Would a lookahead assertion help, like so: split(/(?<!\^)(?=[-+])/)?

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Deplane! Deplane! (Or: RGBRGBRGB => RRRGGGBBB?)
Imagine bytes in memory for an RGB image--R and G and B represented by bytes in sequence.  If an image is NxM then the memory layout will be M repetitions for vertical scanlines of 3*N bytes in sequence for the horizontal pixels.  (As one might expect.)
A mandate has come down from on high that you need to be able to isolate contiguous color planes.  You might be asked for the R, G, or B plane.  When you give back the plane it must be the N*M bytes in sequence for that color.
Yet there is a twist: You cannot use additional memory proportional to the size of the image.  Thus you must shuffle the bytes somewhere inside of the existing RGB data to provide the contiguous plane for the requested color.  And you must be able to recover the original image when processing of that color plane is finished.
The image size is actually not relevant to the problem as it operates on the buffer as a whole.  Input is bytes (expressed as hexadecimal ASCII) followed by which plane to extract:
00112233445566778899AABBCCDDEE
G

Output is the extracted color plane, then the original input *(also in hexadecimal ASCII):
114477AADD
00112233445566778899AABBCCDDEE

Where you shuffle the memory is up to you.  But you must actually shuffle the data to produce contiguous bytes (requiring the client to use an iterator is cheating).  And you must be able to reverse the operation to restore the original information.
Lowest big-O implementation wins.  Between two implementations with equal big-O performance... winner decided by code golf rules.

Surely the G channel of the sample input is 0235689BCE? And does the restriction on additional memory also apply to the print operation, or is that allowed to copy?

@petertaylor how do you figure G as not being the second byte and every third byte after?  Regarding restrictions just imagine a buffer of a million by a million image... Your print cannot depend on allocations scaling with the image size.

Is input in raw bytes, or in the base-16 encoding shown in the examples? (I think that's also @PeterTaylor's question.)

@PeterTaylor Yes, hex strings.  Clarified.

If they are hex strings, why not simply convert them to raw bytes, and then you'll have a lot of freed memory to do whatever you wish...

C
only shuffle, not print
lenght in bytes, not pixels
plane: 0,1,2 for R,G,B
not checked!
void deplane(unsigned char *data, int length, int plane) {
    unsigned char *t = data;
    unsigned char *s = data + plane;
    unsigned char p;
    while (s < data + length) {
        p = *s; *s = *t; *t = p;
        t++; s += 3;
    }
    // now plane start at data
    while (t > data) {
        s -= 3; t--;
        p = *s; *s = *t; *t = p;
    }
    // back to original
}

If you are going to golf this code, *s ^= *t; *t ^= *s; (restored by *t ^= *s; *s ^= *t;) can be shorter. But t must start at s+1 this way.

Very smart!! But why "t must start at s+1" ?

If t and s refer to the same memory position, *s ^= *t; will make *s irreversibly zero. You can also skip the first value if this happens. But it may be longer if you treat R plane in a special way.

Oh, right! ....

and the language is ...

Hello @edc65! You also from Italy and 1965 born ...

@giuliolunati What? What does that have to do with anything?

Javascript (E6)
I don't like the I/O format, these should be byte arrays or the like. Anyway.
Source not golfed.
S=(a,p)=>{
  b = a.match(/../g);    // String to array
  l = b.length/3;        // Plane size
  s = p<'G'?2:p>'G'?0:1; // Which plane

  for (j=0, i=s; b[i]; j++, i+=3) // Shuffle
    [b[i],b[j]] = [b[j],b[i]];
  console.log(b.slice(0,l).join('')); // Output plane

  for (; i-=3, j--; ) // Unshuffle
    [b[i],b[j]] = [b[j],b[i]];

  console.log(b.join('')) // Original is back
}

Usage
In firefox console:
S('00112233445566778899AABBCCDDEE','G')

Output
114477AADD
00112233445566778899AABBCCDDEE