title: Generate 0 or 1

text:
# Question
Title: Generate 0 or 1
Is this Q too easy to ask, or has it just never been thought of?

> Generate a random number, either 0 or 1 using a program

You may use a pre-defined function. The code must be executable. (It can't be just a function that requires more code to execute.) Randomness of the output will be verified by showing that it is not possible for a human/computer today to predict the output of the next execution (unless the exact algorithm is revealed), even when given an infinite set of outputs on previous executions of the code.

I'm looking for the most interesting code (never mind if it's lengthy).

*Note:* I had initially asked for the shortest code. The answer to *that* is 2 bytes long. It's `O2` in Pyth, according to @Dennis

# Answer
> 6 votes
# Pyth, 2 bytes

```
O2

```

Try it online.

# Answer
> 6 votes
# Labyrinth, 7 bytes

I think this is also the shortest answer in Labyrinth... and I think it's fairly interesting.

```
v
)
"!@

```

Labyrinth does have built-in random behaviour but it's normally very hard to access. The conditions are as follows:

* The instruction pointer (IP) needs to be on a cell with two neighbours in opposite directions.
* The IP must not be pointing at either of the neighbours.
* The value on top of the main stack must be zero.

If all of those conditions are met, the IP will choose a uniformly random direction towards one of the two neighbours.

In larger programs, this is incredibly tricky to setup, because normally there is no way to make the IP move such that it faces a wall if there isn't another neighbour at its back. The only way to set this up is by using the source-manipulation commands `<^>v`. These cyclically shift a row or a column of the source code. If the shifted row or column is the one the IP is one, the IP will be shifted along without changing its orientation. This way we can move the IP into position.

Now let's look at the code. The IP starts out on the first cell, pointing *right*. The `v` shifts the first column down one cell, taking the IP with it:

```
"
v
)!@

```

Now the IP points East, has a neighbour North and South, and the main stack still has only zeroes on it, so all conditions are met. What are the options now?

If the IP decides to move South, `)` increments the zero on top of the stack to `1` and `!` prints it. `@` terminates the program.

If the IP decides to move North, `"` is a no-op. The IP hits a dead end and turns around. Now it hits the `v` again. So we shift one further:

```
)
"
v!@

```

Now the IP is in a corner and follows the path around the bend. `!` prints the zero on top of the stack, and `@` terminates the program.

# Answer
> 6 votes
## \>\<\>, 5 bytes

```
lxn;n

```

\>\<\> is a 2D language, and `x` is "random direction" (up/down/left/right) in \>\<\>. Since \>\<\> is toroidal, up and down do nothing, as this is a one-liner and wrapping around makes us end up in the same spot. Thus, only moving left or right at the `x` do anything in this program.

The initial `l` pushes the length of the stack, 0. At the `x`, moving right makes us print the top of the stack with `n`, then halt with `;`. Otherwise, moving left executes `l` again, pushing 1 before we wrap around, print and halt.

---

And for the popcon, we have:

```
0 >   xxxxx aa*(n;
  ^+1 <<<<<

```

This is "The Ledge: \>\<\> plays Pokemon version". The instruction pointer needs to get past the row of `x`s, with falling off the ledge (random up/down) moving us back to the start, incrementing a failure counter. It's a race against time, with the program printing 1 if the IP makes it to the end whilst falling off at most 99 times, else 0.

# Answer
> 5 votes
# AppleScript/osascript, 17 Bytes

AppleScript is really a passive-aggressive teenager. o-o

```
some item of{1,0}
```

Or, 18 bytes:

```
random number of 1
```

This is kinda the cheaty way to do it. `some item` will grab a random item of a list. If I wanted a random item of a series, I would use:

```
random number from 0 to 100
```

For a random integer in the set \[0, 100\].

# Answer
> 4 votes
# Vitsy

I'm changing my answer to fit the popcon description.

```
2R(10r68*+DD:::?? WHY WOULD YOU WRITE LIKE THIS?
2R                                                Random float in [0,2).
  (10                                             If its truncated value is 1,
                                                  Push one. Then push 0.
     r                                            Reverse the stack.
      68*+                                        Add 48.
          DD                                      Duplicate, duplicate.
            :::??                                 Clone the stack thrice, rotate
                                                  stack position twice.
                   WH  W U D  U W       K   H     NOPs.
                     Y                            Delete the current stack.
                        O                         Output the top item of the stack
                                                  as a truncated int character.
                          L                       Get the length of the stack.
                            Y                     Delete the current stack.
                             O                    Output again (outputs nothing)
                                 R                Random integer.
                                  I               Get the input length.
                                   T              Tangent of the top item.
                                    E             Push the constant e to the stack.
                                      LI E T IS?   Already described above...

```

# Answer
> 3 votes
# Microscript, 2 bytes

```
r2

```

# Microscript II, also 2 bytes

```
2R

```

# Answer
> 3 votes
# TeaScript, 2 bytes

Using some not-so-new-but-implemented-last-night features, `¡` (inverted exclamation) compiles to `()`. Because of issues with permalinks and special characters, you have to copy and paste this code into the online interpreter

# Answer
> 3 votes
# Simplex v.0.7, 2 bytes

```
IX
I  ~~ increment byte
 X ~~ set byte to a random number from 0 to the current byte value

```

The byte is valued `0` by default; incrementing it by `1` then applying the random function makes it a random value from `0` to `1` inclusive.

# Answer
> 2 votes
# Python 3, 22 bytes

```
print((hash(id)>>9)&1)

```

In python 3, the output for the `hash` function was randomized per run by default.

This was because in older versions, you could make an attack on the dictionary object if you could insert arbitrary objects (such as strings for usernames or integers for uuids). You could exploit the way the dict object was implemented so you could make retrieving objects from the dictionary take much much longer than normal.

Because of this, `hash` became randomised. I'm exploiting this for the challenge so I don't need to import the random module. I'm doing `>>9` because although randomised, during the tests I ran, the last several bits never changed although this bit sometimes did. On my computer, it outputs `0` most of the time but sometimes outputs a `1`.

# Answer
> 1 votes
# CJam, 3 bytes

```
2mr

```

Try it here.

# Answer
> 1 votes
# Befunge, 6 bytes

```
?1.@.0

```

The PC starts at the top-left corner, moving right. When it runs into `?`, it will either

* Move up or down, in which case it wraps vertically back to the very same `?`
* Move left, wrapping around and executing `0`, `.` and `@`: this prints a zero and halts the program
* Move right, executing `1`, `.`, and `@`, which prints a one and halts the program.

Works for both Befunge-93 and Befunge-98.

# Answer
> 1 votes
## Perl, 28 bytes

```
my $rand=int(rand(2));
print $rand, "\n";

```

