text:
Turn nouns into plurals
Your task is to take as input an English noun and output its plural. To win the challenge you must trade off code length against accuracy.
Entries will be scored according to this comma-separated list of 95642 English nouns and their plurals. Your score is the length of your code in bytes, plus the number of nouns in this file that it does not correctly pluralise. If you manage to correctly pluralise every single line in the file then you may apply a 50% bonus. (I don't expect anyone to claim this, but you never know.) The lowest score wins.
Every line in the file consists of a word composed of letters [a-z], followed by ,, followed by the plural, which is also composed of letters [a-z].
Please note that the data in the file is pretty terrible. It was scraped from Wiktionary using someone else's script. There are duplicates, there are things that are not real words, and there are entries that are clearly completely wrong. But none of this matters from the point of view of the challenge. The goal is to produce a program that will correctly reproduce the plurals as written in this file; their correspondence or otherwise to correct English plurals is irrelevant. Also please note that, like any dictionary, the provided file contains its fair share of offensive terms.
Input and output may be performed in any way you find convenient. (Function parameters, command-line input, etc.)
To evaluate your score you will probably need to write some testbed code that iterates over the provided file. Please include this in your answer. This code need not be in the same language as your pluralising program, and should not be golfed. (It should be readable, so we can verify that it works.)
A useful tip: while developing your code, you will probably find it helpful to modify your testbed code so that it prints out every line for which your function fails. That way you can easily see which additional cases you need to consider.
Illustrative examples
the Python code
def p(a):
 return a+'s'

is 24 bytes. However, if we run it through the following evaluation function
def testPlural(func):
    badLines = 0
    with open("simpleNouns.csv") as file:
        for line in file:
            noun, plural = line.rstrip().split(',')
            if plural != func(noun):
                badLines += 1
    return badLines

then we can see that it fails in 11246 cases, giving a score of 24 + 11246 = 11270.
However, if we update the function to
import re
def p(a):
 a+='s'
 return re.sub('ys$','ies',a)

then its length has increased to 58 bytes, but it now fails in only 7380 cases, giving a score of 58 + 7380 = 7438.

There is an existing challenge with the same theme, but this version is different in that the number of test cases is far higher, and the scoring system is different, which I think makes it a challenge of quite a different character.

Have you run the answers there against this list? If they are competitive here, that still makes this a duplicate. I'm unsure at the moment, so I won't vote just yet.

The input file contains more than 2000 duplicate lines. Is this an intentional strategy to give extra weight to some test cases?

@Geobits the top answer there would make a reasonable answer here. However, the point of this challenge is in optimising the solution for the details of this particular list. By doing that even a little, that answer could easily be beaten.

I can see why you're not expecting anyone to get a perfect match. There's some real crap in the data. schwannomatosis,neurofibromatoses? diphosphine,si??!!

I'm not sure that makes it a non-duplicate. It implies I could post another one by just changing the list...

@PeterTaylor I'm in the process of removing the duplicates. Honestly I didn't look at the data that closely. Whether the data is "good" or not isn't really all that relevant to the challenge - its purpose is just to provide an objective winning condition.

@Geobits you must vote according to your conscience I suppose. It's not just the list that's different though. The scoring system in the other challenge means that most of the answers just add 's' to the end of the word, which I think made it rather disappointing, and this version definitely fixes that. Unlike other Stack Exchanges, the execution of an idea really makes a difference here, and if you allow a poorly executed challenge to block people from ever using the same idea, that would seem sub-optimal to me. But I'm new here and don't get to make that call.

40 of the singulars are mapped to multiple conflicting plurals: uniq simpleNouns.csv | cut -d, -f1 | uniq -d -> axis ban batman bob brit chela ... why woolly yen

@ngn hmm, I thought I had removed those, but this was a very long time ago -- I will have to update the file. (I don't really want to bump this challenge while the Moby Dick one is active, but I will update it in the near future.)

As a warning to potential answerers: when I do update the challenge I will remove the 50% bonus for getting all the plurals correct. That bonus is clearly a bad idea in retrospect, as it opens up the possibility of storing a compressed version of the data and just spitting it out. Luckily, the problem @ngn points out makes it impossible to achieve the bonus currently, so no answers will be invalidated by removing it.

I'll start us out with something simple.
Javascript 232+2730=2962
w=prompt();r="ay,ays;ey,eys;oy,oys;y,ies;us,i;um,a;is,es;x,xes;man,men;s,ses;sh,shes;ch,ches;z,zes".split(";");for(i=0;i<r.length;i++){b=r[i].split(",");if(w.slice(-b[0].length)==b[0])return w.slice(0,-b[0].length)+b[1];}alert(w+"s")

Uses a small list of replacement rules. Fails 2730 test cases out of 95642.

Python, 262+2606 = 2868
Small improvement over Peter Olson's answer. Perhaps can be better reimplemented in other language.
import re
def p(n):
 s=n
 for a in r'fe;ves lf;lves ([iln])um;\1a ([cgil])us;\1i (?<![ar])is;es man;men ea;eae (?<!f)ix;ices ((?<!k)s|x|sh|ch|z|j);\1es ((?<=.)[^aeiou])y;\1ies (?<!s);s'.split():
  b,c=a.split(';')
  n=re.sub(b+'$',c,n)
  if n!=s:break
 return n

I wonder if there's any better solution that takes a fundamentally different approach

@Claudiu I'm sure the bulk of transformations will be done using something similar.  I guess the real challenge is to figure out the most efficient way to handle the bad apples.

Agree with guifa, the challenge is how to get most of the irregular nouns. Because for the regular ones, transformation by rule looks very natural.

source: Stack Exchange

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

authors: Павел Саленко

sort: votes


text:
Emulate the Professor's typing
Emulate the Professor's typing
Background
Unfortunately, the Professor is not able to use his keyboard properly: whenever he is meant to use the Shift key, he presses Caps Lock once before typing, and doesn't bother to correct himself. If there are two or more keys in a row that require Shift, he presses Caps Lock before the first one and does nothing before the others.
As his secretary, I want to replicate this effect so that people think that he is the one replying to his emails, not me. He knows his typing looks stupid, but he doesn't care.
Task
Write a program that takes STDIN or file input of some text, and then outputs that text as if it had been typed by the Professor.
This is code golf, and standard loopholes are not allowed.
Keyboard layout
Default:
` 1 2 3 4 5 6 7 8 9 0 - =
   q w e r t y u i o p [ ]
    a s d f g h j k l ; ' #
   \ z x c v b n m , . /

With shift:
¬ ! " £ $ % ^ & * ( ) _ +
   Q W E R T Y U I O P { }
    A S D F G H J K L : @ ~
   | Z X C V B N M < > ?

With caps lock:
` 1 2 3 4 5 6 7 8 9 0 - =
   Q W E R T Y U I O P [ ]
    A S D F G H J K L ; ' #
   \ Z X C V B N M , . /

Example input / output
(The CapsLock line is just there for your understanding, and should not be outputted in your program)
Input:    abc ** def ! (ghijkl) mnop
Output:   abc 88 DEF 1 9GHIJKL0 mnop
CapsLock:     *      * *      *       (* means Caps Lock was pressed before this character)

Input:    print("Hello, World!"); sys.exit()
Output:   print92HELLO, world120; SYS.EXIT90
CapsLock:      *        *    *            *

Input:    !ABC!abc!ABC!abc!x!y!z
Output:   1ABC1ABC1abc1abc1X1y1Z
CapsLock: *       *       * * *

I would say that the opposite of this task would be more interesting :) (i.e to correct his wrongly types mails)

@Optimizer Too ambiguous. Input HELLO could be "corrected" to Hello, HEllo, HELlo, etc.

But the correct would be Hello only, as defined by word case (or fixed rules of correct English casing)

@Optimizer Sure, just pointing out it would need some strict rules, especially regarding numbers/symbols, which could be way more ambiguous than standard prose text. I agree it would be fun if done right.

@Geobits Perhaps that could be a bonus (e.g. 50% bytes)?

@laurencevs Honestly I'd rather see it as a separate challenge :)

What kind of voodoo keyboard is this?

You did the keyboards all wrong ;) http://meta.stackexchange.com/a/156177/314301

Python 2 - 269 275 290 318 337
Input is mostly safe if you use triple-quotes:"""print("Hello, World!"); sys.exit()"""
C=D=0
r=''
l,u,c=" `1234567890-=qwertyuiop[]asdfghjkl;'#\\zxcvbnm,./",' \xac!"\xa3$%^&*()_+QWERTYUIOP{}ASDFGHJKL:@~|ZXCVBNM<>?'," `1234567890-=QWERTYUIOP[]ASDFGHJKL;'#\\ZXCVBNM,./"
for h in input():w=h!=' ';U=h in u;C^=w&U&~D;D=U&w;r+=[l,c][C][[l,u][U].find(h)]
print r

Encoding doesn't seem to help much, except with the awkward ¬ and £ characters (I've tried looking at other problems like this and I think I should try to use split?)(It doesn't seem like the keyboard compresses enough to make it worth .decode, etc...)
Also, spaces suck.
Edit note: Indexing is weird

PowerShell - 295
Takes input from the console (Read-Host), and outputs to the console.
$d=@("``1234567890-=qwertyuiop[]asdfghjkl;'#\zxcvbnm,./ ","``1234567890-=QWERTYUIOP[]ASDFGHJKL;'#\ZXCVBNM,./ ",'¬!"£$%^&*()_+QWERTYUIOP{}ASDFGHJKL:@~|ZXCVBNM<>? ')
((Read-Host).ToCharArray()|%{if($_-eq' '-or$d[2].IndexOf($_)-lt0){$a=0}else{if(!$a){$b=!$b}$a=2}$d[$b][$d[$a].IndexOf($_)]})-join''

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


text:
Hole 2 - Prime Quine
Find Hole 1 here.
Make a quine that, when run, outputs its own source code block multiple times. In fact, it must output it n times, where n in the next prime number.
I think an example shows it best.
[MY QUINE][MY QUINE]
[MY QUINE][MY QUINE][MY QUINE]
[MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE]
[MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE]
[MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE][MY QUINE]

Each Program will output its base "block" (so [MY QUINE]) the next prime number times.
Built in functions to calculate whether a number is prime, (like an isPrime function), or to determine the next prime (like a nextPrime() function) are not allowed.

This means that functions to list the number of divisors is not allowed
Functions that return the prime factorization are likewise disallowed

This should be a true quine (except for some leeway, see next point), so you should not read your own source code.
Because languages like Java and C# are already at a disadvantage, You need not output totally working code. If it could be put in a function (that is called) and output the next quine, you are good.
This is code-golf, so shortest code wins!

No one answered hole 1, so what score does everyone answering this one get for the first hole ?

Could you clarify the part with the prime functions? Can we use them or can we not use them?

What is considered prime checking and what is not? Considering that prime checking can be built using any quine if this sort, the rules are not clear enough

@Optimizer: Everyone has a score of 0 for the first hole until someone answers it.

@MartinBüttner modulo is fine, and in this case Divides would also be fine (sorry for the confusion). I am just excluding functions in which it outputs either a) the next prime or b) if a number is prime.

@MartinBüttner That effectively tells you if a number is prime and is not allowed. Sorry.

@StretchManiac You should clearly mention in the question that both list of prime factorization methods and list of divisors methods are also not allowed. Please post the question in the Sandbox next time.

CJam, 31 bytes
{'_'~]-3>U):U{)__,1>:*)\%}g*}_~

