Random script that isn't actually random


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;


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.


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

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

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


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

[~]$ runghc prog.hs

And for your unfortunate target:

[~]$ runhugs prog.hs

[~]$ runhugs prog.hs

Hugs only implements cooperative multitasking, so the rotate thread will never run