Golfed version, just in case it changes back again (I'm scoring in the headline by this):

```
my $a=int(rand(2));print $a;

```

# Answer
> 1 votes
# Mathematica

```
Boole[OddQ[ToExpression[StringSplit[ToString[s = SiderealTime[][[1, 3]]], "."][[-1]]]]]

```

---

**Explanation**

`SiderealTime[]` gives the present sidereal time.

```
s = SiderealTime[]

```

---

The code for the above time is revealed by its `LongForm`.

```
LongForm[s]

```

> Quantity\[MixedRadix\[14, 10, 33.3553\], MixedRadix\["HoursOfRightAscension", "MinutesOfRightAscension", "SecondsOfRightAscension"\]\]

---

```
s[[3,1]]

```

The element at position `{3,1}` in the expression is

> 33.3553

---

`ToString[%]` converts this to a string.

> "33.3553"

---

```
StringSplit["33.3553", "."]

```

breaks the string at the decimal point.

> {"33","3553"}

---

```
{"33","3553"}[[-1]]

```

returns the last element, namely, `"3553"`

---

```
ToExpression["3553"]

```

converts this to an integer.

> 3553

---

`OddQ[3553]` returns

> True

because `3553` is odd.

---

`Boole[True]` returns `1` for True.

`Boole[False]` would have returned `0`.

# Answer
> 1 votes
# Ruby, 8 bytes

```
p rand 2

```

Probably the shortest it gets in Ruby.

# Answer
> 1 votes
# Python 2, 16 bytes

This one is pretty fun:

```
print id('')/3&1

```

In CPython, at least, `id('')` is different every time, because the string literal `''` is at a different position in memory each time the interpreter is ran. We can't directly take the least-significant bit, because it's obviously aligned to a valid address. However, dividing by three first works fine.

# Answer
> 0 votes
# Java, 88 Bytes

```
class A{public static void main(String[]a){System.out.println((int)(Math.random()*2));}}
```

Readable version:

```
class A{
    public static void main(String[]a) {
        System.out.println((int)(Math.random()*2)); // Get a random float from [0, 2) and truncate it to an integer.
    }
}
```

# Answer
> 0 votes
# GolfScript, 5 bytes

```
2rand

```

Basically exactly like the CJam answer, but with a longer keyword.

# Answer
> 0 votes
# Ruby, *who cares* bytes

Seems this isn't a code-golf challenge anymore? Here's some multithreading for ya.

```
[0,1].map{|i|Thread.new{$n=i}}.map{|t|t.join}
p $n

```

# Answer
> 0 votes
# gs2, 2 bytes

In CP437:

```
↕%

```

Hex dump:

```
12 25

```

Pushes `2`, then calls `random`, generating a random number between 0 and 1.

# Answer
> 0 votes
## Perl, 14 bytes

```
print 0|rand 2

```

Example:

```
$ perl -e 'print 0|rand 2'
1
$ perl -e 'print 0|rand 2'
1
$ perl -e 'print 0|rand 2'
0
$

```

# Answer
> 0 votes
## bash, 19 bytes

```
echo $(($RANDOM%2))

```

# Answer
> 0 votes
# Javascript ES6, 22 bytes

Quite simple.

```
alert(0|Math.random()+.5)

```

# Answer
> 0 votes
# PHP "The Lottery"

In Germany we have a very popular lottery called "*6 aus 49*" ("*6 from 49*"). You tip 6 numbers out of the range 1 to 49. If you have selected at least 2 numbers that also the "Lottofee" ("Lottery Fairy") has picked, you win.1

The code below has a player against the lottery. If the player loses it will output `0`, if the player wins it outputs `1`. As the distribution of a lose to win was still 1:5 I changed the rule, that at least one number must be picked by both the player and the lottery for a win. This results in an almost even distribution with slightly more wins.

```
function pick() {
    $numbers = [];
    for ($i = 0; $i < 6; ++$i) {
        $pick = mt_rand(1, 49);
        while(in_array($pick, $numbers)) {
            $pick = mt_rand(1, 49);
        }
        $numbers[] = $pick;
    }
    return $numbers;
}

$player = pick();
$lottery = pick();

print ( count(array_intersect($player, $lottery)) > 0 ? 1 : 0 ) . "\n";

```

That's a bit simplified, but the general idea.

# Answer
> 0 votes
# Lua,  ~~30~~  18 bytes

This answer is based on the same idea as muddyfish's answer.
In Lua order of elements in a table depends on hash, which is randomized per run.
We simply printing the first key in a table consisting of just '0' and '1':

```
$ lua -e "print(next{['0']='',['1']=''})"

```

---

**EDIT**:

Another version (length mod 2 of some unpredictably chosen global variable's name):

```
$ lua -e "print(#next(_G)%2)"

```

---
Tags: popularity-contest, random
---


# Question
Title: Print the lyrics to Caius' Theme (Final Fantasy XIII-2)
Print or return these lyrics:

```
Dea Mortis, iuravi
Carissimam servaturum.
Dea Mortis, servabo
Ut tempora recte ducam.

Etsi cor in Chaos,
Aut Fortuna bella ferat,
Occurram et obviam ibo.

```

The line break must be preserved, and trailing newlines are allowed.

**+20%** if you omit the end-of-line punctuation, **+30%** if you omit all punctuation, **+20%** if you change any capitalization, **-40%** if you also print the English translation right after the normal lyrics, separated by a blank line:

```
Goddess of Death, I vowed
That I would protect the most dear one.
Goddess of Death, I will protect her,
As I lead time straight.

Even if there is a heart in Chaos,
Or if Fortune may bring wars,
I will resist and go to fight against it.

```

If you print just the English version, add **+30%**.

And the actual song on YouTube.

Code-golf, so fewest bytes win.

# Answer
> 8 votes
# TeaScript, 123 + 1 = 124 bytes ~~142~~

+1 byte for "Safely handle unicode" checkbox

```
Ld`Dea MÆ³s, i¨avi
Càmm  rvÂxum.
Dea MÆ³s,  rva¾
Ut ÛZa c Ýóm.

Et£ ¬r  Cos,
A© FÆ·na Þ)a fÀ,
Occ¨m et obviam i¾.`

```

Try this in the interpreter. Make sure to check **"Safely handle unicode"** under options.

Pastebin because StackExchange messed up the special characters.

The compression algorithm used encodes similar items in the text rather than a simple base encoding. The general code is pretty simple though:

# Answer
> 4 votes
# Bubblegum, 116 bytes

```
00000000: 4d 4d b5 19 82 41 0c ed 33 c5 eb 91 19 f0 0a a9  MM...A..3.......
00000010: 18 20 77 fc 2e e1 8b dc fa 58 45 95 3c 3f 54 8c  . w......XE.<?T.
00000020: 8b a8 77 b6 44 17 ca a5 a3 3d 6b 67 d6 4d 3c c1  ..w.D....=kg.M<.
00000030: 2a 2d ec a1 31 ad e9 df f9 e3 93 d0 dd e1 d5 f4  *-..1...........
00000040: 14 65 68 95 bd c2 23 32 7f bc 74 74 eb 90 45 d1  .eh...#2..tt..E.
00000050: cd d8 b7 2c b6 a4 6d 38 4e 9f 7c cc 8c 54 8d 23  ...,..m8N.|..T.#
00000060: a3 ae 94 7d 49 b7 9c 43 f5 b3 56 39 24 95 ee f3  ...}I..C..V9$...
00000070: 75 49 d6 6f                                      uI.o

```

The above is a hexdump, which can be reversed with `xxd -r`.

I used zopfli for compression, which uses the DEFLATE format, but achieves a better compression ratio than gzip and zlib.

# Answer
> 3 votes
# JavaScript (ES6), 252 bytes

```
btoa`
æ2íÅÖêÚ¾&j¸¬²)k®öº»¦eÞic(®Ø¬]k®ö¡-Z×¦¦ÚZ·µå¹Æ¦e¶ÈrÖuª,].µah®Û§ifÞV}êÚµvqË«©zÕ¨nøh¡`.replace(/[W-Z=]/g,c=>` ,
.`["WXYZ".search(c)]||"")

```

Note the first newline is a carriage return.

## Hexdump:

```
00000000: 6274 6f61 600d c3a6 c296 32c2 8ac3 adc2  btoa`.....2.....
00000010: 8ac3 85c3 96c2 8ac3 aac3 9ac2 be26 026a  .............&.j
00000020: c2b8 c2ac c2b2 29c2 9ac2 996b 1ec2 aec3  ......)....k....
00000030: b6c2 adc2 bac2 bbc2 a665 c280 c39e 6963  .........e....ic
00000040: 28c2 aec3 98c2 ac5d 6b1e c2ae c3b6 c29b  (......]k.......
00000050: c2a1 c285 2d5a c397 c2a6 c2a6 c28a c39a  ....-Z..........
00000060: 5ac2 b7c2 9cc2 b5c3 a5c2 9dc2 b9c3 86c2  Z...............
00000070: a665 c286 04c2 b6c3 88c2 9672 c28a c396  .e.........r....
00000080: c28a 75c2 82c2 85c2 aa2c 5dc2 802e c2b5  ..u......,].....
00000090: 6168 c2ae c39b c2a7 6966 c39e c296 56c2  ah......if....V.
000000a0: 967d c3aa c39a c2b5 760e 71c3 8bc2 abc2  .}......v.q.....
000000b0: adc2 a9c2 967a c395 c2a8 6ec3 b8c2 9ac2  .....z....n.....
000000c0: 9968 c29b c2a1 c296 602e 7265 706c 6163  .h......`.replac
000000d0: 6528 2f5b 572d 5a3d 5d2f 672c 633d 3e60  e(/[W-Z=]/g,c=>`
000000e0: 202c 0a2e 605b 2257 5859 5a22 2e73 6561   ,..`["WXYZ".sea
000000f0: 7263 6828 6329 5d7c 7c22 2229            rch(c)]||"")

```

Edit: I found out that pasting into Firefox console changes carriage returns into line feeds. (Face-palm) Here is a whitespace safe version for two more bytes:

```
btoa`\ræ2íÅÖêÚ¾&j¸¬²)k®öº»¦eÞic(®Ø¬]k®ö¡-Z×¦¦ÚZ·µå¹Æ¦e¶ÈrÖuª,].µah®Û§ifÞV}êÚµvqË«©zÕ¨nøh¡`.replace(/[W-Z=]/g,c=>` ,\n.`["WXYZ".search(c)]||"")

```

# Answer
> 3 votes
# Stuck, 128 bytes

So riddled with unprintables I'm not going to even post the raw source code. Here's the hexdump instead:

```
0000000: 2278 da4d 8d41 0ec2 300c 04ef 79c5 3e20  "x.M.A..0...y.>
0000010: ea1f 500b 37c4 8907 38a9 1196 9a1a 3976  ..P.7...8.....9v
0000020: de4f c489 db68 35ab d998 7057 73e9 1912  .O...h5...pWs...
0000030: 4643 d24a 26bd 4ba3 86ce 36c8 c3a2 2d69  FC.J&.K...6...-i
0000040: fb33 7f7b d1f4 7438 b78f 1ac1 b83a 638f  .3.{..t8.....:c.
0000050: 4ad3 4d57 ef82 aa06 39b1 be49 7b4e 9770  J.MW....9..I{N.p
0000060: dce6 3f4e 42e1 e320 bcd8 c873 7ad4 1a66  ..?NB.. ...sz..f
0000070: b3c6 0e2d 4326 49d1 e50b 7fc1 35fe 2244  ...-C&I.....5."D

```

# Answer
> 2 votes
# Chaîne, ~~154~~ 148 bytes

(Linked interpreter currently only works properly on Firefox)

```
Dea Mortis, {<~}iuravi
Carissimam servaturum.
{}servabo
Ut tempora recte ducam.

Etsi cor in Chaos,
Aut Fortuna bella ferat,
Occurram et obviam ibo.

```

Doing the bonus doesn't grant me anything extra (229.2 bytes):

```
Dea Mortis, iuravi
Carissimam servaturum.
Dea Mortis, servabo
Ut tempora recte ducam.

Etsi cor in Chaos,
Aut Fortuna bella ferat,
Occurram et obviam ibo.

Goddess of Death, I :/E@:
That I :/eY: :*uk: the most dear one.
Goddess of Death, I will :*uk: her,
As I lead time :-Ep:.

Even if :.&L: is a heart in Chaos,
Or if :%u?: may bring wars,
I will :+XU: and to go to fight :5$: it.

```

---
Tags: code-golf, kolmogorov-complexity
---


# Question
Title: 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.

# Answer
# C

It's important to decide who is buying as quickly as possible, so as not to waste precious drinking time - hence **C** is the obvious choice in order to get maximum performance:

```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    const char *buyer;
    int n;

    srand(time(NULL)); // make sure we get a good random seed to make things fair !
    n = rand();
    switch (n % 5)
    {
        case 0: buyer = "John";
        case 1: buyer = "Jeff";
        case 2: buyer = "Emma";
        case 3: buyer = "Steve";
        case 4: buyer = "Julie";
    }
    printf("The person who is buying the drinks today is: %s !!!\n", buyer);
    return 0;
}

```

Explanation:

> This would work just fine if there was a `break;` after each case in the switch statement. As it stands however each case "falls through" to the next one, so poor Julie always ends up buying the drinks.
> 171 votes

# Answer
# PHP

Couldn't let this go, so here is another one:

```
$f = fopen('/dev/random','r');
$s = fread($f, 4);
fclose($f);

$names = ['John', 'Jeff', 'Emma', 'Steve', 'Julie'];

echo $names[$s % count($names)];

```

> This is actually not guaranteed to produce john, but chances are very good. PHP will happily take whatever /dev/random have to offer see that it (probably) can't parse it and come up with the very reasonable number 0 instead. After all, alerting the programmer to a potential error is considered a deadly sin in PHP.
> 164 votes

# Answer
# Haskell

It's too transparent if it always returns the same name so try the following

```
import Control.Monad
import System.Exit
import Control.Concurrent
import Control.Concurrent.MVar

data Person = John | Jeff | Emma | Steve | Julie deriving (Show, Enum)

next Julie = John
next p = succ p

rotate :: MVar Person -> IO ()
rotate mp = modifyMVar_ mp (return . next) >> rotate mp

main :: IO ()
main = do
    mp <- newMVar John
    forkIO $ rotate mp
    putStrLn "Shuffling"
    readMVar mp >>= print
    exitWith ExitSuccess

```

Whenever you want it to be random:

```
[~]$ runghc prog.hs
Shuffling
Steve

[~]$ runghc prog.hs
Shuffling
Julie

```

And for your unfortunate target:

```
[~]$ runhugs prog.hs
Shuffling
John

[~]$ runhugs prog.hs
Shuffling
John

```

> Hugs only implements cooperative multitasking, so the `rotate` thread will never run
> 85 votes

# Answer
# Bash - maximum simplicity

A very simple example - let's avoid any problems by doing it the textbook way. Don't forget to seed the generator from the system clock for a good result!

```
#!/bin/bash

names=(John Jeff Emma Steve Julie)   # Create an array with the list of names
RANDOM=$SECONDS                      # Seed the random generator with seconds since epoch
number=$((RANDOM % 5))               # Pick a number from 0 to 4
echo ${names[number]}                # Pick a name

```

> This relies on the user not knowing what the `$SECONDS` builtin actually does; it returns the number of seconds since the current shell started. As it's in a script, the shell always started zero seconds ago, so the generator is always seeded with `0` and Julie always buys the beer.

Bonus:

> This one stands up to scrutiny quite well; If you enter the same code on the commandline instead of in a script, it will give random results, because `$SECONDS` will return the length of time the user's interactive shell has been running.
> 73 votes

# Answer
## C#

```
using System;
using System.Linq;

namespace PCCG {
    class PCCG31836 {
        public static void Main() {
            var names = new string[]{ "John", "Jeff", "Emma", "Steve", "Julie" };
            var rng = new Random();
            names.OrderBy(name => rng.Next());
            Console.WriteLine(names[0]);
        }
    }
}

```

> This might not fool people who are familiar with the .Net API, but people who don't know it might believe that `OrderBy` modifies the object you call it on, and it's a plausible error for a newbie to the API to make.
> 57 votes

# Answer
## PowerShell

```
$names = @{0='John'; 1='Jeff'; 2='Emma'; 3='Steve'; 4='Julie'}
$id = random -maximum $names.Length
$names[$id]

```

This will always output `John`.

> `$names` is a `System.Collections.Hashtable` which doesn't have a `Length` property. Starting with PowerShell v3, `Length` (and also `Count`) can be used as a property on any object. If an object does not have the property, it will return `1` when the object is not null, else it will return `0`. So in my answer, `$names.Length` evaluates as 1, and `random -maximum 1` always returns 0 since the maximum is exclusive.
> 44 votes

# Answer
# Q

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

```

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

# Answer
# Perl

```
use strict;

my @people = qw/John Jeff Emma Steve Julie/;
my @index = int(rand() * 5);

print "Person @index is buying: $people[@index]\n";

```

> Prints: `Person X is buying: Jeff` (where X is from 0-4)
> Abusing scalar context a bit. `@index = int(rand() * 5)` places a random integer from 0 - 4 in the 0th position of the `@index` list. When printing the array, it properly prints the random integer in @index, but when using as an array index in `$people[@index]`, @index uses scalar context, giving it the value of the list size, i.e. `1`.
>
> Interestingly enough, `@people[@index]` makes it index properly.
>
> Interestingly enough `@people[@index]` is a hash slice in Perl, so `@index` is evaluated in the list context; in this case, it's a single entry list and that's why it works correctly
> 34 votes

# Answer
## ECMAScript

```
// Randomly pick a person on only one line!
var people = [('John', 'Jeff', 'Emma', 'Steve', 'Julie')];

console.log(people[new Date() % people.length | 0]);

```

It **always** picks Julie.

> It has brackets inside the square brackets, and the comma operator returns the value of its right operand.
> It's also very easy to miss. I've missed it before in **real** code.
> 23 votes

# 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.
> 20 votes

# Answer
## C#

```
var names = new string[] {"John", "Jeff", "Emma", "Steve", "Julie"};
var guidBasedSeed = BitConverter.ToInt32(new Guid().ToByteArray(), 0);
var prng = new Random(guidBasedSeed);
var rn = (int)prng.Next(0, names.Length);
Console.WriteLine(names[rn]);

```

Hint:

> Generate seed from GUID. Guids have 4 × 10−10 chance of collision. Super random.

Answer:

> At least when you use `Guid.NewGuid()`, whoops! (Sneaky way to make seed always 0). Also pointless (int) for misdirection.
> 18 votes

# Answer
# bash / coreutils

This is taken almost verbatim from a script I wrote for a similar purpose.

```
#!/bin/bash
# Sort names in random order and print the first
printf '%s\n' John Jeff Emma Steve Julie | sort -r | head -1

```

> Even forgetting to use an upper case R is a mistake I have occasionally made in real life scripts.
> 18 votes

# Answer
# Ruby

```
names = ["John", "Jeff", "Emma", "Steve", "Julie"]

puts names.sort{|x| rand()}.first

```

> This would work correctly with `sort_by`, but `sort` expects a comparison function that works like `<=>`. rand()'s result will always be positive, so it will always produce equivalent results provided your Ruby implementation's `sort` algorithm is deterministic. My Ruby 1.9.3 always outputs Julie.
> 16 votes

# Answer
# Ruby

```
names = ["John", "Jeff", "Emma", "Steve", "Julie"]

puts names[rand() % 5]

```

> `rand()` with no arguments produces a random float between 0 and 1. So modulo 5 does nothing, and when slicing into an array with a float argument Ruby just rounds it down, so this always returns John.
> 12 votes

# Answer
# Perl

three `srand`s will make it three times more random!

```
#!perl
use feature 'say';

sub random_person {
    my ($aref_people) = @_;
    srand; srand; srand;
    return $aref_people->[$RANDOM % scalar @$aref_people];
}

my @people = qw/John Jeff Emma Steve Julie/;
my $person = random_person(\@people);

say "$person makes next round of drinks!";

```

explanation

> there is no $RANDOM in perl, it's an undefined variable. the code will always return the first element from the list - drinks on John :)

edit:

after going through the code, one of the five guys has decided to fix the obvious error, producing the following program:

```
#!perl
use feature 'say';

sub random_person {
    my ($aref_people) = @_;
    return $aref_people->[rand $#$aref_people];
}

my @people = qw/John Jeff Emma Steve Julie/;
my $person = random_person(\@people);

say "$person buys next round of drinks!";

```

can you tell who did it just by looking at the code?

explanation:

> in Perl, `$#array` returns the index of last element; since arrays are zero-based, given a reference to an array with five elements, `$#$aref_people` will be `4`.
> `rand` returns a random number greater or equal to zero and less than its parameter, so it will never return `4`, which effectively means Julie will never buy drinks :)
> 11 votes

# Answer
# Python

Everybody knows that you can't trust randomness in such a small sample space; to make it truly random, I've abandoned the outdated method of picking a name from a list, and instead my program will spell out a completely random name. Since most of the names in the office had 4 letters, we'll settle for that.

```
import random

def CHR (n):
    # Just easily convert a number between 0 and 25 into a corresponding letter
    return chr(n+ord('A'))

# Seed the RNG with a large prime number. And multiply it by 2 for good measure.
random.seed (86117*2)

# Now, let's see what COMPLETELY RANDOM name will be spelled out!
totallyRandomName = ''
for i in range(4) :
    totallyRandomName += CHR(int(random.random()*26))

print (totallyRandomName)

```

> Naturally, I did some preparation work to make sure I pick the right seed.
> 10 votes

# Answer
# C

```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
char *name[]={"John", "Jeff", "Emma", "Steeve", "Julie"};

int i;
int n=rand()%10000;
int r=3;

for (i=0; i<10000+n; i++) // random number of iteration
    {
    r=(r*r)%10000; // my own PRNG (square and mod)
    }

printf("%s", name[r%5] );
}

```

Sorry, Jeff!

> After a few iteration r==1 mod 5, because of math. Morality : don't write your own PRNG if you're bad at math. :)
> 10 votes

# Answer
**C++x11**

```
#include <vector>
#include <iostream>

int main () {
  std::srand(time(NULL));
  std::vector<std::string> choice{("jen","moss","roy")};
  std::cout << choice[rand()%choice.size()] << std::endl;
}

```