Try it online in the CJam interpreter.
Idea
To check for primality, we'll use Wilson's theorem, which states that an integer n > 1 is prime if and only if (n - 1)! ≡ -1 (mod n), which is true if and only if (n - 1)! + 1 % n == 0.
Code
{                           }_~ e# Define a block and execute a copy.
                                e# The original block will be on top of the stack.
 '_'~]                          e# Push those characters and wrap the stack in an array.
      -3>                       e# Keep only the last three elements (QUINE).
         U):U                   e# Increment U (initially 0).
             {           }g     e# Do-while loop:
              )__               e# Increment the integer I on the stack (initially U).
                 ,1>            e#   Push [1 ... I-1].
                    :*          e#   Multiply all to push factorial(I-1).
                      )\%       e#   Push factorial(I-1) + 1 % I.
                                e# While the result is non-zero, repeat.
                                e# This pushes the next prime after U.
                           *    e# Repeat QUINE that many times.

How did you find that method of checking prime o.O

Remembered would be more accurate. It's known as Wilson's theorem.

mp (is prime?) exists now, so in the latest version of CJam, one could golf this down a little more.

@Mauris It existed in the first public version, IIRC. However, the question forbids built in prime and factorization operators.

Mathematica, 248 222 bytes
Edit: Fixed the usage of a prime-related function, but also improved the quining a bit.
Edit: Thanks to Dennis for introducing me to Wilson's theorem.
1;n=If[ValueQ@n,n+1,1];StringJoin@Array[#<>ToString[1##,InputForm]<>#2&@@\("1;n=If[ValueQ@n,n+1,1];StringJoin@Array[#<>ToString[1##,InputForm]<>#\2&@@("*"&,For[i=n,Mod[++i!/i+1,i]>0,0];i]")&,For[i=n,Mod[++i!/i+1,i]>0,0];i]

This assumes that the kernel is quit between subsequent runs of the quine (or at least n is reset), because it relies on n being undefined before the first instance of [MyQuine] is run.
This can probably be shortened a lot, but I don't have a lot of experience with quines, especially in Mathematica.
Here is an explanation:
1;

This doesn't do anything, but if concatenated onto the end of the previous quine, it multiplies the result of the last expression by 1 (which is a no-op) and the semicolon suppresses output. This ensures that only the last copy of [MyQuine] prints anything.
n=If[ValueQ@n,n+1,1];

This initialises n to 1 in the first copy of [MyQuine] and then increments it by 1 in each further copy - i.e. this just counts how many copies there are in n.
Skip ahead to the end now:
For[i=n,Mod[++i!/i+1,i]>0,0];i

This finds the next prime using Wilson's theorem.
StringJoin@Array[#<>ToString[1##,InputForm]<>#2&@@\("QUINE_PREFIX"*"QUINE_SUFFIX")&,NEXTPRIME[n]]

This is the actual quine. It creates NextPrime@n copies of the code itself. It's also a bit weird. Yes, I'm multiplying two strings there, and no that doesn't have a meaningful result. QUINE_PREFIX contains all the code before the two strings and QUINE_SUFFIX contains all the code after the two strings. Now usually you use Apply (or @@) to turn a list into a series of arguments. But you can replace any Head with Apply - e.g. multiplication. So despite this being a product I can still turn it into into two arguments to my function. That function does:
#<>ToString[1##,InputForm]<>#2

Where # is the first argument (the prefix string), #2 is the second argument (the suffix string), ## is a sequence of both arguments. I need to prepend 1 to preserve the multiplication - otherwise ## would splat into the argument list to ToString. Anyway, ToString[1##,InputForm]&@@("abc"*"def") returns "abc"*"def"... just what I need!
I think with all the stuff I need around the quine, an eval-based quine would be more appropriate here. I'll look into that later or tomorrow.

@MartinBüttner the question should be edited

Heh, I can also use Wilson's Theorem to bring my entry at par with Denis' ;)

@Optimizer But in my case there was no danger of offending anyone because I'm still using 7 times as many bytes as the two of you ;)

@MartinBüttner I know :D That is why I did not use it :)

CJam, 36 35 bytes
{]W="_~"]U):U{)_,{)1$\%!},,2>}g*}_~

This can definitely be golfed further.
How it works:
{                               }_~   "Copy this code block and execute the copy";
 ]W=                                  "Take just the last element from the stack";
                                      "The other thing on stack is the block from above";
    "_~"]                             "Put "_~" on stack and wrap the 2 things in an array";
                                      "At this point, the string representation of stack"
                                      "elements is identical to the source code";
         U):U                         "Increment U and update U's value. This  variable"
                                      "actually counts the number of [Quine] blocks";
             {)_,{)1$\%!},,2>}g       "Find the next prime number"
                               *      "Repeat the array that many times, thus repeat the"
                                      "[Quine] block, the next prime times";

Thanks to Martin for reminding me the ]W= trick :)
Try it online here