> Size of vector is actually 1 due to the parenthesis used in the initializer list. Comma operator will discard all the names and return the last one, hence the buyer is always Roy.
> 10 votes

# Answer
## Scala

I know my users will be skeptical, so I have included a proof that my randomness is truly fair!

```
object DrinkChooser {

  def main(args: Array[String]): Unit = {
    proveRandomness()
    val names = List("John","Jeff","Emma","Steve","Julie")
    val buyer = names(randomChoice(names.size))
    println(s"$buyer will buy the drinks this time!")
  }

  def proveRandomness(): Unit = {
    val trials = 10000
    val n = 4
    val choices = for (_ <- 1 to 10000) yield randomChoice(n)
    (choices groupBy(identity)).toList.sortBy(_._1) foreach { case (a, x) =>
      println(a + " chosen " + (x.size * 100.0 / trials) + "%")
    }
  }

  def randomChoice(n: Int): Int = {
    var x = 1
    for (i <- 1 to 1000) { // don't trust random, add in more randomness!
      x = (x * randomInt(1, n)) % (n + 1)
    }
    x
  }

  // random int between min and max inclusive
  def randomInt(min: Int, max: Int) = {
    new scala.util.Random().nextInt(max - min + 1) + min
  }

}

```

One example run:

```
1 chosen 25.31%
2 chosen 24.46%
3 chosen 24.83%
4 chosen 25.4%
John will buy the drinks this time!

```

Unless someone else gets extremely lucky, John will always buy the drinks.

> The "proof" of randomness relies on the fact that `rand(1, 4) * rand(1, 4) % 5` is still evenly distributed between 1 and 4, inclusive. But `rand(1, 5) * rand(1, 5) % 6` is degenerate. There's the possibility you get a 0, which would then make the final result 0 regardless of the rest of the "randomness".
> 10 votes

# Answer
# 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
> 10 votes

# Answer
## JavaScript

Second try, this one's a little trickier:

```
var getRandomEntry = function(args){
    return args[Math.floor(Math.random() * arguments.length)];
}

alert(getRandomEntry(["peter","julie","samantha","eddie","mark"]));

```

> The `arguments` variable is locally accessible for functions and is an array of all arguments passed in to the function. By using simple naming and passing in an array to the function itself, you can spoof that we're not taking the length of the array, but in fact the length of the arguments list (which is 1). This can be even better executed by using special chars or a font type.
> 9 votes

# Answer
# C++

To be fair we should run many, many trials and pick whomever is selected the most often.

```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <map>

static const char *names[] = { "John", "Jeff", "Emma", "Steve", "Julie" };

int main() {
    srand(time(NULL));
    std::map<int, int> counts;

    // run 2^31 trials to ensure we eliminate any biases in rand()
    for (int i = 0; i < (1<<31); i++) {
        counts[rand() % (sizeof(names)/sizeof(*names))]++;
    }

    // pick the winner by whomever has the most random votes
    int winner = 0;
    for (std::map<int, int>::const_iterator iter = counts.begin(); iter != counts.end(); ++iter) {
        if (iter->second > counts[winner]) {
            winner = iter->first;
        }
    }

    printf("%s\n", names[winner % (sizeof(names)/sizeof(*names))]);
}

```

> What's the value of `1<<31`? Sorry, John.
> 8 votes

# Answer
# Lua

```
buyer={'John', 'Jeff', 'Emma', 'Steve', 'Julie'}
   -- use clock to set random seed
math.randomseed(os.clock())
   -- pick a random number between 1 and 5
i=math.random(5)
io.write("Today's buyer is ",buyer[i],".\n")

```

> `os.clock()` is for timing purposes, `os.time()` is what ought to be used with `math.randomseed` for good RNG. Sadly, Julie always buys (at least on my computer).
> 7 votes

# Answer
## T-SQL (2008+)

```
SELECT TOP 1 name
FROM
 (VALUES('John'),('Jeff'),('Emma'),('Steve'),('Julie')) tbl(name)
ORDER BY RAND()

```

Explanation:

> In MS SQL Server, `RAND()` only evaluates once per execution. Every name always gets assigned the same number, leaving the original ordering. John is first. Sucks for John.

Suggested improvement:

> T-SQL can produce decent quality, per-row random numbers with `RAND(CHECKSUM(NEWID()))`.
> 7 votes

# Answer
# Idiomatic C++11

When drinks are involved, it's especially important to be up to date with the latest standards and coding styles; this is a great example of a highly efficient and idiom-compliant C++11 name picker.

It is seeded from the system clock, and outputs the seed along with the name for verification each time.

```
#include <vector>
#include <chrono>
#include <random>
#include <iostream>

auto main()->int {
  std::vector<std::string> names;           // storage for the names
  names.reserve(5);                         // always reserve ahead, for top performance
  names.emplace_back("John");               // emplace instead of push to avoid copies
  names.emplace_back("Jeff");
  names.emplace_back("Emma");
  names.emplace_back("Steve");
  names.emplace_back("Julie");

  std::mt19937_64 engine;                   // make sure we use a high quality RNG engine
  auto seed((engine, std::chrono::system_clock::now().time_since_epoch().count()));  // seed from clock
  std::uniform_int_distribution<unsigned> dist(0, names.size() - 1);     // distribute linearly
  auto number(dist(engine));                // pick a number corresponding to a name
  std::string name(names.at(number));       // look up the name by number
  std::cout << "Seed: " << seed << ", name: " << name << std::endl;  // output the name & seed
  return EXIT_SUCCESS;                      // don't forget to exit politely
}

```

Try this live: http://ideone.com/KOet5H

> Ok so this actually is pretty good code overall; there are a lot of red herrings to make you look too closely at the code to notice the obvious - that the RNG is never actually seeded :) In this case `seed` is just an integer, and while it looks like `engine` is passed as a parameter to a seeding function, it's actually just ignored. The seed variable really is set from the clock, so it can be output at the end along with the name to add insult to injury, but it'll still always be Steve who buys the drinks.
> 6 votes

# Answer
# 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!
> 6 votes

# Answer
# Python

```
names=["John", "Jeff", "Emma", "Steve", "Julie"]
import random # Import random module
random.seed(str(random)) # Choose strictly random seed
print(random.choice(names)) # Print random choice

```

> str(random) gives a constant string; not a random value
> 5 votes

# Answer
# Perl

Emma had better not forget her purse! Runs under `strict` and `warnings`.

```
use strict;
use warnings;

# Use a hash to store names since they're more extendible

my %people;
$people{$_}++ for qw/John Jeff Emma Steve Julie/;

print +(@_=%people)[rand@_];  # 'cos (keys %people)[rand( keys %people )]
                              # is just too long-winded.

```

> Explanation here.
> 5 votes

# Answer
JavaScript

```
function getDrinksBuyer(){
    var people = ["Jeff", "Emma", "Steve", "Julie"];
    var rand = Math.random(0,4)|0;
    return people[rand];
}

```

> The `|0` results in 0 all the time but looks like it's doing some other rounding.
> 4 votes

# Answer
# J

```
;(?.5) { 'John'; 'Jeff'; 'Emma'; 'Steve'; 'Julie'

```

Poor Julie... Trivia: this might've been the cleanest J I've ever written...

> This code is actually correct, except for one thing. `?.` is the uniform rng: `?.5` will always return 4. `?5` would've been correct.
> 4 votes

# Answer
## 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 */ }
}

```
> 4 votes

# Answer
# 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.
> 4 votes

# Answer
# 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`.
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
## 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%.
> 3 votes

# Answer
# 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
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# 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.
> 2 votes

# Answer
# 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?
> 2 votes

# Answer
## 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... ;)
> 2 votes

# Answer
## 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.
> 2 votes

# Answer
# Atari BASIC

It generates a random number `R`, and then `READ`s 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))`.
> 2 votes

# Answer
# 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?
> 2 votes

# Answer
# 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.
> 1 votes

# Answer
# 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(?).
> 1 votes

# Answer
## 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
>             }
>         }
>     }
>
> ```
> 1 votes

# Answer
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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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**.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
## 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!
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
Ozone

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

```

The trick is in "+2n2".
> 0 votes

# Answer
# 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'.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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 :)
> 0 votes

# Answer
# 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
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
**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
> -1 votes

# Answer
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.
> -3 votes

---
Tags: popularity-contest, random, underhanded
---


title: Cave Rangers - Exploring the Darkness

text:
# Question
Title: Cave Rangers - Exploring the Darkness
Your geologist buddy nearly kicked down your office door as he burst in, eyes wide in excitement, and asked you to come with him to a site he just discovered. On the way he explains that he thinks he literally just struck gold. Only problem is, it's buried deep underground in a cavern with a very unstable roof. It's too dangerous to go spelunking, so he wants you to program one of his cave exploring robots to collect as much gold as it can before he pulls it back up. He also mentions that he's probed the cavern and found some wildlife that could be harmful to the robots, and also that he'd dropped some equipment down there that might still be useable. Each robot is equipped with two arms and a range of sensors. When you arrive at the scene, he tells you he's planning on recruiting more coders, and whoever does the best job will be rewarded.

Now, down to the nitty-gritty. The sensors pass information to your program as ASCII characters. Here's a list of what each character means and descriptions for anything the bot might encounter in the cave:

```
Code    Name/Description

Y       Your bot
        You do things

@       Other bots
        They do other things

-       Ground
        This doesn't do things

C       Centipede
        These will bite you and leave a poison effect
        The bite will cost 1 health
        The poison effect will last for 3 turns, costing 2 health each turn

B       Bats
        If bats end up in the same space you are, your bot runs in a random direction during its turn rather than what you told it to do

L       Lion (because reasons)
        Lions deal heavy damage, 10 health, each time they attack

F       Food
        Eating this will give you 5 health
        Can only be used once

W       Water
        Drinking this will cure poison effects early
        Can only be used once

R       Revealer
        This will increase the range of your visibility to an 11x11 grid
        The extra range will only be 75% correct, but the original range won't be effected

K       Knife
        You do twice as much damage to other bots if you have a knife

G       Gold
        The whole reason you're doing this in the first place

N       Nurse Nina
        She mend you good
        Restores your health by 10 while you occupy the same space as her

}       Boulder
        You can't walk over boulders, and neither can anything else

P       Pit
        If you fall in a pit, you will be stuck for 3 turns

```

The size of the cavern grows based on how many bots are participating. It starts as a 30x30, and it gets an extra 10x10 for every bot. So 2 bots will explore a 50x50 cavern.

Bots start with 20 health, but they don't have a maximum limit on health.

**Input:**

You'll receive input through STDIN in the following format:

```
20,5,10,1,0,True,False    <-health, number gold pieces, number of turns your bot has lasted, number of until the poison wears off, number of turns until you are no longer stuck in a pit, if you have a revealer, if you have a knife
-----
-G}--
--Y-L
-C---
---B-

```

The first line contains information about your bot, and the rest is the grid that your bot can see. If your bot is against one of the 4 walls of the cavern, you will get a grid that looks more like this (in the case of being all the way to the West):

```
---
}--
Y--
---
---

```

The cavern does not wrap around, and neither does your vision. The walls of the cavern are not marked, the only indication your bot receives that it is nearing a wall is its view being diminished. With the Revealer, you might get something like this:

```
--------C--
LW--------B
---K-N-----
--------BR-
-F---------
--B--Y---@N
-W@---F----
------K-F--
----@-}----
R@---G}--}-
--------G-R

```

**Output:**

You get two moves per turn, which you output in the following format:

```
MNNANW    <- Moves are groups of 3 characters representing the action and the direction

```

Possible actions are the following:

```
M    Move - Move your bot in the specified direction
A    Attack - Attack the square in the specified direction
H    Hold - Do nothing

```

Possible directions are the following:

```
NN - North (up)
NE - Northeast (up-right)
EE - East (right)
SE - Southeast (down-right)
SS - South
SW - Southwest
WW - West
NW - Northwest

```

The moves are applied from left to right.

**Turns:**

Turns progress in the following fashion:

1. Poison effects are applied to any player who has been poisoned
2. Non-bots move and attack

2a. Lions, Centipedes, and Bats move randomly

2b. Lions and Centipedes will attack everything that is directly adjacent to it (including diagonally)

2c. The bat effect will only be applied to a bot if it is on the same space as the bat

2d. Nurse Nina will stay in a location for 3 turns, and then jump to a random location.
3. Bots move

3a. If your bot gives invalid output, it won't move

3b. Your bot will try to get as close to the space designated by the output as possible (see the note at the bottom for more detail)

3c. One attack to a Centipede, Lion, or Bat will kill it

3d. Attacking another bot without a knife will do 5 damage, and 10 with a knife

**Rules:**

1. Stick to common languages that can be run on OS X or Linux.
2. You can optionally write up to and not exceeding 1kb data to a file

**Scoring:**

Bots will only be in the cavern until only one remains, or until 50 turns have gone by, whichever comes first. Your bot will be judged on the sum of the number of gold coins it collected and how many turns it lasted.

Controller code can be downloaded for testing here (make a folder called "bots" in the same directory that you download it to, and put your bot inside "bots") You'll need NumPy to run it. Feel free to dig through it, but you'll have to excuse the mess...

Here's some code for a random bot:

```
#!/usr/bin/python
import random as r

a = ['M','A','H']
d = ['NN','NE','EE','SE','SS','SW','WW','NW']

print(a[r.randint(0,2)]+d[r.randint(0,7)]+a[r.randint(0,2)]+d[r.randint(0,7)])

```

\****Your bot will always move in the general direction your output specifies, but if it is obstructed by a rock or a wall, the exact direction depends on the circumstance. For instance, if your bot is against a wall like so:

```
---
}--
Y--
---
---

```

and your output is

```
MNWMSW

```

your bot will move one space down. It couldn't move North or West, so that move had no effect. It could move South (and did) but couldn't move West. However, if your bot tried to move Northeast, it would go directly to that space (diagonal movement is diagonal, not procedural)

**Leaderboard**

These are the average scores of 4 games.

```
The bot of Survival:    54.75
Coward:                 52.25
Pufferfish:             50.00
Randombot:              50.00
Indiana Jones:          47.50
TheoremBot:             46.50

```

# Answer
> 4 votes
# Indiana Jones, Python 2

This bot is not afraid of anything. It will try to get the gold; and if it can't find any, it will try to stab opponents with knives.

```
#!/usr/bin/env python
import sys
import random
data = sys.stdin.readlines()
health, gold, turns, poison_remaining, pit_remaining, revealer, knife = eval(data[0])
lines = data[1:]

myloc = [-1, -1]

width, height = len(lines[0]), len(lines)

for y, line in enumerate(lines):
    if line.find('Y')>-1:
        myloc = [line.index('Y'), y]
if myloc[0]<width/2:
    padding = int(width/2-myloc[0])
    lines = ['-'*padding+line for line in lines]
    myloc[0]+=padding
elif myloc[0]>width/2+1:
    padding = int(myloc[0]-width/2-1)
    lines = [line+'-'*padding for line in lines]

if myloc[1]<height/2:
    padding = int(height/2-myloc[1])
    lines = ['-'*width]*padding + lines
    myloc[1]+=padding
elif myloc[1]>height/2+1:
    padding = int(myloc[1]-height/2-1)
    lines = lines + ['-'*width]*padding

uddirections = {1:'N',0:'',-1:'S'}
lrdirections = {1:'E',0:'',-1:'W'}

golds = {}
for y, line in enumerate(lines):
    if 'G' in line:
        x = line.index('G')
        direction = ((uddirections[max(min(myloc[1]-y,1),-1)]+lrdirections[max(min(x-myloc[0],1),-1)])*2)[:2]
        distance = max(abs(myloc[0]-x), abs(myloc[1]-y))
        golds[distance] = direction

bots = {}
for y, line in enumerate(lines):
    if '@' in line:
        x = line.index('@')
        direction = ((uddirections[max(min(myloc[1]-y,1),-1)]+lrdirections[max(min(x-myloc[0],1),-1)])*2)[:2]
        distance = max(abs(myloc[0]-x), abs(myloc[1]-y))
        bots[distance] = direction

foods = {}
for y, line in enumerate(lines):
    if 'F' in line:
        x = line.index('F')
        direction = ((uddirections[max(min(myloc[1]-y,1),-1)]+lrdirections[max(min(x-myloc[0],1),-1)])*2)[:2]
        distance = max(abs(myloc[0]-x), abs(myloc[1]-y))
        foods[distance] = direction

knives = {}
for y, line in enumerate(lines):
    if 'K' in line:
        x = line.index('K')
        direction = ((uddirections[max(min(myloc[1]-y,1),-1)]+lrdirections[max(min(x-myloc[0],1),-1)])*2)[:2]
        distance = max(abs(myloc[0]-x), abs(myloc[1]-y))
        knives[distance] = direction

if golds:
    direction = golds[min(golds.keys())]
elif not knife and knives:
    direction = knives[min(knives.keys())]
elif health<20 and foods:
    direction = foods[min(foods.keys())]
elif bots and knife:
    direction = bots[min(bots.keys())]
    if min(bots.keys())==1:
        print ('A'+direction)*2
        sys.exit(0)
    elif min(bots.keys())==2:
        print 'M'+direction+'A'+direction
        sys.exit(0)
else:
    print ('M'+random.choice('NS')+random.choice('NEWS'))*2
    sys.exit(0)
print ('M'+direction)*2

```

# Answer
> 3 votes
## The bot of survival - Python 2

```
from __future__ import print_function
health,gold,survived,poison,pit,revealer,knife = input()
if pit:
    exit()
#Yes, this is python 2, despite the use of input()
lines = []
try:
    while True:
        lines.append(raw_input())
except EOFError:
    pass
CMOVES={"NW":(-1,-1),"NN":(-1,+0),"NE":(-1,+1),
        "WW":(+0,-1),             "EE":(-0,+1),
    "SW":(+1,-1),"SS":(+1,+0),"SE":(+1,+1),
}
MOVES={v:k for k,v in CMOVES.iteritems()}
import sys
def get_your_pos():
    for row,line in enumerate(lines):
        for col,square in enumerate(line):
            if square == "Y":
                return row,col
    raise ValueError("Your bot is not present.")
def isnearby(thing,p=None):
    your_pos = p or get_your_pos()
    for move in MOVES:
        yp = your_pos[0]+move[0],your_pos[1]+move[1]
        try:
            if yp[0] >= 0 and yp[1] >= 0 and lines[yp[0]][yp[1]] == thing:
                return move
        except IndexError:
            #Edge of cavern
            pass