J - 60 char
Uses the next-prime method like the other answers. (That's the 4 p: bit.)
((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''

A cute little J trick is that f :g acts like f when given one argument and g when given two. So, if you write out, say f :;'a'f :;'a'f :;'a' then that acts like f'a';'a';'a', which is great because that's a boxed list whose items are 'a' and whose length is the number of occurrences.
So we can lift that into a quiney sort of thing. The f we use looks like (foo $~ bar), where foo constructs the string part that we repeat over and over, bar finds the next prime number and multiplies it by 60, the length of the string in foo.
   ((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
   # ((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
180
   ((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
   # ((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''((58&$,2#{:)@;$~60*4 p:#) :;'((58&$,2#{:)@;$~60*4 p:#) :;'''
300

Could you modify your code to meet the new specs? Methods that output the next prime are not allowed. Thanks.

Python 2.7, 214
from sys import*;R,s=range,chr(35)
def N(n):
 if n<3:return n+1
 for p in R(n+1,n+n):
    for i in R(2, p):
     if p%i==0:break
     else:return p
P=file(argv[0]).read();print(P.split(s)[0]+s)*N(P.count(chr(37)));exit(0)
#


text:
Solve a Tetris Puzzle (pack predefined shapes into optimal form)
The challenge is about finding an optimal solution on how to place a number of given shapes. It is oriented on the principle of Tetris, where it is optimal to pack the given pieces as tight as possible.
An optimal solution means that all shapes could be placed in one rectangle block filling the width of the playground. If there is no optimal solution possible, the code should find a solution where holes are placed as high as possible (thus allowing to have a subpart of the solution being optimal). Empty spaces on top of the solution are also counted as holes (see example at the bottom).

Rules

There are predefined Tetris shapes: I J L S Z O T
There could be multiple shapes of the same type available
There is a playground with a certain width X
The minimum width is 4, there is no maximum width
There is no limitation for the height of the playground
It is possible to rotate the shapes in 4 directions (Up, Left, Right, Down)
It is NOT possible to mirror the shapes (Turning L into J or S into Z)

Possible shapes:
T:      T
       TTT

I:     IIII

J:     JJJ
         J

L:       L
       LLL

S:      SS
       SS

Z:     ZZ
        ZZ

O:     OO
       OO

A bit of imagination is needed, but everyone who played Tetris should be familiar with the shapes.
Example
A call to a solution using Python could look like the following:
tetrissolver.py <Width> <Shape1> <Shape2> <ShapeN>
tetrissolver.py 4 S S T T L
The result would be some kind of output which shows the optimal solution (tightest possible packaging). Bonus points if the solution also returns if the found solution is optimal.
Possible output of the above input in a text format:
LLLT
LSTT
SSST
STSS
TTTS

The found solution is optimal

If there is no optimal solution available, the code should find a solution with the least amount of holes in it. Empty spaces on top of the package are counted as holes. The above example with an additional T element could look like the following in the solution (holes marked with X):
XTXX
TTTX
LLLT
LSTT
SSST
STSS
TTTS

The found solution is NOT optimal

Solution
The solution should find the most optimal package. Holes should be placed as high as possible. If two solutions generate the same quality of packages (optimal packages if possible, same amount of holes), the smallest solution wins.

Is a minimum width guaranteed?

Yep, minimum width is 4 (all pieces fit into the minimal width regardless of their orientation). I'll also update it in the description

Java - Theoretically Optimal Solution
I needed one of these anyway, so...
Code is viewable here.
The routine should theoretically produce an optimal solution for any input. It typically runs on the order of milliseconds or seconds for < 100 shapes, and the complexity appears to be roughly O(n log2 n) for random inputs. Packing hundreds or even thousands of random shapes should complete in a reasonable amount of time.
The worst case performance grows as O(nn ww), where n is the number of shapes to pack and w is the packing width. Thus this program earns the dubious distinction of having the worst worst case performance of any (non-busy-beaver) algorithm I've ever programmed. :P
Sample I/O
java TetPack 10 J T Z I I J Z O O J T S S O I

IIIIJOOTTT
IIIIJOOSTI
OOSJJZTSSI
OOSSZZTTSI
OOJSZJTZZI
OOJJJJJJZZ

Displayed solution is optimal.

java TetPack 3 T

XTX
TTT

9 J S I O S T T I I I S

XIIIIIIII
TTTSSIIII
TTSSJJJOO
TTSSSSJOO
TSSSSIIII

java TetPack 15 L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

JJJJLLLLJLJJJJJ
JJJJLLJJJLJJJJJ
LLLLLLJJJLLLJJJ
LLLLLLJJLLLLJJJ
LLLLJJJJLLJLLLL
LLLLJJJJJLJJJLL
LLJJJJJJJLLLLLL
LLJJJJJJJLLLLLL
LLJJJJJLJLLLLLL
JJJJJJLLJJJLJLL
JJJJJJLLLLLLJLL
JJJJJLLLJJLJJLL
LLLJJLLLJJLJJJJ
LLLLLLLLJJLLLJJ
JLLLLLJLJJLLJJJ
JJJLLLJJJLLLJJJ

Displayed solution is optimal.

java TetPack 4 Z T

XZXX
ZZTX
ZTTT

java TetPack 30 J I O J J L T T T I O Z Z S I I O Z T O L L J I I L S Z Z I J I O S L L L L J J J I I O Z L J I L S I S Z I L I J I O J J L T T T I O Z Z S I I O Z T O L L J I I L S Z Z I J I O S L L L L J J J I I O Z L J I L S I S Z I L I

XXIIIIIIIIIIIIIIIIIIIIIIIIIIII
LIIIILIIIILIIIILIIIIJLIIIIJLOO
LIIIILJJJLLIIIILLLJJJLIIIIJLOO
LLJLJLLIJLLLZLJLLLJJJLLZZJJLLI
JJJLJJJILLLZZLJJJLJZZLLIZZZOOI
JJJLLILILZZZJLLSSOOIZZLILZZOOI
JJJJJILILLZZJSSSZOOIOOLILZTLLI
IJJJJILLSSZJJSSZZOOIOOTILLTTLI
IJJJJILSSZZSSZSZTOOIITTTOOTSLI
IJJJJLLZZZSSZZTTTTOOIIJJOOLSSI
ISSZILLLZZOOZTTTTJOOIIJLLLLTSI
SSZZILLOOJOOTZZTTJJJIIJLZZTTOO
LSZLIZZOOJJJTTZZTIIIIIJLLZZTOO
LSSLIJZZOOOOTSSSSSSTZZJJJLIIII
LLSLLJJJOOOOSSSSSSTTTZZLLLIIII

Tried your code with an Java online compiler, worked like a charm!


text:
Spiral Polygons

Draw a series of connected polygons like the one shown above.
However, what the above picture does not show is the spiral formed by consecutive vertexes:

The limitation of these is that there is only 1 spiral marked. You should mark all the spirals. This can be done by rotating each spiral shown above so that there is a spiral starting at each vertex of the largest polygon.
The spirals should all be one color, while the rest of the picture another.
The innermost polygon should be entirely the color of the spiral.
Rules

You will receive the arguments { n, s, p, a } in a function or program
n = iterations inward (number of polygons)
s = sides of the (regular) polygon (you may assume n>=3)
p = (the linear distance from a vertex of polygon A to its corresponding counter-clockwise "inner" vertex) / (the total length of A's side). So for the diagram, p would be about 1/3 because each inner polygon meets the larger polygon's side at about 1/3 of the way through that side.
a = the radius (circumscribing) of the exterior polygon

The limit of any of the values of n,s,p or a are based on what can be perceived as this kind of drawing by a human. (e.g. no shaded circles) as well as common sense (s>=3,n>=1)
Happy golfing! Shortest program wins.

Is the parameter p linear in angle or in distance between two vertices?

Sorry for the confusion, hopefully the edits will clear things up.

You should color it a different color than the other lines. So each side will have 2 colors - one that goes p through it, and the rest a different color.

@MartinBüttner I think he means that all the spirals (the clockwise portion of all sides) should be a highlight colour (like red) and the rest of the side should be the basic foreground colour (like black.) This would give s anticlockwise red spirals. However, what remains would be s clockwise black spirals! StretchManiac, this is a good question but we really need an example picture to see what you mean. Upvoting and closevoting.

Openvoting, though it would be helpful to confirm if the innermost polygon should be filled (I understand it shouldn't.)

Mathematica, 218 206 bytes
{n,s,p,a}=Input[];t=0;Graphics[(c=Array[a{Cos[u=t+2Pi#/s],Sin@u}&,s+1];m=(f=p#2+(1-p)#&)@@c;a=Norm@m;t=ArcTan@@m;k=#;{Line@{#,x=f@##},If[k<n,Red],Line@{x,#2}}&@@@Thread@{c,RotateLeft@c})&~Array~n,Axes->1>0]

Expects the input as an array as defined in the question, e.g. {20, 7, 0.5, 100}:

or {20, 5, 0.333, 100}

These images still use red and grey from an earlier version, but the new version uses black for the counter-clockwise spirals and red for the rest.
I've included an axis, because otherwise the a parameter is meaningless with a vector graphic. I've also interpreted p as a linear interpolation in position, not in angle.
Ungolfed:
{n, s, p, a} = Input[];
t = 0;
Graphics[
 (
    c = Array[a {Cos[u = t + 2 Pi #/s], Sin@u} &, s + 1];
    m = (f = p #2 + (1 - p) # &) @@ c;
    a = Norm@m;
    t = ArcTan @@ m;
    k = #;
    {Line@{#, x = f@##}, If[k < n, Red], Line@{x, #2}} & @@@
     Thread@{c, RotateLeft@c}
    ) &~Array~n
 ,
 Axes -> 1 > 0]


text:
Make a one sequence
A sequence of integers is a one-sequence if the difference between any two consecutive numbers in this sequence is -1 or 1 and its first element is 0.
More precisely: \$a_1, a_2, ..., a_n\$ is a one-sequence if:
$$\forall k \::\: 1\le k<n, |a_k-a_{k+1}| = 1 \\ a_1 = 0$$
Input

\$n\$ - number of elements in the sequence
\$s\$ - sum of elements in the sequence

Output

a one-sequence set/list/array/etc of length \$n\$ with sum of elements \$s\$, if possible
an empty set/list/array/etc if not possible

Examples
For input 8 4, output could be [0 1 2 1 0 -1 0 1] or [0 -1 0 1 0 1 2 1]. There may be other possibilites.
For input 3 5, output is empty [], since it cannot be done.
Rules
This is a code golf, shortest answer in bytes wins. Submissions should be a program or function. Input/output can be given in any of the standard ways.

By the way, I have a proof that all numbers representable as a one sequence of length l are all the numbers between (l-1)*l/2 and -(l-1)*l/2 which have the same parity as (l-1)*l/2.

this can be used to make an efficient algorithm (O(n)) to make a desired one sequence

CJam, 56 47 44 34 bytes
A lot of scope for improvement here, but here goes the first attempt at this:
L0aa{{[~_(]_)2++}%}l~:N;(*{:+N=}=p

Credits to Dennis for efficient way of doing the { ... }% part.
Prints the array representation if possible, otherwise ""
Try it online here

I'm confused: The {}% part of your code looks nothing like mine (which is just @PeterTaylor's code, replacing dots with underscores). If I contributed anything to your code, it's the {}= operator...

I initially had _{_W=)+}%\{_W=(+}%+ which was first making two copies, add 1 to the first, subtracting 1 from other. Your example made me figure out how to do that in one { ... }% block. Regarding the { ... }=, I already had reduced it that much in my experimentation, although not posted yet.

I understand from the question that given input 3 5 the output should be [] and not ""

@PeterTaylor "an empty set/list/array/etc if not possible" - So I think that I just have to make it clear ...

Plus, []p in CJam just outputs to "". So its how the language represents empty arrays.

JavaScript (E6) 79  82
F=(n,t,
  d=n+n*~-n/4-t/2,
  l=1,
  q=[for(x of Array(n))d<n--?++l:(d+=~n,--l)]
)=>d?[]:q

No need of brute force or enumeration of all tuples.
See a sequence of length n as n-1 steps, each step being increment or decrement.
Note, you can only swap an increment for a decrement, sum varies by 2, so for any given length the sum is always even or always odd.
Having all increments, the sequence is 0, 1, 2, 3, ..., n-1 and we know the sum is (n-1)*n/2
Changing the last step, the sum changes by 2, so the last step weighs 2.
Changing the next to last step, the sum changes by 4, so the last step weighs 4.  That's because the successive step builds upon the partial sum so far.
Changing the previous step, the sum changes by 6, so the last step weighs 6 (not 8, it's not binary numbers).
...
Changing the first step weighs (n-1)*2
Algorithm
Find the max sum (all increments)
Find the difference with the target sum (if it's not even, no solution)
Seq[0] is 0
For each step
  Compare current difference with the step weight
  if is less
     we have an increment here, seq[i] = seq[i-1]+1
  else
     we have a decrement here, seq[i] = seq[i-1]-1.
     Subtract we current weight from the current diff.
If remaining diff == 0, solution is Seq[]. Else no solution

Ungolfed code
F=(len,target)=>{
  max=(len-1)*len/2
  delta = max-target
  seq = [last=0]
  sum = 0
  weight=(len-1)*2
  while (--len > 0)
  {
    if (delta >= weight)
    {
      --last
      delta -= weight;
    }
    else
    {
      ++last
    }
    sum += last
    seq.push(last);
    weight -= 2;
  }
  if (delta) return [];
  console.log(sum) // to verify

  return seq
}

Test In Firefox / FireBug console
F(8,4)

Output
[0, -1, 0, -1, 0, 1, 2, 3]

GolfScript (41 39 bytes)
[][1,]@~:^;({{.-1=(+.)))+}%}*{{+}*^=}?`

Online demo
Thanks to Dennis for 41->39.

You can shorten ,0= to ?. A straightforward port to CJam would be 5 bytes shorter: L1,al~:S;({{_W=(+_)))+}%}*{:+S=}=p

@Dennis oooh, that's handy way of getting ride of two {}% blocks. Mind if I use it ?

@Optimizer: I don't, but it's not really my work.

I was talking about the { ... }% block. In my code, I had two, was trying to reduce it to 1. As was as real algorithm goes, I think both Peter and I posted the same algorithm almost at the same time.

Jelly, 11 bytes
’Ø-ṗÄS=¥ƇḢŻ

Try it online!
Although I originally had ’2*ḶBz0Z-*ÄS=¥ƇḢŻ, this is close enough to caird's solution in principle now that I'm almost tempted to just suggest it in the comments. In the case that you really really want [] over 0, maybe it's just +3 bytes?, maybe it's +5.
 Ø-            [-1, 1]
   ṗ           to the Cartesian power of
’              n - 1.
    Ä          Cumulative sums.
        Ƈ      Keep only those for which
     S ¥       the sum
      =        is equal to s.
         Ḣ     Take the first survivor
          Ż    and slap a 0 on the start of it.

-1 from your [] versions

@cairdcoinheringaahing ...oh. Thanks!

and I just realized I'd already done that by accident on both of them

Mathematica, 73 bytes
f=FirstCase[{0}~Join~Accumulate@#&/@Tuples[{-1,1},#-1],l_/;Tr@l==#2,{}]&;

Simple brute force solution.
I'm generating all choices of steps. Then I turn those into accumulated lists to get the one-sequences. And then I'm looking for the first one whose sum is equal to the second parameter. If there is non, the default value is {}.

Mathematica just shines its way on maths/combination related problems, Don't it ? ;)

@Optimizer I'm sure CJam will beat it nevertheless. ;) Actually this same algorithm shouldn't be hard to do in CJam.

It will definitely beat it, but just because of short method names. The algorithm will not be as straight forward.

@Optimizer, huh? I think it's more straightforward with a simple loop and filter than this function composition.

Haskell, 56 bytes
n%s=[x|x<-scanl(+)0`map`mapM(\_->[1,-1])[2..n],s==sum x]

Explanation:

Build a list with the permutations of 1,-1 and length n-1: replicateM n-1[-1,1]
Example: replicateM 2 [-1,1] == [[-1,-1],[-1,1],[1,-1],[1,1]]
Build the one-sequence out of it. scanl has poor performance, but it does the right job here.
Filter all possible one-sequences with length n where the sum is s

a simple improvement is to change a to an infix function. here's a hint to a more unintuitive improvement: importing Control.Monad just for using replicateM which is already too long. what other monadic function can you use to simulate replicateM?

by the way, you should return only one solution, so you should add head$ to your solution.

head does not return [] for [] :: [[a]] - and I hate errors.

because some time has passed, I'll tell you what I meant. You could use mapM(\x->[1,-1])[2..n] instead of sequence and replicate.

Interesting. That is even shorter :P

Husk, 14 16 bytes
ḟo=⁰ΣmΘm∫π←²fIṡ1

Try it online!
Same idea as Unrelated String's answer. I'll add in a version that returns [] once I can find a way to make if work properly.
Now works as advertised!

Doesn't this always output a sequence that's too long by one element?

yes, forgot about it. I fixed it.

Python, 138
from itertools import*
def f(n,s):
 for i in[list(accumulate(x))for x in product([-1,1],repeat=n-1)]:
  if sum(i)==s:return[0]+i
 return[]

Python 3, 80 bytes
f=lambda l,s,a=[0]:l>1and max(f(l-1,s,a+[a[-1]+x])for x in(1,-1))or(sum(a)==s)*a

Try it online!

Jelly, 18 16 bytes
’Ø-œċŒ!€ẎÄS=¥ƇḢŻ

Try it online!
Returns 0 if no such list exists. If you insist on returning [], +5 bytes.
-2 bytes thanks to Unrelated String
How it works
Rather than generating all possible lists of length \$n\$ and comparing to specific parameters, this instead generates all possible partial differences, then filters sequences on that
’Ø-œċŒ!€ẎÄS=¥ƇḢŻ - Main link. Takes n on the left and s on the right
’                - n-1
 Ø-              - [-1, 1]
   œċ            - Combinations with replacement
     Œ!€         - Get the permutations of each
        Ẏ        - Tighten into a list of partial differences
         Ä       - Compute the forward sums
             Ƈ   - Filter; Keep those sequences k where the following is true:
            ¥    -   Group the previous 2 links into a dyad f(k, s):
          S      -     Sum of k
           =     -     Equals s
              Ḣ  - Take the first sequence or 0 if there are none
               Ż - Prepend a 0 if a list

17?

wait, no, 16

@UnrelatedString Very nice, thanks!

Ruby(136)
def one_sequences(n)
  n.to_s.chars.map(&:to_i).each_cons(2).to_a.select{|x|x[0] == 0 && (x[1] == 1 || x[1]
  == -1)}.count
end

CJam, 65 58 54 bytes
Barely shorter than my Mathematica solution, but that's mostly my fault for still not using CJam properly:
0]]l~:S;({{_1+\W+}%}*{0\{+_}%);}%_{:+S=}#_@\i=\0>\[]?p

It's literally the same algorithm: get all n-1-tuples of {1, -1}. Find the first one whose accumulation is the same as s, prepend a 0. Print an empty array if none is found.

CJam, 40
Another approach in CJam.
ri,W%)\_:+ri-\{2*:T1$>1{T-W}?2$+\}/])!*p

J, 47 chars
Checks every sequence like many other answers. Will try to make a shorter O(n) solution.
   f=.4 :'(<:@#}.])(|:#~y=+/)+/\0,|:<:2*#:i.2^<:x'

   8 f 4
0 1 2 1 0 1 0 _1

   3 f 5
[nothing]

APL 38
{⊃(↓a⌿⍨⍺=+/a←+\0,⍉1↓¯1*(⍵⍴2)⊤⍳2*⍵),⊂⍬}

Example:
     4 {⊃(↓a⌿⍨⍺=+/a←+\0,⍉1↓¯1*(⍵⍴2)⊤⍳2*⍵),⊂⍬}8
0 1 2 1 0 1 0 ¯1

This one as many others just brute forces through every combination to find one that matches, if not found returns nothing. Actually it tries some combinations more than once to make the code shorter.

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


text:
Be an Epidemiologist!
Challenge
You must create a simple model of how disease spreads around a group of people.
Rules and Requirements
The model must be a 1000 by 1000 2D array with each element being a different person.
The user must input three variables using argv: the probability of transmission (how likely someone is going to infect someone else), chance of mutation and how many periods the simulation should run for.
In the first period (t=0), four people should be chosen randomly and infected with the disease.
The way the disease behaves is governed by the following rules:

The disease can only move vertically and horizontally, moving to the person next door.
The infection last for 3 periods in every person. You may not factor in immunodeficiencies.
After a person has been infected three times, they are immune and cannot be infected again.
The disease is subject to mutation making the previously immune people vulnerable to this new mutated disease. The mutated disease has exactly the same traits and follows the same rules as the original disease.
If a mutation occurs, the whole disease does not change, just that particular 'packet' upon transmission.
Once a person has been been infected by one virus, they cannot be infected again until the current infection passes.
If a person is infected, they are infectious from the start of their infection period to its end.
There are no levels of immunity - a person is either immune or not.
To stop memory overload, there is a maximum limit of 800 mutations.

At the end of the specified number of periods, you should output the results.
The results must be a 1000 x 1000 grid showing which people are infected and which people are not. This can be output as a text file, as an image file or graphical output (where #FFFFFF is a healthy person and #40FF00 is an infected person).
Please can you include the language name and a command to run it in your answer.
Winning
The fastest code to run on my computer wins. Its time will be measured with the following piece of Python code:
import time, os
start = time.time()
os.system(command)
end = time.time()
print(end-start)

Note that when running this script, I will use the following defaults:
Probability of transmission = 1
Chance of mutation = 0.01
Number of periods = 1000

You want to make a 10-gigabyte file?

And btw, are you planning to view the final generated image file ? ;)

@Optimizer I was actually planning to use the winning answer for my own experimentation, so yes :)

By having a 4 GB limit, you have completely removed the option of saving the output in image file ...

1000x1000: That's more like it!

So we assume that a virus cannot mutate to a previously seen virus? Say V mutate to V', we assume that whenever V' mutates, it won't mutate back to V, right?

Also say there are two people next to each other. The first contracts virus V, the second contracts virus V'. The contraction will both end at the same period. Can virus V infects the second person? (Or a more black-and-white question: is it possible that a person be infected immediately after he is healed, so he will end up with 6 consecutive period of infection?)

Another one, can two independent viruses mutate to the same virus? Say we have V in person A, and V again in person B. When they transmit the virus, can they both mutate to the same mutation V'? Or perhaps they in fact should mutate to the same virus strain? If they can mutate arbitrarily, what is the probability of two viruses mutating to the same virus strain?

If a healthy, non-immune person is next to two people infected by two different strains of virus, which one does the people get?

@justhalf 1: No, it will not mutate back. 2: For the purposes of this, assume that all mutations form unique strains. 3: Choose the strain randomly

I think giving unique strain for each mutation gives too many strains to be handled. Even before period 200 there are already more than 8000 strains. Considering each person needs to remember whether it is immune to each strain (consider 2 bits each), it already reaches 2bil bytes (2GB memory). Yes, 2bits per strain can be (though a bit tricky) reduced to 1 bit each, but my point still stands that there will just be too many strains to be handled. How about limiting the number of possible mutation?

@justhalf Yes, that would make sense.

So how does the mutation work? Does each mutation have a chance to mutate to any of the 800 possible strains? Then a virus might be able to mutate to previously seen form. Is this how it's supposed to work?

@justhalf No, the virus just mutates no more.

I'll need to change my implementation then. I can only do that on Tuesday (long weekend here). So I guess I'll need to keep my answer in its current form until Tuesday. Anyway since when it mutates back to original strain, most will already be immune to it, I guess it's still ok. =)

Dude,.. just tried this on a 200mhz MCU, my first algorithm (JUST TO INITIALIZE!) took 4 minutes :'D (language was lua)

windows or linux/osx?

I was curious what this would look like so I made this quick and dirty hack in JavaScript: http://jsfiddle.net/andrewmaxwell/r8m54t9c/
// The probability that a healthy cell will be infected by an adjacent infected cell EACH FRAME.
var infectionProbability = 0.2

// The probability that the infection will mutate on transmission EACH FRAME.
var mutationProbability = 0.00001

// The maximum number of times a cell can be infected by the same infection.
var maxInfections = 3

// The number of frames a cell in infected before it becomes healthy again.
var infectionDuration = 3

// The width and heigh of the board
var size = 400

// The number of cells infected at the beginning.
var startingNum = 4

var imageData, // the visual representation of the board
    cells, // array of cells
    infectionCount // counter that is incremented whenever a mutation occurs

// Just some colors. The colors are re-used as the number of mutations increases.
var colors = [[255,0,0],[255,255,0],[0,255,0],[0,255,255],[0,0,255],[255,0,255],[128,0,0],[128,128,0],[0,128,0],[0,128,128],[0,0,128],[128,0,128],[255,128,128],[255,255,128],[128,255,128],[128,255,255],[128,128,255],[255,128,255]
]

// when a cell is infected, it isn't contagious until the next frame
function infect(person, infection){
    person.infect = true
    person.infectionCounts[infection] = (person.infectionCounts[infection] || 0) + 1
    person.currentInfection = infection
}

// when a mutation occurs, it is given a number and the counter is incremented
function mutation(){
    return infectionCount++
}

function reset(){

    cells = []
    infectionCount = 0
    imageData = T.createImageData(size, size)

    // initialize the cells, store them in a grid temporarily and an array for use in each frame
    var grid = []
    for (var i = 0; i < size; i++){
        grid[i] = []
        for (var j = 0; j < size; j++){
            cells.push(grid[i][j] = {
                infectionTime: 0, // how many frames until they are no longer infected, so 0 is healthy
                infectionCounts: [], // this stores how many times the cell has been infected by each mutation
                neighbors: [] // the neighboring cells
            })
        }
    }

    // store the neighbors of each cell, I just want to minimize the work done each frame
    var neighborCoords = [[0,-1],[1,0],[0,1],[-1,0]]
    for (var i = 0; i < size; i++){
        for (var j = 0; j < size; j++){
            for (var n = 0; n < neighborCoords.length; n++){
                var row = i + neighborCoords[n][0]
                var col = j + neighborCoords[n][1]
                if (grid[row] && grid[row][col]){
                    grid[i][j].neighbors.push(grid[row][col])
                }
            }
        }
    }

    // infect the initial cells
    for (var i = 0; i < startingNum; i++){
        infect(cells[Math.floor(cells.length * Math.random())], 0)
    }
}

function loop(){
    requestAnimationFrame(loop)

    // for each cell marked as infected, set its infectionTime
    for (var i = 0; i < cells.length; i++){
        var p = cells[i]
        if (p.infect){
            p.infect = false
            p.infectionTime = infectionDuration
        }
    }

    for (var i = 0; i < cells.length; i++){
        var p = cells[i]

        // for each infected cell, decrement its timer
        if (p.infectionTime){
            p.infectionTime--

            // for each neighbor that isn't infected, if the probability is right and the neighbor isn't immune to that infection, infect it
            for (var n = 0; n < p.neighbors.length; n++){
                var neighbor = p.neighbors[n]
                if (!neighbor.infectionTime && Math.random() < infectionProbability){
                    var infection = Math.random() < mutationProbability ? mutation() : p.currentInfection
                    if (!neighbor.infectionCounts[infection] || neighbor.infectionCounts[infection] < maxInfections){
                        infect(neighbor, infection)
                    }
                }
            }

            // colors! yay!
            var color = colors[p.currentInfection % colors.length]
            imageData.data[4 * i + 0] = color[0]
            imageData.data[4 * i + 1] = color[1]
            imageData.data[4 * i + 2] = color[2]
        } else {
            imageData.data[4 * i + 0] = imageData.data[4 * i + 1] = imageData.data[4 * i + 2] = 0
        }

        imageData.data[4 * i + 3] = 255
    }

    T.putImageData(imageData, 0, 0)
}

// init canvas and go
C.width = C.height = size
T = C.getContext('2d')
reset()
loop()

Setting infectionProbability to 1 made some of the sweetest patterns I've seen!

Could you add how long your program takes to your answer?

C++11, 6-8 minutes
My test run takes about 6-8 minutes in my Fedora 19, i5 machine. But due to the randomness of the mutation, it might as well be faster or take longer than that. I think the scoring criteria needs to be readdressed.
Prints the result as text at the end of completion, healthy person denoted by dot (.), infected person by asterisk (*), unless ANIMATE flag is set to true, in which case it will display different characters for people infected with different virus strain.
Here is a GIF for 10x10, 200 periods.

Mutation behaviour
Each mutation will give new strain never seen before (so it is possible that one person infects the four neighboring people with 4 distinct strains), unless 800 strains have been generated, in which case no virus will go any further mutation.
The 8-minute result comes from the following number of infected people:

Period   0, Infected:      4
Period 100, Infected:  53743
Period 200, Infected: 134451
Period 300, Infected: 173369
Period 400, Infected: 228176
Period 500, Infected: 261473
Period 600, Infected: 276086
Period 700, Infected: 265774
Period 800, Infected: 236828
Period 900, Infected: 221275

while the 6-minute result comes from the following:

Period   0, Infected:      4
Period 100, Infected:  53627
Period 200, Infected: 129033
Period 300, Infected: 186127
Period 400, Infected: 213633
Period 500, Infected: 193702
Period 600, Infected: 173995
Period 700, Infected: 157966
Period 800, Infected: 138281
Period 900, Infected: 129381

Person representation
Each person is represented in 205 bytes. Four bytes to store the virus type this person is contracting, one byte to store how long has this person been infected, and 200 bytes to store how many times he has contracted each strain of virus (2 bit each). Perhaps there are some additional byte-alignment done by C++, but the total size will be around 200MB. I have two grids to store the next step, so total it uses around 400MB.
I store the location of infected people in a queue, to cut the time required in the early periods (which is really useful up to periods < 400).
Program technicalities
Every 100 steps this program will print the number of infected people, unless ANIMATE flag is set to true, in which case it will print the whole grid every 100ms.
This requires C++11 libraries (compile using -std=c++11 flag, or in Mac with clang++ -std=c++11 -stdlib=libc++ virus_spread.cpp -o virus_spread).
Run it without arguments for the default values, or with arguments like this:
./virus_spread 1 0.01 1000
#include <cstdio>
#include <cstring>
#include <random>
#include <cstdlib>
#include <utility>
#include <iostream>
#include <deque>
#include <cmath>
#include <functional>
#include <unistd.h>

typedef std::pair<int, int> pair;
typedef std::deque<pair> queue;

const bool ANIMATE = false;
const int MY_RAND_MAX = 999999;

std::default_random_engine generator(time(0));
std::uniform_int_distribution<int> distInt(0, MY_RAND_MAX);
auto randint = std::bind(distInt, generator);
std::uniform_real_distribution<double> distReal(0, 1);
auto randreal = std::bind(distReal, generator);

const int VIRUS_TYPE_COUNT = 800;
const int SIZE = 1000;
const int VIRUS_START_COUNT = 4;

typedef struct Person{
    int virusType;
    char time;
    uint32_t immune[VIRUS_TYPE_COUNT/16];
} Person;

Person people[SIZE][SIZE];
Person tmp[SIZE][SIZE];
queue infecteds;

double transmissionProb = 1.0;
double mutationProb = 0.01;
int periods = 1000;

char inline getTime(Person person){
    return person.time;
}

char inline getTime(int row, int col){
    return getTime(people[row][col]);
}

Person inline setTime(Person person, char time){
    person.time = time;
    return person;
}

Person inline addImmune(Person person, uint32_t type){
    person.immune[type/16] += 1 << (2*(type % 16));
    return person;
}

bool inline infected(Person person){
    return getTime(person) > 0;
}

bool inline infected(int row, int col){
    return infected(tmp[row][col]);
}

bool inline immune(Person person, uint32_t type){
    return (person.immune[type/16] >> (2*(type % 16)) & 3) == 3;
}

bool inline immune(int row, int col, uint32_t type){
    return immune(people[row][col], type);
}

Person inline infect(Person person, uint32_t type){
    person.time = 1;
    person.virusType = type;
    return person;
}

bool inline infect(int row, int col, uint32_t type){
    auto person = people[row][col];
    auto tmpPerson = tmp[row][col];
    if(infected(tmpPerson) || immune(tmpPerson, type) || infected(person) || immune(person, type)) return false;
    person = infect(person, type);
    infecteds.push_back(std::make_pair(row, col));
    tmp[row][col] = person;
    return true;
}

uint32_t inline getType(Person person){
    return person.virusType;
}

uint32_t inline getType(int row, int col){
    return getType(people[row][col]);
}

void print(){
    for(int row=0; row < SIZE; row++){
        for(int col=0; col < SIZE; col++){
            printf("%c", infected(row, col) ? (ANIMATE ? getType(row, col)+48 : '*') : '.');
        }
        printf("\n");
    }
}

void move(){
    for(int row=0; row<SIZE; ++row){
        for(int col=0; col<SIZE; ++col){
            people[row][col] = tmp[row][col];
        }
    }
}

int main(const int argc, const char **argv){
    if(argc > 3){
        transmissionProb = std::stod(argv[1]);
        mutationProb = std::stod(argv[2]);
        periods = atoi(argv[3]);
    }
    int row, col, size;
    uint32_t type, newType=0;
    char time;
    Person person;
    memset(people, 0, sizeof(people));
    for(int row=0; row<SIZE; ++row){
        for(int col=0; col<SIZE; ++col){
            people[row][col] = {};
        }
    }
    for(int i=0; i<VIRUS_START_COUNT; i++){
        row = randint() % SIZE;
        col = randint() % SIZE;
        if(!infected(row, col)){
            infect(row, col, 0);
        } else {
            i--;
        }
    }
    move();
    if(ANIMATE){
        print();
    }
    for(int period=0; period < periods; ++period){
        size = infecteds.size();
        for(int i=0; i<size; ++i){
            pair it = infecteds.front();
            infecteds.pop_front();
            row = it.first;
            col = it.second;
            person = people[row][col];
            time = getTime(person);
            if(time == 0) continue;
            type = getType(person);
            if(row > 0 && randreal() < transmissionProb){
                if(newType < VIRUS_TYPE_COUNT-1 && randreal() < mutationProb){
                    newType++;
                    if(!infect(row-1, col, newType)) newType--;
                } else {
                    infect(row-1, col, type);
                }
            }
            if(row < SIZE-1 && randreal() < transmissionProb){
                if(newType < VIRUS_TYPE_COUNT-1 && randreal() < mutationProb){
                    newType++;
                    if(!infect(row+1, col, newType)) newType--;
                } else {
                    infect(row+1, col, type);
                }
            }
            if(col > 0 && randreal() < transmissionProb){
                if(newType < VIRUS_TYPE_COUNT-1 && randreal() < mutationProb){
                    newType++;
                    if(!infect(row, col-1, newType)) newType--;
                } else {
                    infect(row, col-1, type);
                }
            }
            if(col < SIZE-1 && randreal() < transmissionProb){
                if(newType < VIRUS_TYPE_COUNT-1 && randreal() < mutationProb){
                    newType++;
                    if(!infect(row, col+1, newType)) newType--;
                } else {
                    infect(row, col+1, type);
                }
            }
            time += 1;
            if(time == 4) time = 0;
            person = setTime(person, time);
            if(time == 0){
                person = addImmune(person, type);
            } else {
                infecteds.push_back(std::make_pair(row, col));
            }
            tmp[row][col] = person;
        }
        if(!ANIMATE && period % 100 == 0) printf("Period %d, Size: %d\n", period, size);
        move();
        if(ANIMATE){
            printf("\n");
            print();
            usleep(100000);
        }
    }
    if(!ANIMATE){
        print();
    }
    return 0;
}

I really like this! My only question is how do you make the GIF?

I'm using this tool: http://linux.die.net/man/1/byzanz-record . Currently it doesn't have GUI, so you'll need to use the command line =D

Oh, that's nice, thanks! :)

C# 6-7 Minutes
Edit 2
I've finally(5 hours) generated a verbose output for close to 1000 periods(only 840 frames then it crashed) at 1000x1000, every 1 period, however its close to 160MB and requires all the memory on my system to display(IrfanView), not even sure that would work in a browser, may I'll put it up later.
EDIT
I've spent allot of time on making this more efficient per "Beta Decay"s answer stating "Choose the strain randomly" I have choosin only the random method for choosing who infects who per period, however I've changed the way that's calculated and threaded out every thing, I've updated my posts with the new details.
Coded my closest estimation to this I could, I hope it follows all the rules, it uses a ton of memory on my system(about 1.2GB). The program can output animated gifs(looks cool, really slow) or just a image matching "Beta Decay"s specs. This is a little bit of reinventing the wheel, but definitely looks cool:

Results
(Note: this only differentiates between infected and non infected, ie non-verbose)
1000 Periods, 1% Mutation Rate, 100% Spread:

Examples(Verbose)
Anyway using 100% "Probability of transmission" in non-verbose mode is kind of boring as you always get the same shapes and you can't see the different mutations, if you tweak the parameters around a-bit(and enable verbose mode) you get some cool looking output(animated GIFs display every 10th frame):
Random - Grid Size: 200, ProbTransmission: 100%, ProbMutation: 1%

Random - Grid Size: 200, ProbTransmission: 20%, ProbMutation: 1%

Scoring
I agree with "justhalf" that the scoring criteria may not be fair as every run will differ due to the randomness of mutations and position of random start points. Maybe we could do average of several runs or something like that..., well anyway this is in C# so bounty for me :( anyway.
Code
Make sure to include the MagickImage library(set to compile x64 bit) otherwise it won't build(http://pastebin.com/vEmPF1PM):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using ImageMagick;
using System.IO;

namespace Infection
{
    class Program
    {
        #region Infection Options
        private const double ProbabilityOfTransmission = .2;
        private const double ChanceOfMutation = 0.01;
        private const Int16 StageSize = 1000;
        private const Int16 MaxNumberOfMutations = 800;
        private const byte MaxInfectionTime = 3;
        private const byte NumberOfPeopleToRandomlyInfect = 4;
        private static int NumberOfPeriods = 1000;
        #endregion Infection Options

        #region Run Options
        private const bool VerbosMode = false;
        private const int ImageFrequency = 10;
        #endregion Run Options

        #region Stage
        private static Int16 MutationNumber = 1;

        private class Person
        {
            public Person()
            {
                PreviousInfections = new Dictionary<Int16, byte>();
                InfectionTime = 0;
                CurrentInfection = 0;
                PossibleNewInfections = new List<short>(4);
            }
            public Dictionary<Int16, byte> PreviousInfections { get; set; }
            public byte InfectionTime { get; set; }
            public Int16 CurrentInfection { get; set; }
            public List<Int16> PossibleNewInfections { get; set; }
        }
        private static Person[][] Stage = new Person[StageSize][];
        #endregion Stage

        static void Main(string[] args)
        {
            DateTime start = DateTime.UtcNow;

            //Initialize stage
            for (Int16 i = 0; i < Stage.Length; i++)
            {
                var tmpList = new List<Person>();
                for (Int16 j = 0; j < Stage.Length; j++)
                    tmpList.Add(new Person());
                Stage[i] = tmpList.ToArray();
            }

            //Randomly infect people
            RandomlyInfectPeople(NumberOfPeopleToRandomlyInfect);

            //Run through the periods(NumberOfPeriods times)
            List<MagickImage> output = new List<MagickImage>();
            while (NumberOfPeriods > 0)
            {
                //Print details(verbose)
                if (VerbosMode && NumberOfPeriods % ImageFrequency == 0)
                {
                    Console.WriteLine("Current Number: " + NumberOfPeriods);
                    Console.WriteLine("Current Mutation: " + MutationNumber);
                    output.Add(BoardToImage());
                }

                Period();
            }

            //Outputs a Animated Gif(verbose)
            if (VerbosMode)
            {
                ImagesToAnimatedGIF(output.ToArray(), Directory.GetCurrentDirectory() + "\\Output.gif");
                System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + "\\Output.gif");
            }
            //Only outputs the basic result image matching the specs
            SaveBoardToSimpleImage(Directory.GetCurrentDirectory() + "\\FinalState.gif");

            Console.WriteLine("Total run time in seconds: " + (DateTime.UtcNow - start).TotalSeconds);
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }

        #region Image
        private static void SaveBoardToSimpleImage(string filepath)
        {
            using (Bitmap img = new Bitmap(StageSize, StageSize))
            {
                for (int i = 0; i < img.Width; i++)
                    for (int j = 0; j < img.Height; j++)
                        img.SetPixel(i, j, Stage[i][j].CurrentInfection == 0 ? Color.FromArgb(255, 255, 255) :
                            Color.FromArgb(64, 255, 0));
                img.Save(filepath, ImageFormat.Gif);
            }
        }
        private static MagickImage BoardToImage()
        {
            using (Bitmap img = new Bitmap(StageSize, StageSize))
            {
                for (int i = 0; i < img.Width; i++)
                    for (int j = 0; j < img.Height; j++)
                        img.SetPixel(i, j, Stage[i][j].CurrentInfection == 0 ? Color.White :
                            Color.FromArgb(Stage[i][j].CurrentInfection % 255,
                            Math.Abs(Stage[i][j].CurrentInfection - 255) % 255,
                            Math.Abs(Stage[i][j].CurrentInfection - 510) % 255));
                return new MagickImage(img);
            }
        }
        private static void ImagesToAnimatedGIF(MagickImage[] images, string filepath)
        {
            using (MagickImageCollection collection = new MagickImageCollection())
            {
                foreach (var image in images)
                {
                    collection.Add(image);
                    collection.Last().AnimationDelay = 20;
                }
                collection.Write(filepath);
            }
        }
        #endregion Image

        #region Infection
        private static void Period()
        {
            Infect();
            ChooseRandomInfections();
            IncrementDiseaseProgress();
            Cure();

            NumberOfPeriods--;
        }
        private static void Cure()
        {
            Parallel.For(0, Stage.Length, i =>
            {
                for (Int16 j = 0; j < Stage.Length; j++)
                    if (Stage[i][j].CurrentInfection != 0 && Stage[i][j].InfectionTime == MaxInfectionTime + 1)
                    {
                        //Add disease to already infected list
                        if (Stage[i][j].PreviousInfections.ContainsKey(Stage[i][j].CurrentInfection))
                            Stage[i][j].PreviousInfections[Stage[i][j].CurrentInfection]++;
                        else
                            Stage[i][j].PreviousInfections.Add(Stage[i][j].CurrentInfection, 1);

                        //Cure
                        Stage[i][j].InfectionTime = 0;
                        Stage[i][j].CurrentInfection = 0;
                    }
            });
        }
        private static void IncrementDiseaseProgress()
        {
            Parallel.For(0, Stage.Length, i =>
            {
                for (Int16 j = 0; j < Stage.Length; j++)
                    if (Stage[i][j].CurrentInfection != 0)
                        Stage[i][j].InfectionTime++;
            });
        }
        private static void RandomlyInfectPeople(Int16 numberOfPeopleToInfect)
        {
            var randomList = new List<int>();
            while (randomList.Count() < numberOfPeopleToInfect * 2)
            {
                randomList.Add(RandomGen2.Next(StageSize));
                randomList = randomList.Distinct().ToList();
            }
            while (randomList.Count() > 0)
            {
                Stage[randomList.Last()][randomList[randomList.Count() - 2]].CurrentInfection = MutationNumber;
                Stage[randomList.Last()][randomList[randomList.Count() - 2]].InfectionTime = 1;
                randomList.RemoveAt(randomList.Count() - 2);
                randomList.RemoveAt(randomList.Count() - 1);
            }
        }
        private static void Infect()
        {
            Parallel.For(0, Stage.Length, i =>
            {
                for (Int16 j = 0; j < Stage.Length; j++)
                    InfectAllSpacesAround((short)i, j);
            });
        }
        private static void InfectAllSpacesAround(Int16 x, Int16 y)
        {
            //If not infected or just infected this turn return
            if (Stage[x][y].CurrentInfection == 0 || (Stage[x][y].CurrentInfection != 0 && Stage[x][y].InfectionTime == 0)) return;

            //Infect all four directions(if possible)
            if (x > 0)
                InfectOneSpace(Stage[x][y].CurrentInfection, (short)(x - 1), y);

            if (x < Stage.Length - 1)
                InfectOneSpace(Stage[x][y].CurrentInfection, (short)(x + 1), y);

            if (y > 0)
                InfectOneSpace(Stage[x][y].CurrentInfection, x, (short)(y - 1));

            if (y < Stage.Length - 1)
                InfectOneSpace(Stage[x][y].CurrentInfection, x, (short)(y + 1));
        }
        private static void InfectOneSpace(Int16 currentInfection, Int16 x, Int16 y)
        {
            //If the person is infected, or If they've already been infected "MaxInfectionTime" then don't infect
            if (Stage[x][y].CurrentInfection != 0 || (Stage[x][y].PreviousInfections.ContainsKey(currentInfection) &&
                    Stage[x][y].PreviousInfections[currentInfection] >= MaxInfectionTime)) return;

            //If random is larger than change of transmission don't transmite disease
            if (RandomGen2.Next(100) + 1 > ProbabilityOfTransmission * 100) return;

            //Possible mutate
            if (MutationNumber <= MaxNumberOfMutations && RandomGen2.Next(100) + 1 <= ChanceOfMutation * 100)
                lock (Stage[x][y])
                {
                    MutationNumber++;
                    Stage[x][y].PossibleNewInfections.Add(MutationNumber);
                }
            //Regular infection
            else
                lock (Stage[x][y])
                    Stage[x][y].PossibleNewInfections.Add(currentInfection);

        }
        private static void ChooseRandomInfections()
        {
            Parallel.For(0, Stage.Length, i =>
            {
                for (Int16 j = 0; j < Stage.Length; j++)
                {
                    if (Stage[i][j].CurrentInfection != 0 || !Stage[i][j].PossibleNewInfections.Any()) continue;
                    Stage[i][j].CurrentInfection = Stage[i][j].PossibleNewInfections[RandomGen2.Next(Stage[i][j].PossibleNewInfections.Count)];
                    Stage[i][j].PossibleNewInfections.Clear();
                    Stage[i][j].InfectionTime = 0;
                }
            }
            );
        }
        #endregion Infection
    }

    //Fancy Schmancy new random number generator for threaded stuff, fun times
    //http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx
    public static class RandomGen2
    {
        private static Random _global = new Random();
        [ThreadStatic]
        private static Random _local;

        public static int Next()
        {
            Random inst = _local;
            if (inst == null)
            {
                int seed;
                lock (_global) seed = _global.Next();
                _local = inst = new Random(seed);
            }
            return inst.Next();
        }

        public static int Next(int input)
        {
            Random inst = _local;
            if (inst == null)
            {
                int seed;
                lock (_global) seed = _global.Next();
                _local = inst = new Random(seed);
            }
            return inst.Next(input);
        }
    }
}


text:
Draw an Apollonian Gasket
Given three mutually tangent circles, we can always find two more circles which are tangent to all three of those. These two are called Apollonian circles. Note that one of the Apollonian circles might actually be around the three initial circles.
Starting from three tangent circles, we can create a fractal called an Apollonian gasket, by the following process:

Call the initial 3 circles the parent circles
Find the parent circles' two Apollonian circles
For each Apollonian circle:

For each pair of the three pairs of parent circles:

Call the Apollonian circle and the two parent circles the new set of parent circles and start over from step 2.

E.g. starting with circles of equal size, we get:

Image found on Wikipedia
There's one more bit of notation we need. If we have a circle of radius r with centre (x, y), we can define it's curvature as k = ±1/r. Usually k will be positive, but we can use negative k to denote the circle that encloses all the other circles in the gasket (i.e. all tangents touch that circle from the inside). Then we can specify a circle with a triplet of numbers: (k, x*k, y*k).
For the purpose of this question, we will assume positive integer k and rational x and y.
Further examples for such circles can be found in the Wikipedia article.
There's also some interesting stuff about integral gaskets in this article (among other fun things with circles).
The Challenge
You will be given 4 circle specifications, each of which will look like (14, 28/35, -112/105). You can use any list format and division operator that is convenient, such that you can simply eval the input if you wish to. You may assume that the 4 circles are indeed tangent to each other, and that the first of them has negative curvature. That means you are already given the surrounding Apollonian circle of the other three. For a list of valid example inputs, see the bottom of the challenge.
Write a program or function which, given this input, draws an Apollonian gasket.
You may take input via function argument, ARGV or STDIN and either render the fractal on screen or write it to an image file in a format of your choice.
If the resulting image is rasterised, it must be at least 400 pixels on each side, with less than 20% padding around the largest circle. You may stop recursing when you reach circles whose radius is less than a 400th of the largest input circle, or circles which are smaller than a pixel, whichever happens first.
You must draw only circle outlines, not full discs, but the colours of background and lines are your choice. The outlines must not be wider than a 200th of the outer circles diameter.
This is code golf, so the shortest answer (in bytes) wins.
Example Inputs
Here are all integral gaskets from the Wikipedia article converted to the prescribed input format:
[[-1, 0, 0], [2, 1, 0], [2, -1, 0], [3, 0, 2]]
[[-2, 0, 0], [3, 1/2, 0], [6, -2, 0], [7, -3/2, 2]]
[[-3, 0, 0], [4, 1/3, 0], [12, -3, 0], [13, -8/3, 2]]
[[-3, 0, 0], [5, 2/3, 0], [8, -4/3, -1], [8, -4/3, 1]]
[[-4, 0, 0], [5, 1/4, 0], [20, -4, 0], [21, -15/4, 2]]
[[-4, 0, 0], [8, 1, 0], [9, -3/4, -1], [9, -3/4, 1]]
[[-5, 0, 0], [6, 1/5, 0], [30, -5, 0], [31, -24/5, 2]]
[[-5, 0, 0], [7, 2/5, 0], [18, -12/5, -1], [18, -12/5, 1]]
[[-6, 0, 0], [7, 1/6, 0], [42, -6, 0], [43, -35/6, 2]]
[[-6, 0, 0], [10, 2/3, 0], [15, -3/2, 0], [19, -5/6, 2]]
[[-6, 0, 0], [11, 5/6, 0], [14, -16/15, -4/5], [15, -9/10, 6/5]]
[[-7, 0, 0], [8, 1/7, 0], [56, -7, 0], [57, -48/7, 2]]
[[-7, 0, 0], [9, 2/7, 0], [32, -24/7, -1], [32, -24/7, 1]]
[[-7, 0, 0], [12, 5/7, 0], [17, -48/35, -2/5], [20, -33/35, 8/5]]
[[-8, 0, 0], [9, 1/8, 0], [72, -8, 0], [73, -63/8, 2]]
[[-8, 0, 0], [12, 1/2, 0], [25, -15/8, -1], [25, -15/8, 1]]
[[-8, 0, 0], [13, 5/8, 0], [21, -63/40, -2/5], [24, -6/5, 8/5]]
[[-9, 0, 0], [10, 1/9, 0], [90, -9, 0], [91, -80/9, 2]]
[[-9, 0, 0], [11, 2/9, 0], [50, -40/9, -1], [50, -40/9, 1]]
[[-9, 0, 0], [14, 5/9, 0], [26, -77/45, -4/5], [27, -8/5, 6/5]]
[[-9, 0, 0], [18, 1, 0], [19, -8/9, -2/3], [22, -5/9, 4/3]]
[[-10, 0, 0], [11, 1/10, 0], [110, -10, 0], [111, -99/10, 2]]
[[-10, 0, 0], [14, 2/5, 0], [35, -5/2, 0], [39, -21/10, 2]]
[[-10, 0, 0], [18, 4/5, 0], [23, -6/5, -1/2], [27, -4/5, 3/2]]
[[-11, 0, 0], [12, 1/11, 0], [132, -11, 0], [133, -120/11, 2]]
[[-11, 0, 0], [13, 2/11, 0], [72, -60/11, -1], [72, -60/11, 1]]
[[-11, 0, 0], [16, 5/11, 0], [36, -117/55, -4/5], [37, -112/55, 6/5]]
[[-11, 0, 0], [21, 10/11, 0], [24, -56/55, -3/5], [28, -36/55, 7/5]]
[[-12, 0, 0], [13, 1/12, 0], [156, -12, 0], [157, -143/12, 2]]
[[-12, 0, 0], [16, 1/3, 0], [49, -35/12, -1], [49, -35/12, 1]]
[[-12, 0, 0], [17, 5/12, 0], [41, -143/60, -2/5], [44, -32/15, 8/5]]
[[-12, 0, 0], [21, 3/4, 0], [28, -4/3, 0], [37, -7/12, 2]]
[[-12, 0, 0], [21, 3/4, 0], [29, -5/4, -2/3], [32, -1, 4/3]]
[[-12, 0, 0], [25, 13/12, 0], [25, -119/156, -10/13], [28, -20/39, 16/13]]
[[-13, 0, 0], [14, 1/13, 0], [182, -13, 0], [183, -168/13, 2]]
[[-13, 0, 0], [15, 2/13, 0], [98, -84/13, -1], [98, -84/13, 1]]
[[-13, 0, 0], [18, 5/13, 0], [47, -168/65, -2/5], [50, -153/65, 8/5]]
[[-13, 0, 0], [23, 10/13, 0], [30, -84/65, -1/5], [38, -44/65, 9/5]]
[[-14, 0, 0], [15, 1/14, 0], [210, -14, 0], [211, -195/14, 2]]
[[-14, 0, 0], [18, 2/7, 0], [63, -7/2, 0], [67, -45/14, 2]]
[[-14, 0, 0], [19, 5/14, 0], [54, -96/35, -4/5], [55, -187/70, 6/5]]
[[-14, 0, 0], [22, 4/7, 0], [39, -12/7, -1/2], [43, -10/7, 3/2]]
[[-14, 0, 0], [27, 13/14, 0], [31, -171/182, -10/13], [34, -66/91, 16/13]]
[[-15, 0, 0], [16, 1/15, 0], [240, -15, 0], [241, -224/15, 2]]
[[-15, 0, 0], [17, 2/15, 0], [128, -112/15, -1], [128, -112/15, 1]]
[[-15, 0, 0], [24, 3/5, 0], [40, -5/3, 0], [49, -16/15, 2]]
[[-15, 0, 0], [24, 3/5, 0], [41, -8/5, -2/3], [44, -7/5, 4/3]]
[[-15, 0, 0], [28, 13/15, 0], [33, -72/65, -6/13], [40, -25/39, 20/13]]
[[-15, 0, 0], [32, 17/15, 0], [32, -161/255, -16/17], [33, -48/85, 18/17]]

Your example illustration seems to have only included the "inside" apollonian circles after the first operation.

@Sparr I'm not sure what you mean. After the first operation, one of the two Apollonian circles already exists (the original parent circle that you didn't pick for the current iteration) and you're only looking for the other solution.

Never mind, you're right, I was mis-reading.

GolfScript (289 bytes vector / 237 bytes raster)
At 289 bytes and executing in a reasonable time:
'/'/n*','/']['*0,`1/*~1.$[]*(~-400*:&;{1+1=*}/:D;{{1+2<~D@*\/}%}%'<svg><g fill="none" stroke="red">'puts.{[[~@:b[D&*\abs]{@&*[b]+}2*]{'.0/'*'"#{
}"'n/*~}%'<circle r="
" cx="
" cy="
" />'n/\]zip puts}:|/[{.([.;]+}3*]{(:?zip{)\~++2*\-}%:c.|0=D&*<{?);[c]+[{([.;]+.}3*;]+}*.}do'</g></svg>'

This takes input on stdin and generates an SVG file to stdout. Unfortunately it takes a bit too long for an online demo, but a tweaked version which aborts early can give you an idea.
Given input [[-2, 0, 0], [3, 1/2, 0], [6, -2, 0], [7, -3/2, 2]] the output (converted to PNG with InkScape) is

At 237 bytes and taking far too long (I extrapolate that it would take just over a week to produce similar output to the above, although in one-bit black and white):
'/'/n*','/']['*0,`1/*~1.$[]*(~-400*:&;{1+1=*}/:D;{{1+2<~D@*\/}%}%.[{.([.;]+}3*]{(:?[zip{)\~++2*\-}%:c]@+\0c=D&*<{?);[c]+[{([.;]+.}3*;]+}*.}do;:C;'P1 ''801 '2*.~:B*,{:P;C{:?[0=2/.D&*-.*\D&*+.*]{2,{P{B/}2$*B%400-?0=*\)?=&*-.*}/+<},,1=},!}/

Output is NetPBM format without newlines, so possibly doesn't strictly follow the spec, although the GIMP will still load it. If strict conformance is required, insert an n after the last !.
The rasterisation is by testing each pixel against each circle, so the time taken is pretty much linear in the number of pixels times the number of circles. By downscaling everything by a factor of 10,
'/'/n*','/']['*0,`1/*~1.$[]*(~-40*:&;{1+1=*}/:D;{{1+2<~D@*\/}%}%.[{.([.;]+}3*]{(:?[zip{)\~++2*\-}%:c]@+\0c=D&*<{?);[c]+[{([.;]+.}3*;]+}*.}do;:C;'P1 ''81 '2*.~:B*,{:P;C{:?[0=2/.D&*-.*\D&*+.*]{2,{P{B/}2$*B%40-?0=*\)?=&*-.*}/+<},,1=},!}/

will run in 10 minutes and produce

(converted to PNG with the GIMP). Given 36 hours it produced the 401x401

I never would've thought you could do graphical output with Golfscript...

JavaScript (418 410 bytes)
Implemented as a function:
function A(s){P='<svg><g fill=none stroke=red transform=translate(400,400)>';Q=[];s=eval(s);S=-400*s[0][0];function d(c){P+='<circle r='+Math.abs(p=S/c[0])+' cx='+p*c[1]+' cy='+p*c[2]+' />'}for(c=4;c--;d(s[0]),s.push(s.shift()))Q.push(s.slice());for(;s=Q.shift();d(c)){c=[];for(i=4;i--;)c[i]=2*(s[0][i]+s[1][i]+s[2][i])-s[3][i];for(i=6;c[0]<S&&i;)Q.push([s[i--%3],s[i--%3],c,s[i%3]])}document.body.innerHTML=P}

Online demo (note: doesn't work in browsers which fail to honour the SVG spec's requirements with respect to implicit sizing, so I offer a slightly longer version which works around that bug; browsers may also render the SVG less accurately than e.g. Inkscape, although Inkscape is a bit stricter on quoting attributes).
Note that 8 bytes could be saved by using document.write, but that seriously borks jsFiddle.

You can probably save more by defining the function with ES6 and storing, e.g., S/c[0] in a variable and then also get rid of Math.abs with a ternary operator etc.

@IngoBürk, if I were going to go the ES6 route then I'd write it in CoffeeScript instead.

use the host c99.nl. It allows document.write.

Good to see an answer to this:)

Updated with @IngoBürk's suggestion for a temporary variable. Eliminating Math.abs would actually cost a character.

Mathematica 289 characters
By solving the bilinear system as per http://arxiv.org/pdf/math/0101066v1.pdf Theorem 2.2 (highly inefficient).
Spaces not needed, still golfing it:
w = {k, x, y};
d = IdentityMatrix;
j = Join;
p_~f~h_ := If[#[[-1, 1]] < 6! h,
    q = 2 d@4 - 1;
    m = #~j~{w};
    r = Complement[w /. NSolve[ And @@ j @@
                        MapThread[Equal, {Thread@m.q.m, 4 d@3 {0, 1, 1}}, 2], w], a];
    If[r != {},
     a~AppendTo~# & @@ r;
     Function[x, x~j~{#}~f~h & /@ r]@#]] & /@ p~Subsets~{3};
Graphics[Circle @@@ ({{##2}, 1}/# & @@@ (f[a = #, -Tr@#]; a))] &

A reduced size animation with input {{-13, 0, 0}, {23, 10/13, 0}, {30, -84/65, -1/5}, {38, -44/65, 9/5}}

How do you take input?

@MartinBüttner as a function argument, by adding @{{-1, 0, 0}, {2, 1, 0}, {2, -1, 0}, {3, 0, 2}} to the last line

@MartinBüttner If you're going to test it try first with 50/h instead of 400/h. You're going to get the result faster. also, you can monitor the progress by entering Dynamic@Length@a before executing the function

Instructions for testing this answer (with a reduced number of circles) without Mathematica installed: 1) Download this from pastebin and save it as *.CDF 2) Download and install the free CDF environment from Wolfram Research at (not a small file). Enjoy. Tell me if it works!-- Note: Calcs are slow, wait for the graphics to come up.

What does the "highly inefficient" comment refer to? Is it that (looking at the animation) you're apparently drawing most of the circles at least twice? I think the complex Descartes approach is inherently as efficient as it gets.

That was a weird edit, considering that the challenge is scored in bytes, not characters.

@MartinBüttner In this case both counts agree. I edited it because I linked it to a question in Mathematica.se (I didn't want to replicate it since it's probably OT there) where people aren't used to the "languageXXX NNN" notation. I forgot it would bump, sorry.

@belisarius Of course they agree, but it seemed a bit misleading. No big deal. It reminded me to add some LaTeX to the spec. ;)

Maple (960 bytes)
I used Descartes Theorem to generate the Apollonian Gasket and then use Maple's plotting system to plot it. If I have time I want to further golf this and and change it to Python (Maple is definitely not the best for fractals). Here is a link to a free Maple player if you want to run my code.
X,Y,Z,S,N:=abs,evalf,member,sqrt,numelems;
f:=proc(J)
    L:=map((x)->[x[1],(x[2]+x[3]*I)/x[1]+50*(1+I)/X(J[1][2])],J);
    R:=Vector([L]);
    T,r:=X(L[1][3]),L[1][4];
    A(L[1][5],L[2][6],L[3][7],L[1][8],L[2][9],L[3][10],R,T,r);
    A(L[1][11],L[2][12],L[4][13],L[1][14],L[2][15],L[4][16],R,T,r);
    A(L[1][17],L[3][18],L[4][19],L[1][20],L[3][21],L[4][22],R,T,r);
    A(L[2][23],L[3][24],L[4][25],L[2][26],L[3][27],L[4][28],R,T,r);
    plots[display](seq(plottools[circle]([Re(R[i][29]),Im(R[i][30])],X(1/R[i][31])),i=1..N(R))):
end proc:
A:=proc(a,b,c,i,j,k,R,E,F)
    K:=i+k+j+2*S(i*k+i*j+k*j);
    if K>400*E then
    return;
    end if;
    C:=(a*i+c*k+b*j+2*S(a*c*i*k+b*c*j*k+a*b*i*j))/K;
    C2:=(a*i+c*k+b*j-2*S(a*c*i*k+b*c*j*k+a*b*i*j))/K;
    if Y(X(C-F))<1/E and not Z([K,C],R) then
    R(N(R)+1):=[K,C];
    A(a,b,C,i,j,K,R,E,F);
    A(a,c,C,i,k,K,R,E,F);
    A(b,c,C,j,k,K,R,E,F);
    end if:
    if Y(X(C2-F))<1/E and not Z([K,C2],R) then
    R(N(R)+1):=[K,C2];
    A(a,b,C2,i,j,K,R,E,F);
    A(a,c,C2,i,k,K,R,E,F);
    A(b,c,C2,j,k,K,R,E,F);
    end if:
end proc:

Some sample gaskets
f([[-1, 0, 0], [2, 1, 0], [2, -1, 0], [3, 0, 2]]);

f([[-9, 0, 0], [14, 5/9, 0], [26, -77/45, -4/5], [27, -8/5, 6/5]]);

authors: Кирилл Хлапониной-Казаковой


text:
Preprocessing primality
The challenge:
Given an integer N, 1 < N < 2³¹, write code that uses the C preprocessor
to determine whether N is prime, and produces a "Hello world" program if N is prime,
or an error otherwise. Make the code as short as possible.
It's not very hard, so don't worry that there are so many rules; most
of them are boilerplate.
The following sample code (in example.c) works for N < 100:
#include <stdio.h>
int main() {
#if (N%2!=0 && N%3!=0 && N%5!=0 && N%7!=0) || (2==N || 3==N || 5==N || 7==N)
printf("Hello world!");
#else
Walkmen;
#endif
}

23 is prime but 99 is not, so:
c:\golf\preprime>gcc -std=c99 -DN=23 example.c

c:\golf\preprime>a
Hello world!
c:\golf\preprime>gcc -std=c99 -DN=99 example.c
example.c: In function 'main':
example.c:6:1: error: 'Walkmen' undeclared (first use in this function)
 Walkmen;
 ^
example.c:6:1: note: each undeclared identifier is reported only once for each function it appears in
c:\golf\preprime>

Rules

1 < N < 2147483648
N will be defined in a macro named N. N will be written using only the characters 0123456789 and will not begin with 0.
The code will be compiled with the command gcc -std=c99 -DN=<number> <filename>.c [-o <outfile>]
If N is prime, a valid C99 program must be successfully compiled. When executed, the program's output to stdout must be precisely Hello world! followed by zero or more newlines.
If N is composite, gcc must emit a compiler error. A linker error is not acceptable.
You may not utilize any GCC extensions.
You may not assume anything about the name of any file.
Note: It is not allowed to use implicit types or implicit function declarations.
Neither gcc nor any "Hello world" program may take more than 20 seconds to execute on a typical computer.
Shortest code length in UTF-8 bytes wins.

For reference, my ungolfed implementation is 571 bytes. Happy golfing!

441 characters
OK, here is another approach — this time breaking things down into a giant binary tree of tests. I was hoping this could be done recursively, but the C preprocessor doesn't support recursive functions...so I did this as a fallback.
Algorithm: This tests N for divisibility by 2 and by all odd numbers up to the square root of 2³². (Note: That's a bit of overkill, because it need only test potential divisors up to the square root of 2³¹, but it's easier to stick to powers of 2.)
#define A(x) (N%(x)||N==x)
#define B(x) A(x)&A(x+2)&A(x+4)&A(x+6)
#define C(x) B(x)&B(x+8)&B(x+16)&B(x+24)
#define D(x) C(x)&C(x+32)&C(x+64)&C(x+96)
#define E(x) D(x)&D(x+128)&D(x+256)&D(x+384)
#define F(x) E(x)&E(x+512)&E(x+1024)&E(x+1536)
#define G(x) F(x)&F(x+2048)&F(x+4096)&F(x+6144)
#define H(x) G(x)&G(x+8192)&G(x+16384)&G(x+24576)
#include <stdio.h>
int main(){
#if A(2)&H(3)&H(32771)
printf("Hello world!");
#else
Walkmen;
#endif
}

Notes:

The value 32771 is really just 3+32768.
Yes, the parentheses around x in N%(x) are indeed needed (but not in N==x).
Compiles as per instructions and obeys rules of output.
Elapsed time for each test of N (e.g., each invocation of the compiler) is about 1/6 second on my machine.

Nice. It's not required to write "Walkmen" :)

boost/preprocessor, 355
#ifndef I
#include "boost/preprocessor.hpp"
#include "boost/preprocessor/slot/counter.hpp"
#include "stdio.h"
#define I BOOST_PP_COUNTER
#define F(z,x,d){int a[((x|d<<8)<2||(x|d<<8)==N||N%(x|d<<8))-1];}
int main(){
#include __FILE__
printf("Hello world!");}
#elif I<182
BOOST_PP_REPEAT(256,F,I)
#include BOOST_PP_UPDATE_COUNTER()
#include __FILE__
#endif

boost/preprocessor is part of the boost extension to the standard library for preprocessor programming.
We need both the BOOST_PP_REPEAT and the BOOST_PP_COUNTER + self-include approaches because of the limitations of the system.
gcc only supports a nested include depth of 200, so the counter approach alone is insufficient.
BOOST_PP_REPEAT is limited to repeating 256 times, so it doesn't work alone either.
With both approaches together we get up to 51200 repetitions; we need only 46340 (sqrt 2^31) to cover all possible primes.
To actually cause compilation failure we need to generate some code whoses validity depends on primality (since we can't chain together an #if if we're using #includes). The easiest way is to declare an array who's length depends on N%i, since negative array lengths produce a gcc compiler error.
As a bonus the number of error messages is equal to the number of factors :).
Examples
$  gcc -std=c99 -DN=24 primes.c
In file included from primes.c:8:
primes.c: In function ‘main’:
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative
primes.c:11: error: size of array ‘a’ is negative

$  gcc -std=c99 -DN=23 primes.c && ./a.out
Hello world!

Genius. Especially the 200*256 > √2³¹ part.

Love the self-inclusion. I tried N = 1338557220 for 18 MB of errors.


text:
Find one point per pyramidal region
Consider 3 dimensional space which has been partitioned by at least two planes  which go through the origin.  If there are n planes then the number of distinct pyramidal regions this creates is exactly 2 - n + n^2 as long as they are in "general position", a term I make specific below.

The challenge is write code that will return one point per pyramidal region. That is to return 2 - n + n^2 points in 3d space, each of which is in a different pyramidal region.

Notice that a plane through the origin can be defined by a single vector starting at the origin which is orthogonal to the plane.
Your code should take a list of planes in as input, each plane being described by a vector from the origin which is orthogonal to it.  The vector itself is just represented as a space separated list of three numbers. Your should output a list of 2 - n + n^2 points. You can assume the planes are in general position, that is that no three of the vectors defining the planes are coplanar.
I will verify that the points are really all in different pyramidal regions using the following code.
Let us assume the variable planes contains an array of vectors, each one of which defines the plane. For example, let n = 4, the planes could equal
[[ 0.44060338 -0.55711491 -0.70391167]
 [ 0.15640806  0.89972402  0.40747172]
 [-0.48916566  0.86280671  0.12759912]
 [ 0.25920378 -0.94828262  0.18323068]]

We can then choose a number of points and put them in a 2d array called testpoints.  To determine if they are all in distinct pyramidal regions we can call the following Python function which just looks to see which side of each plane the points are on and checks that each point is on at least one different side from every other point.
def all_in_distinct_pyramidal_regions(testpoints, planes):
    signs = np.sign(np.inner(testpoints, hyperplanes))
    return (len(set(map(tuple,signs)))==len(signs))

You can create some random test planes by first sampling points on a sphere and then using those points to define the hyperplanes. Here is a Python function that does this sampling.
import numpy as np
def points_on_sphere(N, norm=np.random.normal):
    """
    http://en.wikipedia.org/wiki/N-sphere#Generating_random_points
    """
    normal_deviates = norm(size=(N, 3))
    radius = np.sqrt((normal_deviates ** 2).sum(axis=0))
    points = normal_deviates / radius
    return points

You can use any language you choose for which there is a free and easy way to run the code in Linux. You can use any standard libraries of that language.  I will however want to test your code so please give full instructions for how to run it.
Code to produce 10 random points on a sphere can be run using http://ideone.com/cuaHy5 .
Here is a picture of the 4 planes described above along with 2 - 4 + 16 = 14 points, one in each of the pyramidal regions created by the planes.

A valid output for this instance would therefore be the 14 points.
0.96716439  0.21970818  0.12775507
-0.84226594 -0.37162037 -0.39049504
0.60145419  0.58557551 -0.54346497
-0.4850864   0.26433373 -0.83355796
-0.69380885 -0.62124759  0.36425364
0.09880807 -0.09275638  0.99077405
0.19131628 -0.97946254 -0.06364919
-0.98100047  0.17593773 -0.08175574
-0.76331009  0.63554838 -0.11591362
0.89104146  0.34728895  0.29229352
-0.61696755 -0.26411912  0.74134482
0.18382632 -0.03398322 -0.98237112
-0.44983933 -0.18244731  0.87427545
0.8391045   0.18244157 -0.51246338

Makes no sense to me. How can planes form a cone? Plane are square, cone are round ???

@feersum Imagine cutting a cone shape using planes. You are right you don't get a very good cone unless you use a lot of planex as the sides are flat but one end is a point (the origin) and the other unbounded.

This could really do with a better explanation, a picture, and a reference to the foumula. I haven't a clue what you mean by a cone here. Also, I considered that the faces of a tetrahedron if extended infinitely will divide space into a finite closed space (the tetrahedron) plus 14 infinite regions, which matches your formula, but there are other cases (such as the cube, 6 faces + 8 corners + 12 edges = 26 infinite regions) which don't match your formula (2-6+36=32) so the only thing I could guess you might mean seems wrong. Please clarify.

@steveverrill I added a picture and also an example valid output for the 4 planes described in the question. If anything is still unclear, please let me know.

@feersum Cone has a different meaning in linear algebra as a set of points closed under scaling: http://en.wikipedia.org/wiki/Cone_(linear_algebra)

@xnor I changed the word cone so I hope it is less controversial now. I am sad about the close vote however :(

@steveverrill Added a link for the formula too now.

I'm willing to give it a shot, but my solution would just be a grid search over increasingly fine spherical meshes, which is pretty boring. Are you OK with this kind of solution?

@COTO Cool! As long as it gives the correct answer to all the fiendish test cases I make it will be accepted :)

What is the minimal number of planes the program should handle?

@Ell, "Consider 3 dimensional space which has been partitioned by at least two planes which go through the origin"

Python, 423 376 353
S=sum
from numpy import*
C=cross
e=1e-15
def P(N,I,M):
 if M:v=M[0];L=[C(n,v)for m in N for n in-m,m if all(dot(N,C(n,v))<e)];[P(N+[u*v],[i for i in I if all(dot(N+[u*v],i)<e)]+L,M[1:])for u in-1,1]if L else P(N,I,M[1:])
 else:
    for u in-1,1:print list(u*S(I))
N=map(array,input())
a,b=N[:2]
c=C(a,b)
for u in-1,1:P([a,u*b],[c,-c,C(a,c)+u*C(b,c)],N[2:])

Reads a list of comma-separated triplets from STDIN and writes a list of triplets to STDOUT.
Assumes at least two planes are given.
Example
$ python cone.py <<< [0.44060338,-0.55711491,-0.70391167],[0.15640806,0.89972402,0.40747172],[-0.48916566,0.86280671,0.12759912],[0.25920378,-0.94828262,0.18323068]
[0.50892804716566153, 0.17353382779474077, -1.1968194626314141]
[-0.50892804716566153, -0.17353382779474077, 1.1968194626314141]
[0.1422280331828244, -0.62348456475000202, -0.24583080842150512]
[-0.1422280331828244, 0.62348456475000202, 0.24583080842150512]
[-1.2182327603643608, 0.1230166261435828, -1.5722574943149592]
[1.2182327603643608, -0.1230166261435828, 1.5722574943149592]
[-1.5849327743471977, -0.67400176640115994, -0.62126884010505024]
[1.5849327743471977, 0.67400176640115994, 0.62126884010505024]
[2.0938608215128593, 0.84753559419590085, -0.5755506225263638]
[-2.0938608215128593, -0.84753559419590085, 0.5755506225263638]
[1.7271608075300224, 0.050517201651157972, 0.37543803168354511]
[-1.7271608075300224, -0.050517201651157972, -0.37543803168354511]
[0.36670001398283714, 0.79701839254474283, -0.95098865420990886]
[-0.36670001398283714, -0.79701839254474283, 0.95098865420990886]

How it works
Note that when three planes (whose normals are non-coplanar) partition the space, each of the eight resulting regions is bounded by (subsets of) all three planes.
If we added a plane, it would divide some of the regions in two, resulting, again, in a pair of subregions bounded by at least three planes.
Any cross-section of such a region is a polygon, whose vertices lie on the lines of intersection of the planes bounding the region.
Moreover, since these planes extend to infinity (as planes usually do), the polygon is necessarily convex, the upshot of which is that the region is closed under addition.
In particular, if we take one vector along each line of intersection of a pair of bounding planes that lies within the region, the sum of these vectors is also within the region and not on any of the planes (and, hence, not in any other region.)
The program recursively partitions the space by incrementally adding planes and subdividing the currently-explored region, while keeping a track of vectors along the lines of intersection and eventually taking their sum.
This method breaks if only two planes are given, since then there's only one line of intersection. We treat this as a special case and return the sum of a pair of vectors, each of which lies on a different plane, taking the four different sign combinations.

Thank you for this! I haven't managed to decrypt it yet  so any explanation gratefully accepted. In reply to your question, ideally it should work up to about 1000 planes.

@Lembik I'll add an explanation later, hopefully. However, I was asking about the minimal number of planes (currently, the program assumes at least two planes.)

Oh right. Two planes is fine as a minimum.

Thank you for the explanation. Would you mind expanding "The program recursively partitions the space by incrementally adding planes and subdividing the currently-explored region, while keeping a track of vectors along the lines of intersection and eventually taking their sum." please.  In particular, do you only keep track of lines of intersection or actually bounded regions as well? If it is just lines of intersection, let us say we add one new plane and work out all the lines of intersection with the current planes. What do you do now exactly?

@Lembik It keeps track of both the bounded region and lines of intersection (LoI). P is where most happen; it takes, in order, the bounding planes, the LoI and the remaining planes. It checks if one of the remaining planes bisects the region by finding its LoI with all the bounding planes and testing if any of them is on the boundary of the region, thus killing two birds with one stone. It then calls itself recursively for each of the new subregions (passing only the LoI of that region,) or for the same region, with the remaining planes. When no planes are left it returns the sum of the LoI.