for turn in range(2):
    import random
    nprio = .5
    if health > 25:
        nprio -= .2
    elif health < 10:
        nprio += .3
    if poison:
        nprio += .18
    #heal
    motive = how = None
    if random.random() < nprio:
        nurse = isnearby("N")
        if nurse:
            motive = "M"
            how = MOVES[nurse]
        elif random.random() < nprio:
            food = isnearby("F")
            if food:
                motive = "M"
                how = MOVES[food]
    #cure poison
    if poison and not motive:
        water = isnearby("W")
        if water:
            motive = "M"
            how = MOVES[water]
    if not motive:
        #Kill lions, bats, and centipedes
        for animal in ("L","B","C"):
            animal = isnearby(animal)
            if animal:
                motive = "A"
                how = MOVES[animal]
                y = get_your_pos()
                y = y[0]+animal[0],y[1]+animal[1]
                lines = map(list,lines)
                lines[y[0]][y[1]] = "-"
                break
        else:
            #Pick up knives
            if not knife:
                knife = isnearby("K")
                if knife:
                    motive = "M"
                    how = MOVES[knife]
            #Attack other bots
            else:
                prey = isnearby("@")
                if prey:
                    motive = "A"
                    how = MOVES[prey]
    #Get gold
    gold = isnearby("G")
    if gold and not motive:
        motive = "M"
        how = MOVES[gold]
    def isvalidmove(c):
        c = CMOVES[c]
        y = get_your_pos()
        y=(y[0]+c[0],y[1]+c[1])
        if y[0] >= 0 and y[1] >= 0:
            try:
                lines[y[0]][y[1]]
            except LookupError:
                pass
            else:
                return True
    if turn and not motive:
        motive = "M"
        while not (how and how not in (isnearby("}"),isnearby("P"),isnearby("@"))\
              and isvalidmove(how)):
            how = random.choice(CMOVES.keys())
    if not motive:break
    if not turn and motive == "M":
        lines = map(list,lines)
        yp = get_your_pos()
        lines[yp[0]][yp[1]] = "-"
        yp=[yp[0]+CMOVES[how][0],yp[1]+CMOVES[how][1]]
        lines[yp[0]][yp[1]] = "Y"
    print(motive+how,end="")
else:
    exit()
#Nothing found on first move
def isvaguelynearby(thing):
    your_pos = get_your_pos()
    for move in MOVES:
        yp = your_pos[0]+move[0],your_pos[1]+move[1]
        try:
            if yp[0] >= 0 and yp[1] >= 0 and board[yp[0]][yp[1]] != "P":
                dest = isnearby(thing,yp)
                if dest:
                    return move,dest
        except IndexError:
            #Edge of cavern
            pass
if random.random() < nprio:
    dests = isvaguelynearby("N")
    if not dests and random.random() < nprio:
        dests = isvaguelynearby("F")
    if dests:
        m1,m2 = MOVES[dests[0]],MOVES[dests[1]]
        print("M" + m1 + "M" + m2)
        exit()
dests = (poison and isvaguelynearby("W")) or (not knife and isvaguelynearby("K"))\
    or isvaguelynearby("G")
prey = isvaguelynearby("L") or isvaguelynearby("B") or isvaguelynearby("C") or \
       (knife and isvaguelynearby("@"))
if dests:
    m1,m2 = MOVES[dests[0]],MOVES[dests[1]]
    print("M" + m1 + "M" + m2)
elif prey:
    m1,m2 = MOVES[prey[0]],MOVES[prey[1]]
    print("M" + m1 + "A" + m2)
else:
    how = None
    while not (how and how not in     (isnearby("}"),isnearby("P"),isnearby("@"))\
          and isvalidmove(how)):
        how = random.choice(CMOVES.keys())
    print("M"+how,end="")
    lines = map(list,lines)
    yp = get_your_pos()
    lines[yp[0]][yp[1]] = "-"
    yp=[yp[0]+CMOVES[how][0],yp[1]+CMOVES[how][1]]
    lines[yp[0]][yp[1]] = "Y"
    while not (how and how not in (isnearby("}"),isnearby("P"),isnearby("@"))\
          and isvalidmove(how)):
            how = random.choice(CMOVES.keys())
    print("M"+how)

```

Edit: added better pit avoidance.

# Answer
> 3 votes
# Coward, python3

A coward always runs from potential threats.

However, if he feels super strong, he will suddenly run amok and stab everything near him.

The problem with the current implementation is that move commands are issued without knowledge whether it is the first or the second move.

```
#!/usr/bin/env python3.4

import sys, random

class Coward():
  """
  A coward always runs from potential threats.

  However, if he feels super strong, he will suddenly run amok
  and stab everything near him.
  """
  def __init__(self, hp, gold, turn, poison, pit, revealer, knife):
    self.hp=int(hp)
    self.gold=int(gold)
    if knife=="True": self.knife=True
    else: self.knife=False
    self.pit=int(pit)
    self.poison=int(poison)

  def readGrid(self, grid):
    self.grid=grid.split("\n")
  @property
  def _confidence(self):
    return self.hp+5*self.knife-2*self.poison
  @property
  def _lineOfY(self):
    for i, line in enumerate(self.grid):
      if "Y" in line:
        return i
  @property
  def _colOfY(self):
    return self.grid[self._lineOfY].index("Y")
  @property
  def _maxX(self):
    return len(self.grid)-1
  @property
  def _maxY(self):
    return len(self.grid[0])-1
  def move(self, step):
    d = {'NN':(0,-1),'NE':(1,-1),'EE':(1,0),'SE':(1,1),'SS':(0,1),'SW':(-1,1),'WW':(-1,0),'NW':(-1,-1)}
    c2d={(0,-1):'NN',(1,-1):'NE',(1,0):"EE",(1,1):"SE",(0,1):"SS",(-1,1):"SW",(-1,0):"WW",(-1,-1):"NW"}
    #Don't move into wall/ boulder/ pit
    #print(d, file=sys.stderr)
    for k,v in list(d.items()):
      x=self._lineOfY+v[0]
      y=self._colOfY+v[1]
      #print (k, v ,x , y, file=sys.stderr)
      if x<0 or y<0 or x>self._maxX or y>self._maxY:
        #print ("Out of bounds: ", k, file=sys.stderr)
        del d[k]
      elif self.grid[x][y]=="}" or self.grid[x][y]=="P":
        del d[k]
    #Always avoid bats, and enemys
    for dx in range(-2,3):
      for dy in range(-2,3):
        x=self._lineOfY+dx
        y=self._colOfY+dy
        if x<0 or y<0 or x>self._maxX or y>self._maxY:
          continue;
        if self.grid[x][y] in ["B", "L", "C", "@"]:
          for k in self._toDirection(dx, dy):
            if k in d: del d[k] #Too many threats from all sides can paralyze the Coward: nowhere to go...
    #print(d, file=sys.stderr)
    tomove=[]
    #Neighboring fields
    for dx in [-1,1]:
      for dy in [-1,1]:
        x=self._lineOfY+dx
        y=self._colOfY+dy
        if x<0 or y<0 or x>self._maxX or y>self._maxY:
          continue
        if self.poison>0 and self.grid[x][y]=="W":
          for k,v in d.items():
            if v==(dx,dy):
              tomove.append(k)
        if self.grid[x][y]=="N": #Always go to nurse, even if dangerous
          tomove.append(c2d[(x,y)])
        if self.grid[x][y] in ["F","K","G"]: #Go to Food, Knife or Gold, if save
          for k,v in d.items():
            if v==(dx,dy):
              tomove.append(k)
    #Further away: Go towards food, knife and gold and Nina if save.
    for target in ["N", "F", "G", "K"]:
      for dx in [-2,2]:
        for dy in [-2,2]:
          x=self._lineOfY+dx
          y=self._colOfY+dy
          if x<0 or y<0 or x>self._maxX or y>self._maxY:
            continue
          if self.grid[x][y]==target:
            l=[ k for k in self._toDirection(dx,dy) if k in d]
            if l: tomove.append(random.choice(l))
    s=list(d.keys())
    random.shuffle(s)
    tomove+=s
    try:
      return "M"+tomove[step-1]
    except IndexError:
      return ""
  def attack(self, step):
    c2d={(0,-1):'NN',(1,-1):'NE',(1,0):"EE",(1,1):"SE",(0,1):"SS",(-1,1):"SW",(-1,0):"WW",(-1,-1):"NW"}
    #If Bot next to you: always attack
    for k,v in c2d.items():
      x=self._lineOfY+k[0]
      y=self._colOfY+k[1]
      if x<0 or y<0 or x>self._maxX or y>self._maxY:
        continue
      if self.grid[x][y]=="@":
        return "A"+v
    #If Bot or monster could come closer: attack potential new position
    attDir={(-2,-2):["NW"], (-2,-1):["NW","WW"], (-2,0):["WW","NW","SW"], (-2,1):["WW","SW"], (-2,2):["SW"],(-1,-2):["NW","NN"], (-1,2):["SW","SS"], (0,2):["SW","SS","SE"],(0,-2):["NW","NN","NE"],(1,-2):["NN","NE"],(1,2):["SS","SE"],(2,-2):["NE"],(2,-1):["NE","EE"], (2,0):["NE","EE","SE"], (2,1):["EE","SE"], (2,2):["SE"]}
    for k,v in attDir.items():
      x=self._lineOfY+k[0]
      y=self._colOfY+k[1]
      if x<0 or y<0 or x>self._maxX or y>self._maxY:
        continue
      if self.grid[x][y] in ["@","L","C","B"]:
        return "A"+random.choice(v)
    return ""
  def _toDirection(self,dx,dy):
    if dx<0:
      if dy<0:
        return ["WW","NW","NN"]
      elif dy==0:
        return ["WW","NW","SW"]
      elif dy>0:
        return ["WW","SW","SS"]
    elif dx>0:
      if dy<0:
        return ["EE","NE","NN"]
      elif dy==0:
        return ["EE","NE","SE"]
      elif dy>0:
        return ["EE","SE","SS"]
    elif dx==0:
      if dy<0:
        return ["NN","NE","NW"]
      elif dy==0:
        return []
      elif dy>0:
        return ["SS","SE","SW"]
  def _nearBat(self):
    for dx in range(-2,3):
      for dy in range(-2,3):
        x=self._lineOfY+dx
        y=self._colOfY+dy
        if x<0 or y<0:
          continue;
        if self.grid[x][y]=="B":
          return True
    return False
  def makeTurn(self):
    try:
      command=""
      #If stuck, just attack
      if self.pit:
        command+=self.attack(1)+self.attack(2)
      #Always run from bats
      if self._nearBat:
        command+=self.move(1)+self.move(2)
      #If high-confidence: attack
      if self._confidence>30:
        command+=self.attack(1)+self.attack(2)
      #Else: Move somewhere
      command+=self.move(1)+self.move(2)
      #Just in case, two random attacks
      d = ['NN','NE','EE','SE','SS','SW','WW','NW']
      a=random.choice(d)
      b=random.choice([ x for x in d if x!=a])
      command+="A"+a+"A"+b
      return command[:6]
    except Exception as e:
      #print (e, file=sys.stderr)
      #Attacking is better than nothing
      d = ['NN','NE','EE','SE','SS','SW','WW','NW']
      a=random.choice(d)
      b=random.choice([ x for x in d if x!=a])
      return "A"+a+"A"+b

info=sys.stdin.readline()
grid=sys.stdin.read()
info=info.split(",")
bot=Coward(*info)
bot.readGrid(grid)
t=bot.makeTurn()
#print(t, file=sys.stderr)
print(t)

```

# Answer
> 2 votes
# Pufferfish, Python 3+

I'm just that person.

```
#!/usr/bin/env python3.4
import random
def select():
 return "A"+["NN","NE","EE","SE","SS","SW","WW","NW"][random.randint(0,7)]
print(select()+select())

```

---
Tags: king-of-the-hill
---


title: Remove repeated words from a string

text:
# Question
Title: Remove repeated words from a string
Remove all repeating words from an inputted sentence.

Input will be something like `cat dog cat dog bird dog Snake snake Snake` and the output should be `cat dog bird Snake snake`. There will always be a single space separating words.

Output order must be the same as input. (Refer to the example)

You don't need to handle punctuation but capital letter handling is required.

# Answer
> 1 votes
# gs2, 3 bytes

```
,É-

```

Encoded in CP437.

STDIN is pushed at the start of the program. `,` splits it over spaces. `É` is `uniq`, which filters duplicates. `-` joins by spaces.

# Answer
> 9 votes
## CJam, 7 chars

```
qS/_&S*

```

Can probably be much shorter... but whatever I've almost never used CJam. ^.^

`q` reads input, `S/` splits on spaces, `_&` duplicates and applies a setwise AND (therefore getting rid of duplicates), and `S*` re-joins on space.

Online interpreter link

# Answer
> 8 votes
# Haskell, 34 bytes

```
import Data.List
unwords.nub.words

```

Usage example: `(unwords.nub.words) "cat dog cat dog bird dog Snake snake Snake"` -\> `"cat dog bird Snake snake"`.

# Answer
> 8 votes
# APL, ~~22~~ 20 bytes

```
{1↓∊∪(∊∘' '⊂⊢)' ',⍵}

```

This creates an unnamed monadic function that accepts a string on the right and returns a string.

Explanation:

```
               ' ',⍵}    ⍝ Prepend a space to the input string
     (∊∘' '⊂⊢)          ⍝ Split the string on spaces using a fork
    ∪                    ⍝ Select the unique elements
{1↓∊                     ⍝ Join into a string and drop the leading space

```

Try it online

Saved 2 bytes thanks to Dennis!

# Answer
> 7 votes
## Ruby, 21 chars

```
->s{s.split.uniq*' '}

```

# Answer
> 7 votes
# JavaScript (ES6) 33

(see this answer)

Test running the snippet below in an EcmaScript 6 compliant browser (implementing Set, spread operator, template strings and arrow functions - I use Firefox).

Note: the conversion to Set drop all the duplicates *and* Set mantains the original ordering.

```
f=s=>[...Set(s.split` `)].join` `

function test() { O.innerHTML=f(I.value) }

test()
```

```
#I { width: 70% }
```

```
<input id=I value="cat dog cat dog bird dog Snake snake Snake"/><button onclick="test()">-></button>
<pre id=O></pre>
```

# Answer
> 6 votes
# TeaScript, 12 bytes

TeaScript is JavaScript for golfing.

```
xs` `u()j` `

```

This is pretty short. It splits on each space, filters out duplicates, then rejoins.

Try it online

# Answer
> 5 votes
# PowerShell, 15 Bytes

```
$args|select -u

```

Whoa, an actual entry where PowerShell is somewhat competitive? That's unpossible!

Takes the string as input arguments, pipes to `Select-Object` with the `-Unique` flag. Spits out an array of strings, preserving order and capitalization as requested.

### Usage:

```
PS C:\Tools\Scripts\golfing> .\remove-repeated-words-from-string.ps1 cat dog cat dog bird dog Snake snake Snake
cat
dog
bird
Snake
snake

```

---

If this is too "cheaty" in assuming the input can be as command-line arguments, then go for the following, at **~~24~~ 21 Bytes** <sub>(saved some bytes thanks to blabb)</sub>. Interestingly, using the unary operator in *this* direction happens to also work if the input string is demarcated with quotes *or* as individual arguments, since the default `-split` is by spaces. Bonus.

```
-split$args|select -u

```

# Answer
> 4 votes
# Julia, 29 bytes

```
s->join(unique(split(s))," ")

```

This creates an unnamed function that splits the string into a vector on spaces, keeps only the unique elements (preserving order), and joins the array back into a string with spaces.

# Answer
> 4 votes
# R, 22 bytes

```
cat(unique(scan(,"")))

```

This reads a string from STDIN and splits it into a vector on spaces using `scan(,"")`, selects only unique elements, then concatenates them into a string and prints it to STDOUT using `cat`.

# Answer
> 4 votes
# Retina, 22 bytes

```
 (\w+)\b(?<=\b\1\b.+)

```

Save the file with a trailing linefeed and run it with the `-s` flag.

This is fairly straight forward in that it matches a single word, and the lookbehind checks whether that same word has appeared in the string before. The trailing linefeed causes Retina to work in Replace mode with an empty replacement string, removing all matches.

# Answer
> 4 votes
# Mathematica, ~~43~~ 39 bytes

```
StringRiffle@*Keys@*Counts@*StringSplit

```

# Answer
> 3 votes
# Pyth - 9 bytes

Well this is why we're all waiting for Pyth5, could have been 5 bytes.

```
jdoxzN{cz

```

Try it online here.

# Answer
> 3 votes
## C++11, 291 bytes

```
#include<iostream>
#include<string>
#include<list>
#include<sstream>
#include<algorithm>
using namespace std;main(){string s;getline(cin,s);list<string>m;stringstream b(s);while(getline(b,s,' '))if(find(m.begin(),m.end(),s)==m.end())m.push_back(s);for(auto a:m)cout<<a<<' ';cout<<endl;}

```

I don't see a whole lot of C++ answers compared to golfing languages, so why not. Note that this uses C++11 features, and so if your compiler is ~~stuck in the dark ages~~ sufficiently old enough, you may need to pass a special compilation switch to make it use the C++11 standard. For `g++`, it's `-std=c++11` (only needed for versions \< 5.2). Try it online

# Answer
> 3 votes
# K5, 9 bytes

```
" "/?" "\

```

FYI, this is a function.

## Explanation

```
     " "\    Split the input on spaces
    ?        Find all the unique elements
" "/         Join them back together

```

# Answer
> 2 votes
# Matlab: 18 Bytes

```
unique(d,'stable')

```

where `d` is `d = {'cat','dog','cat','dog','bird','dog','Snake','snake','Snake'}`.

The result is `'cat' 'dog' 'bird' 'Snake' 'snake'`

# Answer
> 2 votes
## Python 3, 55

```
l=[]
for x in input().split():l+=[x][x in l:]
print(*l)

```

Yeesh, this is long. Unfortunately, Python's `set` doesn't keep the order of the elements, so we have to do the work ourselves. We iterate through the input words, keeping a list `l` of elements that aren't yet in `l`. Then, we print the contents of `l` space-separated.

A string version of `l` would not work if some words are substrings of other words.

# Answer
> 2 votes
# C#, 38 bytes

```
String.Join(" ",s.Split().Distinct());

```

# Answer
> 2 votes
## Perl 6, 14 bytes

As a whole program the only way you would write it is 21 bytes long

```
say $*IN.words.unique # 21 bytes

```

---

As a lambda expression the shortest is 14 bytes

```
*.words.unique # 14 bytes

```

```
say ( *.words.unique ).('cat dog cat dog bird dog Snake snake Snake')

my &foo = *.words.unique;
say foo $*IN;

```

While the output is a List, if you put it in a stringifying context it will put a space between the elements. If it was a requirement to return a string you could just add a `~` to the front `~*.words.unique`.

---

If snippets were allowed, you could shorten it to 13 bytes by removing the `*`.

```
$_ = 'cat dog cat dog bird dog Snake snake Snake';

say .words.unique

```

# Answer
> 1 votes
## Python 3, ~~87~~ 80 bytes

*turns out the full program version is shorter*

```
s=input().split(' ')
print(' '.join(e for i,e in enumerate(s)if e not in s[:i]))

```

Did it without regex, I am happy

Try it online

# Answer
> 1 votes
# Lua, 94 bytes

```
function c(a)l={}return a:gsub("%S+",function(b)if l[b]then return""else l[b]=true end end)end

```

# Answer
> 1 votes
# awk, 25

```
BEGIN{RS=ORS=" "}!c[$0]++

```

### Output:

```
$ printf "cat dog cat dog bird dog Snake snake Snake" | awk 'BEGIN{RS=ORS=" "}!c[$0]++'
cat dog bird Snake snake $
$

```

# Answer
> 1 votes
# Scala, ~~44~~ 47 bytes

```
(s:String)=>s.split(" ").distinct.mkString(" ")

```

**EDIT**: using `toSet` might not preserve order, so I'm now using distinct // that just cost me 3 bytes :(

# Answer
> 1 votes
# JavaScript, 106 102 100 bytes

```
function(s){o={};s.split(' ').map(function(w){o[w]=1});a=[];for(w in o)a.push(w);return a.join(' ')}

```

// way too long for JS :(

# Answer
> 1 votes
# PHP ~~64~~ 59 bytes

```
function r($i){echo join(" ",array_unique(split(" ",$i)));}

```

# Answer
> 1 votes
# Hassium, 91 bytes

```
func main(){d=[]foreach(w in input().split(' '))if(!(d.contains(w))){d.add(w)print(w+" ")}}

```

Run online and see expanded here

# Answer
> 1 votes
# AppleScript, 162 bytes

Interestingly, this is almost identical to the non-repeating characters thing.

```
set x to(display dialog""default answer"")'s text returned's words
set o to""
repeat with i in x
considering case
if not i is in o then set o to o&i&" "
end
end
o
```

I didn't actually know the considering keyword before this. *the more you know...*

# Answer
> 1 votes
## Burlesque, 6 bytes

```
blsq ) "cat dog cat dog bird dog Snake snake Snake"wdNBwD
cat dog bird Snake snake

```

Rather simple: split words, nub (nub = remove duplicates), convert back to words.

# Answer
> 1 votes
# Gema, 21 characters

```
*\S=${$0;$0}@set{$0;}

```

(Very similar to the unique character solution, as there are no arrays in Gema, so allowing built-in unique functions not helps us much.)

Sample run:

```
bash-4.3$ gema '*\S=${$0;$0}@set{$0;}' <<< 'cat dog cat dog bird dog Snake snake Snake'
cat dog bird Snake snake

```

# Answer
> 0 votes
# PHP, 37 Bytes

*Assuming `$s` is the input string.*

```
print_r(array_flip(explode(' ',$s)));

```

# Answer
> 0 votes
## Ruby, 24 bytes

Similar to Doorknob's answer, just a full program.

```
puts gets.split.uniq*' '

puts                     print
     gets.split          split input by space
               .uniq     make each element unique
                    *' ' join with spaces

```

# Answer
> -1 votes
# C#, 909 bytes

```
class Dictionary
{
    public Dictionary<int, string> InsertWordsIntoDictionary(string userInput)
    {
        Dictionary<int, string> newWords = new Dictionary<int, string>();
        int a = 0;
        int b = 1;

        userInput = userInput.Insert(userInput.Length, " ");

        for (int i = 0; i < userInput.Length; i++)
        {
            char holder = userInput.ElementAt(i);
            if (holder.Equals(' '))
            {
                if (!newWords.ContainsValue(userInput.Substring(a, i - a)))
                {
                    string hello = userInput.Substring(a, i - a);
                    newWords.Add(b, hello);
                    a = i + 1;
                    b++;
                    hello = userInput;
                }
                a = i + 1;
            }
        }
        return newWords;
    }
}

```

---
Tags: code-golf, string
---


title: "i" have "i" chance of occuring

text:
# Question
Title: "i" have "i" chance of occuring
> Design a random number generator where the i th number has i% chance of occurring for all 0 \< i \< 14. 0 should have exactly 9% chance of occurring. The seed for the generator should be the system time. You cannot use a pre-defined function for random number generation.

Basically 1 has 1% chance of occurring, 2 has 2% chance and so on up to 13 having 13% chance of occurring. This is code-golf, so the shortest code wins.

# Answer
# CJam, 14 bytes

```
E,_T9t\]ze~es=

```

Test it here.

## Explanation

```
E,   e# Push [0 1 2 ... 12 13].
_    e# Make a copy.
T9t\ e# Set the first element to 9. Swap with the original range.
]z   e# Wrap them in an array and transpose to get [[9 0] [1 1] [2 2] ... [13 13].
e~   e# Run-length decode to get `[0 0 0 0 0 0 0 0 0 1 2 2 3 3 3 ... 13 13 ... 13 13].
es=  e# Use the current timestamp as a cyclic index into this array.

```
> 12 votes

# Answer
## Python 2, 54

```
import time
print((time.time()*1e4%800+1)**.5+1)//2%14

```

The expression `f(t) = ((8*t+1)**.5+1)//2` transforms a uniform distribution to a triangular integer distribution by mapping the intervals

```
[0,1)  --> 1
[1,3)  --> 2
[3,6)  --> 3
[6,10) --> 4
...

```

We convert the millisecond digits of the time to a uniform float from 0 to 100 by doing `time.time()*1e4%100`. Actually, we do `%800` to replace multiplying by 8 in the conversion step. At the end, 14's are converted to 0's by doing `%14`.
> 6 votes

# Answer
# Dyalog APL, 20 bytes

```
⊃(⌊.1×⊃⌽⎕TS)↓(/⍨⍳13)

```

`⍳13` integers 1 though 13
`(/⍨``)` replicate by itself, e.g. `/⍨3` is `3 3 3` and `/⍨2 3` is `2 2 3 3 3`
*n* … drop *n* elements (leaves empty list if *n* \> length of list)
`⎕TS` system time stamp e.g. 2015 11 1 13 28 56 834
`⊃⌽` last element, i.e. current millisecond 0–999
`⌊.1×` multiply with 0.1 and round down
first element, gives 0 if if data is empty
> 5 votes

# Answer
# Pyth - 14 bytes

```
@+mZ9smRd14.d8

```

Generates array with the specified distribution, then pick a random one.

Try it online here.
> 4 votes

# Answer
# Processing 3, 65 55 74 bytes

```
long i=0,c=8,r=System.nanoTime()%100;for(;r>c;i++,c+=i);print(i);

```

Get a random number from 0 to 99 (inclusive). If number is 0-8, print 0, if it is 9 print 1, if 10-11 print 2, if 12-14 print 3, etc...

No one noticed it, but the problem with the old code is that millis() returns the amount of time the application has been running, which would give very similar numbers on subsequent runs of the program. At least now we have nano precision!
> 3 votes

# Answer
# PHP, 50 bytes

```
<?for($t=microtime()*100;0<=$t-=++$i;)?><?=$i%14;

```
* `microtime` returns the time as a string like "0.04993000 1446409253", when I multiply this by 100, PHP coerces the string into 0.04993000, result 4.993000. So `$t` is initialized with a "random" number in `[0,100)`
* We subtract 1, 2, 3, ... from `$t` until it reaches 0
* The result is the last subtracted number, modulo 14
> 2 votes

# Answer
# Python3, 86 Bytes

straight forward:

```
import time;print(sum([[i]*i for i in range(1,14)],[0]*9)[int(str(time.time())[-2:])])

```
> 1 votes

# Answer
# JavaScript (ES6) 116

This is an adaptation of a *simple* seeded RNG that I have used instead of the standard RNG of javascript that cannot be seeded (and so is not repeateble)

```
R=(s=~new Date,p=[],i=0,j=9)=>{
while(p.push(i)<100)--j?0:j=++i;
return _=>(s=(1+Math.sin(s))*1e5,p[100*(s-~~s)|0])
};

// test

var rnd=R()

t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0];
rgb='000,444,666,888,aaa,ddd,f0f,ff0,0ff,0ff,0f0,00f,f00,fff'.split`,`
.map(v=>(v=parseInt(v,16),[(v&15)*17,(v>>4&15)*17,(v>>8)*17]))

cnt=400*300
//for (i=0;i<cnt;i++)t[rnd()]++;

ctx = C.getContext("2d");
img=ctx.getImageData(0, 0, 400, 300)
for(p=0,y=0;y<300;y++)for(x=0;x<400;x++)
  v=rnd(),t[v]++,
  img.data[p++]=rgb[v][0],img.data[p++]=rgb[v][1],
  img.data[p++]=rgb[v][2],img.data[p++]=255
ctx.putImageData(img, 0, 0)

o=''
for(i=0;i<14;i++)
  t[i]/=cnt, o+=`<p><i>${i}</i><b style="width:${t[i]*300}%">,</b>${(t[i]*100).toFixed(2)}%</p>`;
G.innerHTML=o
```

```
#G { width: 400px; font-size: 12px; border: 1px solid #000;  }
p { margin: 0}
b { display: inline-block; font-size:80%; background: #08c; margin: 2px }
i { display: inline-block; width: 20px; text-align: right; padding: 0 4px }
#C { width: 400px; height: 300px; }
```

```
<div id=G></div>
<canvas id=C></canvas>
```
> 1 votes

# Answer
# J - 28 char

This one was silly.

```
{:({:1e3*6!:0'')$100{.#~i.14

```

`6!:0''` is the current `Y M D h m s` time as a 6-item list, where milliseconds are represented as fractions on the seconds—to get at them, we have to no choice but to multiply the seconds (`{:`) by `1e3`. Meanwhile, `#~i.14` is a list of zero 0s, one 1, two 2s, and so on through to thirteen 13s, and we pad that out to 100 items with `100{.`.

J doesn't have cyclic indexing, so it might be tempting to take the milliseconds modulo 100 before indexing the big list. However, we can save two characters by using `$` to instead *cyclically extend* the 100-item list to however many milliseconds we get (anywhere from 0 to 60999) and take the last entry then.

Not that a 60000 element list is a whole lot of memory used or anything, it just feels like overkill :P
> 1 votes

# Answer
## TI-BASIC, 18 bytes

```
real(int(.5+2√(-4+50fPart(sub(getTime

```

`100fPart(sub(getTime` gets the random residue between 0 and 99. The (n-1)th triangular number is equal to `(N^2+N)/2`, so the inverse is equal to `√(2y+1)-.5`. Floor this after adjusting downwards by 9, and we have the result

The only problem is that for residues less than 8, we get an imaginary square root. So we take the real part to have the program output 0 instead.
> 0 votes

# Answer
## Perl 5, 51 bytes

50 bytes + 1 for `-E` instead of `-e`:

```
@_=(0)x 9;push@_,($_)x$_ for 0..13;say$_[time%100]

```
> 0 votes

---
Tags: code-golf, math, random, probability-theory
---