text:
Russian Roulette
Write a program which plays Russian Roulette!
If the program is started,

there should be a 5 in 6 chance of it ending normally after printing "I survived!"
there should be a 1 in 6 chance of the program crashing. (segmentation fault, etc.)

No input, and no other outputs are allowed.
The randomness must be fair: it must have a uniform probability distribution. This means an uninitialized variable (or a RNG without seed) MOD 6 will not be sufficient.
If the solution works with only one dedicated operating system / platform, you will receive a 6 byte penalty to the score.
Shortest code wins, not sooner than 10 days after first valid answer.

Can we rely on the underlying runtime to be fair, even if not explicitly guaranteed in documentation? E.g. Python's randrange(5) might be implemented as randrange(MAX_INT)%6.

To inspire creativity, you might consider granting a bonus to those solutions which don't rely on division by zero.

Perhaps said bonus should involve dividing the score by 2.

@JoeZeng : that would have been too much. Usually you can make it a different error, like null pointer reference, etc. for the cost of just a few characters.

I see. I'm not too experienced in creating scoring conditions for code golf puzzles, so I'm still learning stuff like that.

By "crash" will division by zero error be sufficient (i.e., not fatal in this case, but program does not continue)

05AB1E, 13 12 bytes
6LΩiFë“IÐ–d!

-1 byte thanks to @Emigna.
05AB1E actually shouldn't be able to error at all, but since the new version of 05AB1E still has some issues compared to the legacy version, I can take that to my advantage to error out for this challenge.
Try it online.
Explanation:
6L          # Create the list [1,2,3,4,5,6]
  Ω         # Get a random choice from this list
   i        # If it is 1:
    F       #  Do a ranged loop, which currently results in a "(RuntimeError) Could not
            #  convert  to integer." error when no argument is given
   ë        # Else:
    “IÐ–d!  #  Push dictionary string "I survived!" (which is output implicitly as result)

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why “IÐ–d! is "I survived!".

Seems like 5ÝΩz“IÐ–d! should work but apparently 1 / 0 = 0.

@MagicOctopusUrn Yeah, 05AB1E almost never errors.. Apart from the pretty old builtin .0 which used to throw a division by 0 error to STDERR in an old version of 05AB1E, I don't even know how to error in the legacy 05AB1E at all.. The new version still has quite a lot of errors however, which I took to my opportunity here. ;)

I miss the old .0, on more than one occasion it made someone go "Wat... Why is that a command?"

PHP 38 bytes
<?~$$s[rand(+$s=sssss,5)]?>I survived!

Placing a + before a non-numeric string will evaluate to 0. Should rand(0,5) return 5, $s[rand(0,5)] will be the empty string (since $s is only five characters long), and subsequently $$s[rand(0,5)] will be an uninitialized variable. Attempting to take the inversion will halt on Unsupported Operand Type. Any other value, 0-4 will return s, and because $s is defined, you will survive.
Note: as of php version 4.2.0, the random number generator is seeded automatically.

Dyalog APL - 25 22 21 20 Charachters
'I Survived!'⊣1÷6⊤?6

Prints DOMAIN ERROR as the error, due to division by zero.
Shortest non-division by zero solution I could come up with is 23 characters.
('I Survived!'1)[~6⍷?6]

It throws an INDEX ERROR
Try it here
APL Font here

I would like to accept it, but it does not seem to work. A few times it prints "I survived", but after printing DOMAIN ERROR once, it keeps printing only that. Even if I reload the site completely, it will never ever survive again.

@vsz How strange... It works in my Dyalog APL WS, and I remember testing it with TryAPL when I was done. It still works on my interpreter, but not on the website.  If this helps: https://dl.dropbox.com/u/9086539/apl.png

I tried it with other interpreters, like http://ngn.github.com/apl/web/index.html but it doesn't work. Please provide a link to an interpreter where it works, possibly with an explanation whether the RNG must be seeded or is seeded automatically. Otherwise I'll have to accept the golfscript solution.

@vsz I have updated my post to reflect that I am using Dyalog APL.  I was under the assumption that tryapl was using Dyalog (and I am confident that it was when I submitted this post).  But now it seems to be missing the ? operator.  Either way, I am no longer confident in the RNG being seeded automatically.

1÷0 is a DOMAIN ERROR in Dyalog but in ngn/apl it's ∞.  The result from ?6 is 1..6 when ⎕IO←1 (default in Dyalog) and 0..5 when ⎕IO←0 (only option in ngn/apl).  In Dyalog, the PRNG can be seeded by setting ⎕RL.  Initially it has some pre-determined default value.  If you set ⎕RL←0, the PRNG is re-seeded fairly unpredictably by the OS.  TryAPL is using Dyalog and does support the ? function.

@ngn it seems to be working again on TryAPL.  It was originally, then it wasn't, now it is again.  I am wondering if they changed something back in January of last year.  Are you affiliated?

It's quite possible that something was changed back then, we are occasionally updating the software behind TryAPL or experimenting with features of the website.  Am I affiliated?  If I tell you, I'll have to kill you... well, with a probability of 1÷6 :)

By the way, here's an 18-character solution: 'I survived!'⊣÷⍟?6

R 30
"I survived!"[6*runif(1)<5||Z]

One time out of six, it will throw an error: Error: object 'Z' not found

Python, 96
from ctypes import*
from random import*
randrange(5)or pointer(c_int())[9**9]
print'I survived!'

If randrange(5) returns 0, then python will crash due to a segmentation fault.

Ruby, 24-28
p rand(6)<5?"I survived!":1/0

Approx each 6 time, there is a ZeroDivisionError
There is even a shorter version with 24 characters (Thanks to ugoren and histocrat):
6/rand(6);p"I survived!"

If you don't accept the " in the output, then I need 3 more characters. The first option (puts) adds a newline, the second ($><<) makes no newline:
6/rand(6);puts"I survived!"
6/rand(6);$><<"I survived!"

There is a question about random number in ruby at SO.
The seed with srand is automatically called with the seed being from the current time if it wasn't already called. (see Julians comment)

Primo had the idea for an extra bonus to those solutions which don't rely on division by zero.
My first solution can be shortened (28 characters) with a undefined local variable or method ``a' for main:Object (NameError)
p rand(6)<5?"I survived!":a

Can be even shorter with 6/rand(6).

Does Ruby seed its RNG automatically?

You can trim another three characters by removing the control flow: 1/rand(6);p "I survived!"

@ugoren / histocrat Thanks for your hints, I adapted my solution.

Another byte for you: no white space is required between p and "I survived!". By my count, that's only 24 bytes.

@primo Thanks - I adapted my solution.

The no-newline version can also be reduced by a byte, replacing print with $><<.

J, 18
'I survived!'[q:?6

Failing with domain error when trying to factorise 0.

Does J seed its RNG automatically?

@vsz Yes, with ?. You can use ?. for fixed seed.

vba, 27
?1/int(6*rnd),"I Survived!"

used in immediate window.
On failure, an error window stating:

appears

Missing the ! in the text.

@steenslag , fixed

@SeanCheshire I've offered an alternative to your answer.

Befunge - 48 chars
 v >91+"!devi"v
/?>?<v"I surv"<
 / / :
   :,_@#

Befunge's only randomness is the ? operator, which sends you heading in one of four posible directions (1/4 chance). By blocking one or two directions, you have 1/3 or 1/2 chance, and by combining these, you get 1/6 chance to get out of the program "alive".
The program crashes by doing a divive-by-zero. I guess it's implementation-specific what will happen (on Wikipedia it says the program should ask for the desired answer), but befungee.py sort of crashes, or exits angrily:
$ for i in {1..6} ; do ./befungee.py roulette.befunge ; done
Error (1,2): integer division or modulo by zero
Error (3,2): integer division or modulo by zero
Error (1,2): integer division or modulo by zero
I survived!
Error (0,1): integer division or modulo by zero
I survived!

C, 67 65 62 chars
rand()%8 doesn't lose fairness. Division crashes for t=0, gives true for 1 and 2 (retry), gives false for 3..7 (survived).
EDIT: The previous version used a temporary variable, which ended up completely unneeded. 2/(rand()%8) implements both needed conditions.
main(){
        for(srand(time(0));2/(rand()%8););
        puts("I survived!");
}

It does. "no other outputs are allowed"

@vsz, somehow missed it. But anyway, with gcc/Linux it doesn't print anything. Also, strictly adhering to the standard, this requirement is impossible, because undefined behavior might print anything.

@vsz, fixed now - no extra output in any case. Also works with optimization, and 2 characters shorter.

T-SQL 56 44 40 + 6

 if 1/cast(ceiling(rand()*6)-1as int)<2print'I Survived!'

Credit Sean Cheshire for calling out cast as unnecessary

 if 1/ceiling(rand()*6-1)<2print'I Survived!'

Credit personal message from Sean Cheshire for suggestion to change ceiling to floor.
 if 1/floor(rand()*6)<1print'I Survived!'

Death Err Msg:
Msg 8134, Level 16, State 1, Line 3
Divide by zero error encountered.

-1 and ceiling are not needed. cast will truncate

I'm testing if ceiling can be removed without violating the requirement for uniform distribution, the docs say that rand() returns float values 0 through 1.

I wanted to know if ceiling could be removed from my first entry. I was unable to determine from T-SQL documentation if the rand() function would ever return a 1 or not. So I ran a loop about 50 million times testing the rand() function, never once did it return a 1. But, removing ceiling from my first entry would still be 47 bytes, so my second entry is still shorter. Keep ceiling and remove cast.

I doubt you have tested this script more than 20 times. This doesn't always return the expected result always. 1 in 6 this will fail and not return an output. This syntax will work: 0/floor(rand()*6)=0

Python, 70 characters
With inspiration from grc's answer.
from random import*
if randrange(5)<1:exec'()'*9**5
print'I survived!'

randrange(5) returns a value between 0 and 5.
If it returns a 0, Python crashes while attempting to exec(ute) a string of code that contains 9^5 sets of parentheses.

Using the usual divide by zero method:
Perl 5.8 Version
1/(int rand 6)&&print "I survived!"

Perl 5.10 Version
1/(int rand 6)&&say "I survived!"

On failure, these will display:
Illegal division by zero at -e line 1.

Using the bless function which is used for creating objects in perl.
Perl 5.8 Version
print (int rand 6?"I survived!":bless me);

Perl 5.10 Version
say (int rand 6?"I survived!":bless me);

On failure, these will display:
Can't bless non-reference value at -e line 1.

a few suggestions: get rid of parentheses, the logical &&, and the extra space. use ~~ instead of int to force integral values. the result is this: 1/~~rand 6;print"I survived!"

GolfScript, 21 chars
,6rand/;'I survived!'

Like most of the answers, this one has a one in six chance of crashing with a ZeroDivisionError.  The shortest solution I could manage without using division by zero is 23 chars:
5,6rand=+;'I survived!'

which has a 1/6 chance of crashing with undefined method `+' for nil:NilClass (NoMethodError).
(Ps. While developing this, I found what might be a bug in the GolfScript interpreter: code like 0,1> appears to leave a nil value on the stack, which will later crash the program if you try to do anything with that value except pop it off and throw it away with ;.  Unfortunately, the fact that I do need to use the value somehow to trigger a crash means that even exploiting this bug didn't help me get below 23 chars.)

That definitely seems like a bug. 5,5> leaves [] on the stack, which is probably what it should do, but 4,5> leaves nil. If you don't remove it, the interpreter will actually crash while trying to output it. An interesting side-effect is that 4,6rand>+;'I survived!' becomes a valid solution. Someone should probably inform Flagitious.

I reported this, and it has been fixed (along with another bug I stumbled across) in the latest version of the GolfScript interpreter.

PHP - 30 bytes
<?rand(0,5)?:~[]?>I survived!

Requires PHP 5.4+ for the short array syntax, invalid operator idea shamelessly stolen from @primo.
As stated, rand() is automatically seeded on first use.

Division by zero does not halt, it only produces a warning, as well as the text 'I survived!'. Also, rand()%6 is not a uniform distribution, as 32768 = 2 (mod 6). However, rand(0,5)||~$a for 30 bytes is, and will additionally work with all PHP versions (the second expression in a ternary is only optional in 5.3.0+).

@primo Guess I was only looking for the stack trace when I was checking the divide by zero one, didn't notice it still printed. I know the ternary shorthand is 5.3+, but I really have no interest in supporting long out of date versions :)

That I agree with. There's no valid argument for continuing to use less than 5.3 at this point. 5.4, I'm still holding out for a double-digit revision number.

I count 29 bytes.

Befunge, 38
v>25*"!devivrus I",,,,,,,,,,,@
?^
v
?^
<1

Pretty straight-forward. Crashing is done by pushing 1s onto the stack until it overflows. I made a few attempts at cutting out those 11 commas and replacing them with some more efficient loop to print everything, but couldn't get it under 11 characters.
Note that counting characters in Befunge is a little tricky... For instance there's only one character on the third line, but I'm counting an extra one there since execution could travel through that location.

I believe that's the record for the most consecutive commas I've ever seen in a program.

And then I look up how Befunge actually works and palm my face.

Python3.8.10 : 45
int(set('12345 ').pop());print('I survived!')

I hope it follows the challenge specification.
I did some statistics with this method and it seems to have a uniform probability distribution
(the program crashes 10416 times over 60000 calls from the console)

Javascript, 42

(Math.random()*6|0)?alert('i survived!'):b

The bitwise or floors the result of the multiplication thus a value between 0 and 5 results. 0 gets implictly casted to false, so in 5 of 6 cases the alert appears in the 6th case a certain b is referenced, crashing the process.

CMD Shell (Win XP or later), 40 +6
I'm only doing this one because DOS is not something that should even be thought of for code golf, and the whitespace is important
set/a1/(%RANDOM% %% 6)&&echo I Survived!

On failure, it will print

Divide by zero error.

R, 50 44 42 36

ifelse(!is.na(sample(c(NA,1:5),1)),'I Survived!',)

ifelse(floor(runif(1,0,5))>0,'I Survived!',)

ifelse(floor(runif(1,0,5)),'I Survived!',)

ifelse(sample(0:5,1),'I Survived!',)

Death Err Message:

Error in ifelse(!is.na(1/sample(c(NA, 1:5), 1)), "I Survived!", ) :
    argument "no" is missing, with no default

I tried R, and couldn't get it to fail - if(1/0)"I Survived!" still printed I Survived

Unlike other languages, R doesn't consider 1/0 to be a math error and doesn't stop execution, it just returns inf for 1/0. I think @vsz wants a breaking error for this round. But supposing vsz counted NA as the death error, I could get my program down to 41 characters: ifelse(sample(c(NA,1:5),1),'I Survived',)

Emacs-Lisp, 42 characters
(if (= (random 6) 5)
    z (message "I survived!")
    )

Javascript, 40 chars
In Javascript the divide-by-zero trick doesn't even work: it just returns Infinity. Therefore, referencing a non-existing variable:
alert(6*Math.random()|0?"I survived!":f)

Not so short, though fun :)

PowerShell, 40 Chars
IF(6/(Get-Random -Max 6)){'I Survived!'}

On Failure: "Attempted to divide by zero."

Welcome to PPCG!

32 bytes

31 bytes

Python, 53 bytes
Here's a short 53 byte python index out of range program:
import time
[0][time.time()%6<1]
print("I survived!")

Hi and welcome. Please note that in the rules for this challenge, it states "MOD 6 will not be sufficient." Although I'm not familiar with Python, it looks to me like you are using Modulo here.

@ShaunBebbers The quote is "This means an uninitialized variable (or a RNG without seed) MOD 6 will not be sufficient," but this meta post says that current time modulo is enough for a PRNG for code-golf

My misunderstanding then.

Befunge-98 (FBBI), 28 bytes
r?<?
"< <@,ka"I survived!
 =

Try it online!
Errors with a segmentation fault.
Explanation
Befunge-98 adds some extra features (r, k, and =) that can be used to further golf Joe K's Befunge-93 answer.
The first line (r?<?) calculates the 1/6 chance. The r initially reflects the IP to the left, where it reaches the second ? and goes in a random direction. If it goes right, the r reflects it and it tries again. If it goes up or down, it moves onto the second line, and if it goes left, it moves onto the first ?. There are three ways the IP can leave, so there is a 1/3 chance it moves onto the first ?.
If it gets there, it again goes in a random direction. If it goes horizontally, it gets reflected (with either r or <) and tries again. This means that there are only two ways that the IP can leave, and they are equally likely. Either it goes down onto the second line, or it goes up and hits the = on the third line.
There is a 1/6 chance that = is executed (1/3 from the second ? times 1/2 from the first). If it is, it does a system-execute call on the stack (which is empty and interpreted as an empty string). FBBI's implementation of this runs a C system() call on the empty string, which segfaults.
This leaves a 5/6 chance that the IP reaches the second line. If it does, it gets sent left with <, and pushes the string "!devivrus I" onto the stack. ak, prints the top 11 characters of the stack, outputting I survived! Finally, @ ends the program.

Jelly, 12 bytes
6X’’Xṛ“`:ƭ÷»

Try it online!
Explanation
6X            Generate a random number between 1 and 6 inclusive (using python randrange)
  ’’          Decrement it twice
    X         Generate a random number from 1 to the above value. 0 if the value is 0. Error if the value is negative (1/6 chance)
     ṛ        Right Argument; ignore the above value and instead return
      “`:ƭ÷»  "I survived!"

Unfortunately, taking the reciprocal of 0, dividing or integer-dividing by 0, and modulo by 0 all give either inf or nan, and don't actually error.

It's nice to have exactly one documented error in the docs for challenges like these.

@Razetime yep :D it's the only result when ctrl-f'ing "error" in jelly docs. of course there are a bunch of other ways but most of those errors come from writing the code wrong, not the actual runtime. i suppose i could get a line of STDIN which would EOF but IDK if that's allowed and this is easier anyway

Groovy, 39
1/new Random().next(6);print"I survived!"

Picks a random number between 0 and 5 inclusive. If 0, throws a divide by zero exception.

Java, 149
public class R{public static void main(String[]s){int[]a={1,1,1,1,1};System.out.println(a[new java.util.Random().nextInt(7)]>0?"I survived!":"");}}

Fails with an "Array out of bounds" error. Managed to shave a few characters by using anonymous Random object (no imports).

138 bytes https://tio.run/##FYyxDoIwFEV/pTq1g00cjIlonFlhJB0etDEPy4PQ16ohfHuF6Z7knNweEpx6@8658xCCqJYpth47ERh4mzSiFQMgyZpnpFdjQC1I3Jj2Qe4jdryYov4FdoMeI@tpy9iTbJvd99u/joxeV0B2HKTS5L5cEsurMvfz81iKEOeEydnD8QaqWNec/w

Python, 59 55 53, 65 59 56
import os
1/(ord(os.urandom(1))%6)
print"I survived!"

ZeroDivisionError when ord(os.urandom(1))%6 evaluates to 0
import os
print(["I survived!"]*5)[ord(os.urandom(1))%6]

IndexError when ord(os.urandom(1))%6 evaluates to 5

Save 5 characters by changing the import: import random as r then use r.randint

Or save 8 characters by changing import to import os, then use ord(os.urandom(1))%6 as your random int.

Save 1 character by removing the space after print.

VBA - 39/46
I don't love Sean Cheshire's numeric output (though still a good answer, it technically fails the No input, and no other outputs are allowed. from the spec...), plus he uses /0, so here are my alternatives:
?Mid("I Survived!",IIf(Int(6*Rnd),1,0))

This resolves to a Run-time error '5': Invalid procedure when trying to reach character 0 (VBA is 1-based indexing).
n="I Survived!":If Int(6*Rnd) Then ?n Else ?-n

This resolves to a Run-time error '13': Type mismatch when applying a negative switch to a string.

Python (56), Haskell (77)
This crashes with an IndexError when the generated number is 1:

from random import*
print['I survived!'][1/randint(1,7)]

The Haskell solution has the same idea:

import System.Random
main=putStrLn.(["I survived!"]!!).div 1=<<randomRIO(1,6)

TI-BASIC (TI-84+/SE), 36 bytes
startTmr→rand:1/(1<randInt(1,6:"I survived!

There is no input, as the challenge specifies.
Output is I survived! if successful, a DIVIDE BY 0 error otherwise.
The DIVIDE BY 0 error screen looks like the following:
ERR:DIVIDE BY 0
1:Quit
2:Goto

Selecting either option (and returning to home screen if 2 is selected) shows Error after the program call.
Examples:
prgmCDGFE
           Error
prgmCDGFE
I survived!
prgmCDGFE
I survived!
prgmCDGFE
           Error

Explanation:
startTmr→rand:1/(1<randInt(1,6:"I survived!   ;full program

startTmr→rand                                 ;store the current time into "rand"
                                              ; this is necessary because "rand" is 0 after
                                              ; factory reset, the default state for TI-BASIC
                                              ; submissions
                   randInt(1,6                ;get a random integer in [1,6]
                 1<                           ;is greater than 1?  1 if true, 0 if false
              1/(                             ;divide 1 by the result
                                              ; throws "DIVIDE BY 0" error if result was
                                              ; false
                               "I survived!   ;leave this string in "Ans"
                                              ;implicitly print "Ans"

Notes:

TI-BASIC is a tokenized language.  Byte count does not equal character count.
Lowercase letters are two bytes each.

Lowercase letters can be enabled using this assembly program.

startTmr is a command only on the TI-84+ and TI-84+ SE calculators.  Said calculators have different operating systems.

-4 bytes: to produce the error: identity(randInt(0,5 (a zero-size identity matrix will error)

GNU Bash -- 37 bytes
! followed by nothing doesn't trigger history substitution. $[...] is alternative syntax for arithmetic. (...) is a subshell.
This solution is portable. bash itself does fork but doesn't exec any other programs.
(exit $[$RANDOM%6])&&echo I survived!

Japt v1.4.5, 16 bytes
6ö
ªí
`I s¨viv!

Try it
-1 byte thanks to @Shaggy!
Throws TypeError: U.í is not a function when a random number in the range [0,6) is 0.

17 bytes

Actually, it might be an idea to use v1.4.5 for this, just in case ETH adds an N.í() method to v1.4.6.

Updated - Japt tries hard not to crash on weird programs. I was trying to figure out how to reference a variable that didn't exist (A-Z is defined), but didn't consider calling a method that didn't exist.

Yeah, N.í() is my "go to" for throwing an error (it used to be N.y()). There are a few other ways of getting an error but they're rarely useful.

Now, why didn't I think of using a 3rd line?! :\

C# (Visual C# Interactive Compiler), 48 bytes
Write(1/new Random().Next(6)<9?"I survived!":"")

Try it online!
Throws Attempted to divide by zero. if a random number in the range [0,6) is 0.

VB.Net, 38 bytes
If(CInt(Rnd() * 6), "I survived!", Dir())

Throws : System.ArgumentException 'Dir' function must first be called with a 'PathName' argument.
Spaces removed :
If(CInt(Rnd()*6),"I survived!",Dir())

Welcome to PPCG :) Couple of things: you should include your solution's byte count in the header, I'm pretty sure you can remove all the spaces, and, could you use a single character, undefined function name instead of Dir? Also, does VB.Net have bitwise operators?

Thanks for the welcome and tips - first attempt at code golf!  VB.Net will not compile an undefined function name, so I picked an inbuilt with the smallest number of chars.

Commodore C64/128, C64Mini and compatibles, 101 95 92 tokenised BASIC bytes + 6 penalty bytes for only working in Commodore BASIC
As Commodore keyword abbreviations, you may enter it as follows:
 0a$="i survived":fOi=0to5:a$(i)=a$:nE:a$(rN(.)*6)="":x=6*rN(.)
 1?len(a$(x))/len(a$(x))"{left}{left}"a$

I found a six-tokenised byte saving by not using the INT keyword when assigning a value with RND and CBM BASIC will automatically convert the key value to it's integer by ignoring the decimal places.
Non-obfuscated for explanatory purposes:
 0 let a$="i survived"
 1 for i=0 to 5
 2 let a$(i)=a$
 3 next i
 4 let a$(int(rnd(0)*6)=""
 5 let x=int(rnd(0)*6)
 6 print len(a$(x))/len(a$(x));"{left}{left}";a$(x)

Firstly, we set up a$ as a string and we later use it as an array; in Microsoft [Commodore] BASIC that appeared on the PET, VIC-20, C64 etc... you can set up the first 11 elements of a zero-indexed array without expressly declaring it first, though it saves space on the variable stack if you do and you have fewer than 11 elements.
So our string array of six elements are set to the string literal of i survived. One of those elements is randomly reset to an empty string.
The x variable is then used to select which of the six will be displayed (one of which is empty). Finally, we try to divide the length of that element with itself; usually this would produce an output of 1 except where the string length of the element is 0, so 0/0 will produce an error (one in six chance) and halt the execution of the symbolic listing; otherwise, the print command moves the cursor position back two spaces to overwrite the output with the string literal of the array element x, or i survived.
This answer assumes that the division by zero error reported by BASIC (which halts the programs execution by the interpreter) is acceptable as the program crashing as cited above.

Python 2, 49 bytes
import os
print["I survived!"][os.urandom(1)<'+']

Try it online!
Utilises the idea from this answer of using os.urandom, but we save some bytes by avoiding the ord call.
os.urandom(n) generates n random bytes. By checking if they are smaller than chr(math.ceil(256.0/6)) (== '+'), we get an approximately 1/6 chance of True (== 1).

Is the chance one in six though? It's not clear so maybe an explanation will help.

@ShaunBebbers explanation added. Since 256%6 != 0 the chance is not exactly one in six, but many answers here approximate those odds slightly.

Vyxal O, 13 bytes
6ʁ℅ḭ`I ¦⟇d!`,

Try it Online!
Fixed thanks to Razetime!
When run offline, 11 bytes (thanks to Aaron Miller)
6ʁ℅ḭ`I ¦⟇d!

Try it Online!

The challenge states "no other outputs allowed"; when it errors, it prints 0 to STDOUT

You can disable implicit output with the O flag, also I got it to error: Try it Online!

@Makonede Fixed.

This is a valid 11 byte solution, because when run offline, it errors 1/6 of the time without printing anything.

Tcl, 64 bytes
puts [expr srand([clock se])*0+int(rand()*6)%6?"I survived":1/0]

Try it online!

C++, 105 bytes
#include<iostream>
#include<ctime>
int f(){srand(time(0));delete(int*)!(rand()%6);printf("I survived!");}

In C++, delete behavior is that on 0 ( or nullptr ), nothing occurs
Not as cool ( nor dangerous ) as CommitStrip's russian roulette

Microscript II, 20 bytes
6R("I survived!"ph)f

Generates a random integer on [0,5], printing the message and halting if the generated integer is nonzero. If the generated integer is 0, it instead crashes with an IllegalArgumentException because the f instruction is invoked on a nonstring value

Can you add an explanation for those not familiar with Microscript?

@streetster done

Forth (gforth), 51 bytes
include random.fs
: f 1 6 random / ." I Survived!";

Try it online!
Explanation
Randomly gets a number between 0 and 5 (inclusive)
Divides 1 by the result
Crashes with divide by zero error if random number is 0
Code Explanation
include random.fs       \ include the library file necessary for random to work
: f                     \ start a new word definition
  1                     \ place 1 on the stack
  6 random              \ get a random number between 0 and 5 (inclusive)
  /                     \ divide 1 by the result of the random call
  ." I Survived!"       \ print "I Survived!"
;                       \ end word definition

JVM Bytecode -noverify, 372 bytes
Works by passing a wrong type to the print function if Random.nextInt(6) is 0.
Hexdump of the class:
$ xxd.exe Code.class
00000000: cafe babe 0003 002d 0020 0c00 1900 1f01  .......-. ......
00000010: 0016 285b 4c6a 6176 612f 6c61 6e67 2f53  ..([Ljava/lang/S
00000020: 7472 696e 673b 2956 0100 106a 6176 612f  tring;)V...java/
00000030: 7574 696c 2f52 616e 646f 6d01 0006 3c69  util/Random...<i
00000040: 6e69 743e 0c00 0400 0803 0000 0006 0700  nit>............
00000050: 1001 0003 2829 5607 0014 0100 0443 6f64  ....()V......Cod
00000060: 6501 0004 6d61 696e 0900 0900 0101 000a  e...main........
00000070: 536f 7572 6365 4669 6c65 0100 076e 6578  SourceFile...nex
00000080: 7449 6e74 0c00 1100 1a01 0013 6a61 7661  tInt........java
00000090: 2f69 6f2f 5072 696e 7453 7472 6561 6d01  /io/PrintStream.
000000a0: 0007 7072 696e 746c 6e0a 0013 001d 0700  ..println.......
000000b0: 0301 0010 6a61 7661 2f6c 616e 672f 5379  ....java/lang/Sy
000000c0: 7374 656d 0a00 1300 050a 0007 000f 0100  stem............
000000d0: 0428 4929 4907 000a 0100 036f 7574 0100  .(I)I......out..
000000e0: 1528 4c6a 6176 612f 6c61 6e67 2f53 7472  .(Ljava/lang/Str
000000f0: 696e 673b 2956 0100 0b49 2073 7572 7669  ing;)V...I survi
00000100: 7665 6421 0800 1b0c 000e 0017 0100 0001  ved!............
00000110: 0015 4c6a 6176 612f 696f 2f50 7269 6e74  ..Ljava/io/Print
00000120: 5374 7265 616d 3b00 2000 1800 1300 0000  Stream;. .......
00000130: 0000 0100 0900 0b00 0200 0100 0a00 0000  ................
00000140: 2900 0500 0100 0000 1db2 000c bb00 1359  )..............Y
00000150: b700 1512 06b6 0012 9a00 0812 06a7 0005  ................
00000160: 121c b600 16b1 0000 0000 0001 000d 0000  ................
00000170: 0002 001e                                ....

Jasmin code to generate:
.source ""
.class Code
.super java/util/Random
.method public static main([Ljava/lang/String;)V
    .limit stack 3
    getstatic java/lang/System/out Ljava/io/PrintStream;
    new java/util/Random
    dup
    invokenonvirtual java/util/Random/<init>()V
    ldc 6
    invokevirtual java/util/Random/nextInt(I)I
    ifne Survive
    ldc 6
    goto Print
    Survive:
    ldc "I survived!"
    Print:
    invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
    return
.end method

Must to be run with java -noverify to prevent Java from realizing that the class is messed up.
Also it's very wrong this time but CFR output for fun:
/*
 * Decompiled with CFR 0.142.
 */
import java.io.PrintStream;
import java.util.Random;

class Code
extends Random {
    public static void main(String[] arrstring) {
        if (new Random().nextInt(6) != 0) {
            String string = "I survived!";
        }
        System.out.println((String)6);
    }
}
```

Lol, submit the class file as a cfr 'bug', then I can fix it.

@lab27 Not exactly something one could fix, it uses a cast that isn't actually valid and some other silliness

C (gcc), 58 53 bytes
-5 bytes by using &i in place of time(0) - thanks ceilingcat
Floating point exception when rand() is divisible by 6
main(i){i/=(srand(&i)+rand()%6);puts("I survived!");}

Try it online!

ceilingcat that was in my original code but I wasn't sure if the pointer value changed across runs (I'm not that good at C)

44 bytes

Perl 6, 34 bytes
(^6 .roll&&say "I survived!")||die

Throws an exception to crash.
Try it online!

MathGolf, 15 bytes
6rw/;'I ûÄ%$╦'!

Try it online!
Explanation
6r                push [0, 1, 2, 3, 4, 5]
  w               random item from list
   /              divide implicit zero by the random element
    ;             discard TOS (needed for non-crashes)
     'I           push single character "I"
                  space character
        ûÄ%       push "Ä%"
           $      convert to ordinal (from base 256 to base 10)
            ╦     fetch single dictionary word "survived"
             '!   push single character "!"

With some better handling of dictionary fetches, this could probably be 2-3 bytes shorter, but that's not getting implemented within the immediate future.

Octave 33 bytes
{"I_Survived!"}(1/(rand(1)>0.16))

Approx each 6 time, there is a
warning: division by zero
error: index (inf): subscripts must be either integers 1 to (2^31)-1 or logicals

It prints way more than "I survived" and the rules say no other input than that is allowed.

Java, 98 bytes
interface m{static void main(String[]a){System.out.print(Math.random()<.16?1/0:"I survived!");}}

Try it online
Bonus answer that allocates 2^60 bytes of memory instead of dividing by 0:
import sun.misc.Unsafe;import java.lang.reflect.*;interface M{static void main(String[]a)throws Exception{Field f=Unsafe.class.getDeclaredField("theUnsafe");f.setAccessible(1>0);((Unsafe)f.get(null)).allocateMemory(Math.random()<.16?1L<<60:0);System.out.print("I survived!");}}

TIO

Runic Enchantments, 23 bytes
>6'RA0)?;"I survived!"@

Try it online!
Nothing too special here. Just an IP that picks a random number [0-6) and prints the required string if the random value isn't 0.
Required string contains two vs which also creates an IP each that get terminated after 100k execution steps (otherwise TIO would produce instant results and the > wouldn't be needed).

MATLAB/Octave, 37 bytes
a=1:5;a(randi(6));disp("I survived!")

Try it online!
It has 1 in 6 chances to crash with indexing error, when randi returns 6.

PPL, 96 bytes
importRandom
declarex=Random.random()*6
ifx>1{
printLine("I survived!")
}
ifx<=1{
printLine(f)
}

Very similar code to the Minceraft problem. Runs on PPL v1.0.10.
Soon, I will publish an official PPL website where you can create and run PPL code. I am still working on it.
Explanation
The first line imports Random.
Then, we set x to Random.random() (random float between 0 and 1) multiplied by 6.
Since neither else nor ternary exists in PPL, we must use two diverging if-statements. One prints the string I survived! to STDOUT (if x is greater than 1) while the other errors because f is undefined.

05AB1E, 12 bytes
Ties hyper-neutrino's Jelly answer for #1.
“IÐ–d!“6LΩiF

Try it online!
“...“6LΩiF  # trimmed program
“...“       # push "I survived!"
        i   # if...
       Ω    # random element in...
      L     # [1, 2, 3, ...,
     6      # ..., literal...
      L     # ]...
        i   # is 1...
         F  # then do nothing...
“...“       # "I survived!"...
         F  # times
            # implicit output

Rattle, 21 19 bytes
=?6/`p"I survived!"

Try it Online!
There's a 5/6 chance that this just prints I survived, and a 1/6 chance that this exits with an error:
Error: float division by zero at command index 1 [/`]

Explanation
=?6           sets the top of the stack to a random value from 0-5 inclusive
   /`         divides the top of the stack by the top of the stack.
                  This works fine except for when the top of the stack is 0
     b"..."   adds "I survived!" to the output buffer, implicit output (p" " would work here too)

Ly, 19 bytes
6?/<"I survived!"&o

Try it online!
This is similar to some of the other entries.  It generates a random number between 0 and 5, then crashes with a division by zero error if 0 was the result.
6?                   - generate a random number in 0-5
  /                  - divide, fails with division by zero 1/6 of the time
   <                 - switch to a clean stack
    "I survived!"    - push the output string (codepoints)
                 &o  - print the stack a characters

Julia 1.0, 32 bytes
0%rand(0:5);print("I survived!")

Try it online!

APOL, 28 bytes
Dead simple, just uses the "divide by 0" method.
/(1 ∿(0 5));p("I survived!")

<>^v, 18 bytes
5#=V"I survived!";

run online
Explanation
5#=V"I survived!";
5                  Push 5 to stack
 #                 Push random number in range [0, <top of stack>]
  =                Skip next instruction if the top two elements (5 and the random number)
                   of the stack are equal
   V               Try reading the value of register 'v'. This should crash because it was
                   never assigned a value, its setter 'v' being a keyword
    "              String start
     I survived!   Contents of the string
                "  String end
                 ; Print with newline

Python 3, 54 bytes
import random;1/random.randrange(5);print'I survived!'

On 1/0 it will crash:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero


text:
Normal distribution values
Write the shortest program possible which outputs a table of Normal distribution values
phi(z) = Integral[t from -infty to z of e^(-t^2/2) /sqrt(2 pi) dt]

for z from 0.00 to 3.99, giving values accurate to 4 decimal places.
The canonical format for such a table appears to be:
    0.00    0.01    0.02    0.03    0.04    0.05    0.06    0.07    0.08    0.09
0.0 0.5000  0.5040  0.5080  0.5120  0.5160  0.5199  0.5239  0.5279  0.5319  0.5359
0.1 0.5398  0.5438  0.5478  0.5517  0.5557  0.5596  0.5636  0.5675  0.5714  0.5753
0.2 0.5793  0.5832  0.5871  0.5910  0.5948  0.5987  0.6026  0.6064  0.6103  0.6141
0.3 0.6179  0.6217  0.6255  0.6293  0.6331  0.6368  0.6406  0.6443  0.6480  0.6517
0.4 0.6554  0.6591  0.6628  0.6664  0.6700  0.6736  0.6772  0.6808  0.6844  0.6879
0.5 0.6915  0.6950  0.6985  0.7019  0.7054  0.7088  0.7123  0.7157  0.7190  0.7224
0.6 0.7257  0.7291  0.7324  0.7357  0.7389  0.7422  0.7454  0.7486  0.7517  0.7549
0.7 0.7580  0.7611  0.7642  0.7673  0.7704  0.7734  0.7764  0.7794  0.7823  0.7852
0.8 0.7881  0.7910  0.7939  0.7967  0.7995  0.8023  0.8051  0.8078  0.8106  0.8133
0.9 0.8159  0.8186  0.8212  0.8238  0.8264  0.8289  0.8315  0.8340  0.8365  0.8389
1.0 0.8413  0.8438  0.8461  0.8485  0.8508  0.8531  0.8554  0.8577  0.8599  0.8621
1.1 0.8643  0.8665  0.8686  0.8708  0.8729  0.8749  0.8770  0.8790  0.8810  0.8830
1.2 0.8849  0.8869  0.8888  0.8907  0.8925  0.8944  0.8962  0.8980  0.8997  0.9015
1.3 0.9032  0.9049  0.9066  0.9082  0.9099  0.9115  0.9131  0.9147  0.9162  0.9177
1.4 0.9192  0.9207  0.9222  0.9236  0.9251  0.9265  0.9279  0.9292  0.9306  0.9319
1.5 0.9332  0.9345  0.9357  0.9370  0.9382  0.9394  0.9406  0.9418  0.9429  0.9441
1.6 0.9452  0.9463  0.9474  0.9484  0.9495  0.9505  0.9515  0.9525  0.9535  0.9545
1.7 0.9554  0.9564  0.9573  0.9582  0.9591  0.9599  0.9608  0.9616  0.9625  0.9633
1.8 0.9641  0.9649  0.9656  0.9664  0.9671  0.9678  0.9686  0.9693  0.9699  0.9706
1.9 0.9713  0.9719  0.9726  0.9732  0.9738  0.9744  0.9750  0.9756  0.9761  0.9767
2.0 0.9772  0.9778  0.9783  0.9788  0.9793  0.9798  0.9803  0.9808  0.9812  0.9817
2.1 0.9821  0.9826  0.9830  0.9834  0.9838  0.9842  0.9846  0.9850  0.9854  0.9857
2.2 0.9861  0.9864  0.9868  0.9871  0.9875  0.9878  0.9881  0.9884  0.9887  0.9890
2.3 0.9893  0.9896  0.9898  0.9901  0.9904  0.9906  0.9909  0.9911  0.9913  0.9916
2.4 0.9918  0.9920  0.9922  0.9925  0.9927  0.9929  0.9931  0.9932  0.9934  0.9936
2.5 0.9938  0.9940  0.9941  0.9943  0.9945  0.9946  0.9948  0.9949  0.9951  0.9952
2.6 0.9953  0.9955  0.9956  0.9957  0.9959  0.9960  0.9961  0.9962  0.9963  0.9964
2.7 0.9965  0.9966  0.9967  0.9968  0.9969  0.9970  0.9971  0.9972  0.9973  0.9974
2.8 0.9974  0.9975  0.9976  0.9977  0.9977  0.9978  0.9979  0.9979  0.9980  0.9981
2.9 0.9981  0.9982  0.9982  0.9983  0.9984  0.9984  0.9985  0.9985  0.9986  0.9986
3.0 0.9987  0.9987  0.9987  0.9988  0.9988  0.9989  0.9989  0.9989  0.9990  0.9990
3.1 0.9990  0.9991  0.9991  0.9991  0.9992  0.9992  0.9992  0.9992  0.9993  0.9993
3.2 0.9993  0.9993  0.9994  0.9994  0.9994  0.9994  0.9994  0.9995  0.9995  0.9995
3.3 0.9995  0.9995  0.9995  0.9996  0.9996  0.9996  0.9996  0.9996  0.9996  0.9997
3.4 0.9997  0.9997  0.9997  0.9997  0.9997  0.9997  0.9997  0.9997  0.9997  0.9998
3.5 0.9998  0.9998  0.9998  0.9998  0.9998  0.9998  0.9998  0.9998  0.9998  0.9998
3.6 0.9998  0.9998  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999
3.7 0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999
3.8 0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999  0.9999
3.9 1.0000  1.0000  1.0000  1.0000  1.0000  1.0000  1.0000  1.0000  1.0000  1.0000

do you want to exclude the inevitable boring answers in languages which have a built-in function to do this?

Yes. No build-in functions.

Also, do you want to place a limit on running time or are you willing to accept Monte-Carlo approaches (probably based on Box-Müller)?

I haven't thought that but it would be nice that the program will halt in reasonable time. But it is hard to say what would be reasonable.

@PeterTaylor Nice idea. As far as run time, MC solutions would only need to run on order of 10^9 total throws to achieve the expected precision. Maybe 10^11 to be confident. On a multi-GHz, superscaler machine that halts in a few minutes. Maybe better if you are able to take advantage of of the SIMD unit (thought is is not clear that you can).

Is the cannonical format requried, or anything that contains the correct values?

@dmckee, you're not likely to take advantage of the SIMD unit in golf anyway. And on reflection, Monte-Carlo is probably going to require more code than basic direct quadrature.

Mathematica 132 136 127
If Erfc is acceptable, here's my attempt, accurate to 6 places:
t=Table;TableForm[Partition[t[0.5 Erfc[-x/Sqrt[2]],{x,0,3.99,.01}],10],
TableHeadings->{t[k,{k,0,3.9,.1}],t[k,{k,0,.09,.01}]}]

Someone needs to tell Wolfram what a significant figure is. 0.5 isn't the same as 0.500000.

Interesting point. If one uses ScientificForm[number,4], the output will display, at most, four digits (times a power of 10), but it still truncates zeros to the right. So ScientificForm[0.5 ,3] returns 5. * 10^(-1). EngineeringForm[.5,3] shows similar inconsistencies.

(I know this answer is old but) If you want to be explicit about the precision, use 0.5`1 or 0.5`6. 0.5 and 0.500000 both have machine precision.

GolfScript (124 chars)
10:&,~]'    0.0'*40,{n\:I&/'.'I&%&,{'   '\I&*+&8?:^*100/:x^54,-2%{:i*x.{*^/}:$~$i).)*/^\-}/$3989423$15000500+`5<(49-'.'@}%}/

Note: the only whitespace in there are two tab characters. MarkDown is turning them into triple-spaces.
The interesting part (i.e. the calculation) is done in x.8 fixpoint using identity 26.2.10 of Abramowitz and Stegun (1972). The program runs in under 2 seconds on my machine.

Perl - 137 133 bytes
print"\t0.0$_"for 0..9;for($f=2.506628;$i++<80;$f*=-++$i){printf'
%.1f',$x,s;;+\$x**$i/$i/$f;;printf"\t%.4f",eval,$x+=.01for(.5.$_)x10}

(both \t should be replaced with a literal tab character.)
Uses a Taylor Series expansion[1], adding one term per row, which seems to be good enough. The script produces the output exactly as expected, although each row does have a trailing whitespace. Runs in about 60ms on my lappy.
Edit as per comment by Peter Taylor.
[1] http://mathworld.wolfram.com/NormalDistributionFunction.html (formula 10)

Hmm - MarkDown probably clobbered the tabs that were in the table when I pasted it. If you replace the spaces in the first format string by a single tab character and change the last format string into <TAB>%.4f then you get the correct output and save 4 chars.

c -- 372
Just for interest this is an implementation of Peter's Monte Carlo suggestion from the comments
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#define P printf
#define F(c,n) for(c=0;c<n;++c)
long c=9e9,i,j,k;double a[400],b=.01,t;
double B(){return sqrt(-2*log(drand48()))*cos(2*M_PI*drand48());}main()
{srand48(time(0));F(i,c){t=B();F(k,400)a[k] += t<b*k;}P("%4c",' ');F(j,10)
P("%4.2f    ",b*j);F(i,40){P("\n%3.1f ",10*i*b);F(j,10)
P("%6.4f  ",a[10*i+j]/c);}}

Lots of repetitive code. A very straight forward implementation, ungolfed it looks like
#include "stdio.h"
#include "stdlib.h"
#include "math.h"

long c=9e9, i, j, k;  /* demands longs longer than 32 bits */

double a[400], bw=.01, t;

double B/*oxMuller*/(){
 /* normal distribution, centered on 0, std dev 1 */
  return sqrt(-2*log(drand48())) * cos(2*M_PI*drand48());
}

main(){
  srand48(time(0));
  for(i=0; i<c; ++i) { /* compute the probabilities by MC integration */
    t=B/*oxMuller*/();
    for(k=0; k<400; ++k) a[k] += t<bw*k;
  }
  /* Print the table */
  printf("%4c",' ');
  for(j=0; j<10; ++j) printf("%4.2f    ",bw*j);
  for(i=0; i<40; ++i) {
    printf("\n%3.1f ",10*i*bw);
    for(j=0; j<10; ++j) printf("%6.4f  ",a[10*i+j]/c);
  }
  printf("\n"); /* make the end pretty */
}

It is slow, about 60 seconds to do 100,000,000 throws with absolutely all the optimization bells and whistles turned on (-m64 -Ofast) on my 2.2 GHz Core 2 Duo laptop. Worse, it needs circa 50 times that many to provide real confidence that you have the right value in each and every bin. As written I'm asking for even more.
That seems too long to me, but I suspect that I underestimate how much work drand48 is doing (and I have sacrificed about a factor of 2 in the random number generation at the alter of small code).
It also demands that long is a bit bigger than 32 bits (thus the -m64 above).

drand48() is not the problem; you're being hit by branch misprediction. I got a >3X performance improvement when I replaced for(k=0; k<400; ++k) a[k] += t<bw*k; with for( k=t<0?0:ceil(t/bw); k<400; ++k) a[k]+=1;

k
This is based on the Zelen and Severo algorithm here. 162 characters. Can improve the character count significantly by reducing precision.
+`q`p!(q;{abs(x>0)-(exp[-.5*x*x]%sqrt 2*acos -1)*t*.31938153+t*-.356563782+t*1.781477937+t*-1.821255978+1.330274429*t:1%1+.2316419*abs x}(q:0.1*!391)+\:0.01*!100)

Runs in about 15ms on a Pentium E2160.

source: Stack Exchange

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

sort: votes


text:
Calculate e^x and ln(x)
Given a floating point x (x<100), return e^x and ln(x). The first 6 decimal places of the number have to be right, but any others after do not have to be correct.
You cannot have any "magic" constants explicitly stated (e.x. a=1.35914 since 1.35914*2 ~= e), but you can calculate them. Only use +, -, *, and / for arithmetic operators.
If x is less than or equal to 0, output ERROR instead of the intended value of ln(x).
Test Cases:
input: 2
output: 7.389056 0.693147
input: 0.25
output: 1.284025 -1.386294
input: 2.718281828
output: 15.154262 0.999999  (for this to output correctly, don't round to 6 places)
input: -0.1
output: 0.904837 ERROR

Shortest code wins.

I assume you mean to exclude exponentiation of entirely (not just for the the calculation of e itself)? 2**(x*1.442695) for example seems a bit too easy.

@primo: yes, there is no exponentiation whatsoever, but things like product([2]*3) is ok. I guess I should rule out "magic constants" in the case of 1.442695.

You might want to also specify a valid range for the input - any approximation can lose accuracy if x becomes too large or too small.

@A.R.S.: added a boundary. Thanks.

maybe a lower bound too? something like 1e-2 < abs(x) < 1e2 since most evaluations seem to be losing accuracy for abs(x) < 1e-2 (unless you want that to be part of the challenge?)

@milest: That will be part of the challenge. It should not be very hard to implement, since most answers are approximations.

No one uses APL!? Seriously?

I'm not sure why the accepted answer was changed. Perl 89 is shorter than Javascript 90, no?

JavaScript, 103 101 99 97 93 90
This implementation is based on primo's comprehensive description of the algorithm he used.
for(e=l=x=prompt(g=1e5);--g;y=x-1,l=(x>1?y/=x:-y)*l+y/g)
    e=1+e/g*x;
alert([e,x>0?l:"ERROR"])

Edit:
- Trying to catch Perl. Stole a byte back from primo by copying his branch. :)
- 2 more bytes courtesy of primo.
- Finally, caught primo's version! With primo's help, of course... :)
- Simplified the assignment to L. Shaved 3 more bytes.

It's somewhat humorous that defining Math.abs inline is actually shorter than using the built-in.

As far as catching perl goes, would it help if I pointed out that the initial values of e and l don't really matter?

@primo Nice catch!

I've got 93, by combining the y and l definitions: l=(x>1?y=1-1/x:-(y=x-1))*l+y/g

Very elegant. I probably spent over an hour trying to figure out a way to exploit the relationship between x<1 and y<0. You sir, are a genius! :)

Nice! I'd +1 again if I could!

PHP 109 107 bytes
<?for($g=1e4;--$g;$l=$y/$g+abs($y=$x>1?1-1/$x:$x-1)*$l)$e=1+$e/$g*$x.=fgets(STDIN);echo"$e ",$x>0?$l:ERROR;

\$e^x\$ is a fairly straight-forward calculation. I use a nested form of the sum of inverse factorials, which not only increases the convergence rate, but also allows for exponentiation at the same time:
$$e^x = 1 + x \left( 1 + \frac x 2 \left( 1 + \frac x 3 \left( 1 + \frac x 4 \bigg( 1 + \dots \bigg)\right)\right)\right)$$
\$\ln x\$ is slightly more complicated. All convergent series seem to work for \$x \le 1\$ or \$x \ge 1 \$, but not both (Newton's iteration does not have this limitation, but requires the calculation of \$e^{x_n}\$ each step). This isn't really a problem, though, given the log identity:
$$\ln x = -\ln \frac 1 x$$
This means that if, for example, the iteration you're using only works on \$0 < x \le 1\$ and \$x > 1\$, you can use the multiplicative inverse of \$x\$ and negate the result. Because I was using a nested identity for \$e^x\$, I also chose to use a nested identity for \$\ln x\$:
$$\ln(1 + x) = x\left(1 - x\left(\frac 1 2 - x\left(\frac 1 3 - x\left(\frac 1 4 - \dots \right)\right)\right)\right)$$
where \$0 < x \le 1\$
Or equivalently, as demonstrated by Paul Walls' implementation:
$$\ln(1 + x) = x - x\left(\frac x 2 - x\left(\frac x 3 - x\left(\frac x 4 - \dots \right)\right)\right)$$
I define the \$0 < x \le 1\$ case as \$x-1\$ (which is necessarily negative), using the absolute value for the inner product, and then allowing a bare \$x\$ value in the fraction to correct the sign.
Sample I/O:
$ echo 2 | php exp_ln.php
7.3890560989307 0.69314718055995

$ echo 0.25 | php exp_ln.php
1.2840254166877 -1.3862943611199

$ echo 2.718281828 | php exp_ln.php
15.154262234523 0.99999999983113

$ echo -0.1 | php exp_ln.php
0.90483741803596 ERROR

Perl 95 93 89 bytes
$e=1+$e/$?*($x.=<>),$l=$_/$?+$l*abs,$_=$x>1?1-1/$x:$x-1while--$?;print"$e ",$x>0?$l:ERROR

Nearly identical to the PHP solution above, with a slightly larger iteration (65535 down to 0).
Edits:

Both 2 byte improvements due to Paul Walls.
Four more bytes saved in Perl by (ab)using $?, which is stored internally as an unsigned short, and by using $_ to save parentheses in abs.

For x = 1e-4, I get php "1.0001000050002 -8.9909564381939" and perl "1.00010000500017 -8.99099322429857". Should be like "1.000100005 -9.21034037195" Anyways nice job taking advantage of ln x = -ln 1/x to use a nested expression

@milest x=1e-5 will be off by even more, because it's the same calculation as x=100000. As it is, x=1e-2 and x=100 are accurate to full floating point precision, and x=1e-3 and x=1000 are accurate to about 5 digits. If more accuracy is needed, the arbitrary 1e4 bound that I've chosen can be increased accordingly.

Python 2 (168 char)
basic implementation of power series
I need to learn a golfing language =/
I increased the bound to 1e-14 (twice from 1e-7) since some values were off a bit in 6 decimal places, works well for input from 1e-5 to 100 (slows down at input approaches 0)
x=input();t,r,i=1,0,1.
while abs(t)>=1e-14:t,r,i=t*x/i,r+t,i+1
if x<=0:s='Error'
else:z=(x-1.)/(x+1);t,s,i=2*z,0,1
while abs(t/i)>=1e-14:t,s,i=t*z*z,s+t/i,i+2
print r,s

Doesn't python support m=1e-7?

yes it does but 1e-7 can be thought of as 1*10^-7 which might be thought of as exponentiation, so I'm not really sure if its allowed here

I will allow for scientific notation.

Haskell, 166 (89 without I/O)
s=1e-7
e x|x>s=1/e(-x)|x>0=1+x|y<-e$x+s=y-y*s
l x|x<1=0-l(1/x)|1>0=sum$map(s/)[1,1+s..x]
n x|x<0="ERROR"|1>0=show$l x
main=interact$unwords.(\x->[show$e x,n x]).read

Takes an alternative approach: we use that
∂/∂x ex = ex
and solve the differential equation numerically, with a simple euler method. Similarly, use
ln x = 1∫x 1/x dx
and calculate the integral with the rectangular method.
Example:

$ echo 2 | ./exp-and-log
  7.389056835370484 0.6931472554471929
  $ echo 0.25 | ./exp-and-log
  1.284025432730133 -1.3862944228194163
  $ echo 2.718281828 | ./exp-and-log
  15.15426430695358 1.0000000576151333
  $ echo -0.1 | ./exp-and-log
  0.9048374135134576 ERROR

It's quite amazingly inefficient, in fact it uses about 4 GB of memory even for these examples (since it's non-tail–recursive... you need to compile (in GHC) with -with-rtsopts=-K2G so it even accepts such a ridiculous stack size).

R (101 bytes)
Note that $$e^{x} = \lim_{n \to \infty}\left(1 + \frac{x}{n}\right)^n.$$ Then, for large enough n, we can approximate e by a product.
n=1e+08;prod(rep(1+x/n,n))

Similarly, note that $$\log(x) = \int_{1}^{x}\frac{1}{t}dt \leq \Delta t \cdot \sum \frac{1}{t+\Delta t}$$
dt=0.1;sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=dt))*dt))

Combined into one answer (80 bytes):
n=1e+08;c(prod(rep(1+x/n,n)),sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=1/n))/n))

Will produce -Inf instead of ERROR in case x < 0.
[1] 7.3890560 0.6931472
[1]  1.284025 -1.386294
[1] 15.15426  1.00000
[1] 0.9048374      -Inf

Or, with the ERROR handling, 101 bytes:
n=1e+08;gsub("-Inf","ERROR",c(prod(rep(1+x/n,n)),sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=1/n))/n)))

[1] "7.38905602540599"  "0.693147188059945"
[1] "1.28402541433558"  "-1.38629438611989"
[1] "15.154261581541"  "1.00000000372749"
[1] "0.904837420549773" "ERROR"

A TIO link would be great.

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

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


text:
Secret Santa Challenge

Possible Duplicate:
Holiday Gift Exchange

Background:
Secret Santa is a Western Christmas tradition in which members of a group or community are randomly assigned a person to whom they anonymously give a gift.
http://en.wikipedia.org/wiki/Secret_Santa

Ok, me and my work colleges did this today during our lunch hour - we made a secret algorithm santa pick random gifters and receivers.
Think of this question as a Christmas Programming Challenge to see who can come up with some of the most elegant solutions for this problem.
Input:
The input should be an array ['Oliver', 'Paul', 'Rowan', 'Darren', 'Nick', 'Atif', 'Kevin']
Output
A representation of something similar to key value pairs for the gifter and receiver. e.g.
Oliver -> Darren,
Paul -> Nick,
Rowan -> Kevin
Kevin -> Atif,
Darren -> Paul,
Nick -> Oliver,
Atif -> Rowan

Deadline: 15th December (for those late christmas shoppers)
Remember: you cannot have a person choosing themselves and the program must not spiral off into an infinite loop when gifter == receiver when there is only one person left.
Rules:

Must not have duplicates
Must be random (we all have different views on what is random - but you get my gist)
No Language constraints
Have fun

Here is mine (not golfed) in ruby:
require 'pp'

def move(array, from, to)
  array.insert(to, array.delete_at(from))
end

gifters = ['Oliver', 'Paul', 'Rowan', 'Darren', 'Nick', 'Atif', 'Kevin'].shuffle!
recievers = gifters.dup

move recievers, recievers.count - 1, 0

pp Hash[gifters.zip recievers]

which spits out:
{"Nick"=>"Darren",
 "Paul"=>"Nick",
 "Kevin"=>"Paul",
 "Rowan"=>"Kevin",
 "Atif"=>"Rowan",
 "Oliver"=>"Atif",
 "Darren"=>"Oliver"}

Input? Or do you want it hard-coded, as in your example? Does the resulting derangement have to be a single cycle, as implemented by your code, or can it be a product of disjoint cycles?

I should have made it clearer in my post. The input should be an array ['Oliver', 'Paul', 'Rowan', 'Darren', 'Nick', 'Atif', 'Kevin'] and it can be a product of disjoint cycles - the rules are pretty open.

this is kinda trivial for a code challenge tag, and only one answer appears to be golf'd, so uh what's the objective here?

It's not quite exactly the same, the other one has a hardcoded list.

the challenge is for fun - to produce the code in different languages with different approaches. The approach with the best intuitive wins (probably based on up votes, so the mass can decide)

k (29 20 chars)
{i!(1_i),*i:(-#x)?x}

    {i!@[i:(-:#x)?x;,/|2 0N#!#x]}
Example
k){i!(1_i),*i:(-#x)?x}`person1`person2`person3`person4`person5
person2| person1
person5| person3
person4| person2
person1| person5
person3| person4

Explanation - as above, shuffles list and maps to rotation of itself.

very small - where can i get a copy of k to run this?

You can grab an evaluation version of the interpreter here http://kx.com/software.php . It's one interpreter for both q and k

Ruby - 161 42 chars
#!/usr/bin/env ruby
require 'csv'

gifters = CSV.read(ARGV[0]).first

receivers = gifters.shuffle!.dup
puts Hash[gifters.zip(receivers << receivers.shift)]

Usage
./secret_santa path_to_some_csv
=> {"Edward"=>"Alan", "Alan"=>"Charlie", "Charlie"=>"Dave", "Dave"=>"Brett", "Brett"=>"Edward"}

Update
r=ARGV.shuffle!.dup;p ARGV.zip(r<<r.shift)

As this is a code golf problem, I added the language and char count to your answer. I think there's still potential to shorten the code, for example using single char variable names or removing line breaks.

This can be shortened to 38 by replacing ARGV by $* r=$*.shuffle!.dup;p $*.zip(r<<r.shift)

    NSMutableArray *people =
    [NSMutableArray arrayWithArray:@[@"Oliver", @"Paul", @"Rowan", @"Darren", @"Nick", @"Atif", @"Kevin"]];
    [people sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
         return (arc4random_uniform(3)-1);
    }];

    for (int i = 0;  i < [people count]; i++)
        NSLog(@"%@ gifts %@", people[i], people[(i+1)%[people count]]);


text:
Calculate the correlation coefficient
Given a series of numbers for events X and Y, calculate Pearson's correlation coefficient. The probability of each event is equal, so expected values can be calculated by simply summing each series and dividing by the number of trials.
Input
1   6.86
2   5.92
3   6.08
4   8.34
5   8.7
6   8.16
7   8.22
8   7.68
9   12.04
10  8.6
11  10.96

Output
0.769

Shortest code wins. Input can be by stdin or arg. Output will be by stdout.
Edit: Builtin functions should not be allowed (ie calculated expected value, variance, deviation, etc) to allow more diversity in solutions. However, feel free to demonstrate a language that is well suited for the task using builtins (for exhibition).
Based on David's idea for input for Mathematica (86 char using builtin mean)
m=Mean;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/Sqrt[(m@(x^2)-m@x^2)(m@(y^2)-m@y^2)]

m = Mean;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y) - m@x*m@y)/((m@(x^2) - m@x^2)(m@(y^2) - m@y^2))^.5

Skirting by using our own mean (101 char)
m=Total[#]/Length[#]&;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

m = Total[#]/Length[#]&;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

Very nice streamlining of the Mathematica code, using your own mean!

The MMa code can be shortened. See my comment under David's answer. Also, in your code you may define m=Total@#/Length@#&

PHP 144 bytes
<?
for(;fscanf(STDIN,'%f%f',$$n,${-$n});$f+=${-$n++})$e+=$$n;
for(;$$i;$z+=$$i*$a=${-$i++}-=$f/$n,$y+=$a*$a)$x+=$$i*$$i-=$e/$n;
echo$z/sqrt($x*$y);

Takes the input from STDIN, in the format provided in the original post. Result:

0.76909044055492

Using the vector dot product:

where  are the input vectors  adjusted downwards by  and  respectively.
Perl 112 bytes
/ /,$e+=$`,$f+=$',@v=($',@v)for@u=<>;
$x+=($_-=$e/$.)*$_,$y+=($;=$f/$.-pop@v)*$;,$z-=$_*$;for@u;
print$z/sqrt$x*$y

0.76909044055492

Same alg, different language. In both cases, new lines have been added for 'readability', and are not required. The only notable difference in length is the first line: the parsing of input.

Mathematica 34 bytes
Here are a few ways to obtain the Pearson product moment correlation.  They all produce the same result.
From Dr. belisarius: 34 bytes
Dot@@Normalize/@(#-Mean@#&)/@{x,y}

Built-in Correlation function I: 15 chars
This assumes that x and y are lists corresponding to each variable.
x~Correlation~y

0.76909

Built-in Correlation function II: 31 chars
This assumes d is a list of ordered pairs.
d[[;;,1]]~Correlation~d[[;;,2]]

0.76909

The use of ;; for All thanks to A Simmons.

Relying on the Standard Deviation function: 118 115 chars
The correlation can be determined by:
s=StandardDeviation;
m=Mean;
n=Length@d;
x=d[[;;,1]];
y=d[[;;,2]];
Sum[((x[[i]]-m@x)/s@x)((y[[i]]-m@y)/s@y),{i,n}]/(n-1)

0.76909

Hand-rolled Correlation: 119 chars
Assuming x and y are lists...
s=Sum;n=Length@d;m@p_:=Tr@p/n;
(s[(x[[i]]-m@x)(y[[i]]-m@y),{i,n}]/Sqrt@(s[(x[[i]]-m@x)^2,{i,n}] s[(y[[i]] - m@y)^2,{i,n}]))

0.76909

I get 0.076909 for the last code snippet. Also why do you have s = StandardDeviation; when s is never applied?

Considering assumptions in answer for Q-language, in Mathematica it is just x~Correlation~y

@VitaliyKaurov, Yes, good point, now taken into account.

@milest. Of course! StandardDeviation was "legacy" from the earlier solutions. Think I'll reserve s for Sum.

@milest The error in the final output was also due to /(n-1) being mistakenly carried over from the earlier solution. Now corrected.

In the final one you should be able to save 4 chars by taking the root of the product rather than the product of the roots. Might also be worth defining your own function to calculate stddev?

Good, about the square root. BTW, the final approach does use my own stddev.  (In that case, s is an abreviation of Sum.

I meant that defining a function would probably be shorter than repeating s[(#[[i]] - m@#)^2, {i, n}].

I follow the logic of your suggestion, but I don't see any economy of code aside from {i,n} which would be offset by the additional code for the definition itself.  I don't want to define the function in such a way that incrementing always stops at a specific n that was not passed as a parameter.

The following has 82 chars: n=Length@x;z@u_:=Sum[u,{i,n}];u@p_:=p[[i]]-Tr@p/n;z[u@x u@y]/(z[u@x^2]z[u@y^2])^.5

And following is 40 r@x_:=x-Mean@x;r@x.r@y/Norm@r@x/Norm@r@y

Neat. I've never used Norm.

This is 37 r=#-Mean@#&;r@x.r@y/Norm@r@x/Norm@r@y

This is 35 r=#-Mean@#&;n=r@#/Norm@r@#&;n@x.n@y

This is 34 Dot@@Normalize/@(#-Mean@#&)/@{x,y}

Your responses are too good to leave in the margins.  Shall I convert my post into a community wiki so you can paste them above, or would you like to post them as your own answer?

;; shaves a byte off each instance of All in your builtin answers

Miles, s is used in the final line of code.

Q
Assuming builtins are allowed and x,y data are seperate vectors (7 chars):
x cor y

If data are stored as orderded pairs, as indicated by David Carraher, we get (for 12 characters):
{(cor).(+)x}

Don't correlation data normally consist of ordered pairs?

I added al alternative for that case

MATLAB/Octave
For the purpose of demonstrating built-ins only:
octave:1> corr(X,Y)
ans =  0.76909
octave:2>

J, 30 27 bytes
([:+/*%*&(+/)&.:*:)&(-+/%#)

This time as a function taking two arguments. Uses the vector formula for calculating it.
Usage
   f =: ([:+/*%*&(+/)&.:*:)&(-+/%#)
   (1 2 3 4 5 6 7 8 9 10 11) f (6.86 5.92 6.08 8.34 8.7 8.16 8.22 7.68 12.04 8.6 10.96)
0.76909

Explanation
Takes two lists a and b as separate arguments.
([:+/*%*&(+/)&.:*:)&(-+/%#)  Input: a on LHS, b on RHS
                   &(     )  For a and b
                         #     Get the count
                      +/       Reduce using addition to get the sum
                        %      Divide the sum by the count to get the average
                     -         Subtract the initial value from the average
                             Now a and b have both been shifted by their average
                             For both a and b
                *:             Square each value
         (+/)&.:               Reduce the values using addition to get the sum
                               Apply in the inverse of squaring to take the square root
                               of the sum to get the norm
       *&                    Multiply norm(a) by norm(b)
     *                       Multiply a and b elementwise
      %                      Divide a*b by norm(a)*norm(b) elementwise
 [:+/                        Reduce using addition to the sum which is the
                             correlation coefficient and return it

You can factor out the x and y in the final line by stitching them together with ,. to give you ((m@:*/@|:-*/@m)%%:@*/@(m@:*:-*:@m))x,.y

I have to admit, the code in itself looks gorgeous... speaking as someone who loves his non-alphanumeric code... ;)

There is a shorter 24 bytes version +/ .*&(%+/&.:*:)&(-+/%#) recognized by Oleg on the J forums.

APL 57
Using the dot product approach:
a←1 2 3 4 5 6 7 8 9 10 11

b←6.86 5.92 6.08 8.34 8.7 8.16 8.22 7.68 12.04 8.6 10.96

(a+.×b)÷((+/(a←a-(+/a)÷⍴a)*2)*.5)×(+/(b←b-(+/b)÷⍴b)*2)*.5

0.7690904406

Python 3, 140 bytes
E=lambda x:sum(x)/len(x)
S=lambda x:(sum((E(x)-X)**2for X in x)/len(x))**.5
lambda x,y:E([(X-E(x))*(Y-E(y))for X,Y in zip(x,y)])/S(x)/S(y)

2 helper functions (E and S, for expected value and standard deviation, respectively) are defined. Input is expected as 2 iterables (lists, tuples, etc). Try it online.

Oracle SQL 11.2, 152 bytes (for exhibition)
SELECT CORR(a,b)FROM(SELECT REGEXP_SUBSTR(:1,'[^ ]+',1,2*LEVEL-1)a,REGEXP_SUBSTR(:1,'[^ ]+',1,2*LEVEL)b FROM DUAL CONNECT BY INSTR(:1,' ',2,LEVEL-1)>0);

Un-golfed
SELECT CORR(a,b)
FROM
(
  SELECT REGEXP_SUBSTR(:1, '[^ ]+', 1, 2*LEVEL-1)a, REGEXP_SUBSTR(:1, '[^ ]+', 1, 2*LEVEL)b
  FROM DUAL
  CONNECT BY INSTR(:1, ' ', 2, LEVEL - 1) > 0
)

Input string should use the same decimal separator as the database.

Python 3 with SciPy, 52 bytes (for exhibition)
from scipy.stats import*
lambda x,y:pearsonr(x,y)[0]

An anonymous function that takes input of the two data sets as lists x and y, and returns the correlation coefficient.
How it works
There's not a lot going on here; SciPy has a builtin that returns both the coefficient and the p-value for testing non-correlation, so the function simply passes the data sets to this and returns the first element of the (coefficient, p-value) tuple returned by the builtin.
Try it on Ideone


text:
Write a java code to detect the JVM version
The objective is to write java code that detects the JVM version relying in compatibility changes, side effects, bugs and/or undefined behavior that works in a way in one version and another way in another version. Further, the code should be at least a bit readable, without sacrificing whitespaces and legible variable names.
To ensure that objective, the exact formal rules are:

The code must be written in java and should output the JRE version in which it is running.
The code must not use any JDK or JRE API provided specifically for detecting the java version or which gives the JDK or JRE version for free.
The code must not use reflection.
The code is only required to work in Hotspot Java SE 5, 6 and 7, but may work in other JVMs.
The code must not use any third-party libraries in the classpath.
The code must not start any other process, java or not.
The code must not use environment variables.
The code must not search the file system looking for pre-existing files or folders.
The code must be contained in a single file and be called via public static void main(String[] args) or public static void main(String... args).
The code must not use any non-public API present in the JRE.
The code must not generate any NoClassDefFoundError, NoSuchMethodError, ClassNotFoundException or NoSuchMethodException during its execution.
The code should run in a system disconnected from the internet or from any local network.
You should provide an explanation of why it behaves in one way in a version and another way in another version.

Scoring
The method used for measuring the best solution is max(n/s), where n is the number of different java versions detected without violating any of these rules (at least versions 5, 6 and 7) and s is the number of lexical tokens in the solution.

Could not find a better tag, and I had to provide at last two. Further, I do not have enough rep to create new tags. The reason for java is because it is supposingly a very portable language, so writing that would be very interesting. Further, the java versions are defined in a way that we can compare entries detecting the environment with uniformity, without ending to have to compare oranges to apples.

You could consider [underhanded] arguing that VM version detection is a step in attacking the system. I can't say that I have another suggestion.

@dmckee Dropped the [code-golf] tag. Add the [underhanded] tag. Could you please create the [java] tag?

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

@cat, you should instead have removed the tag, because it didn't fit the question.

6/102 = 0.0588
Detects 6 versions. Has 102 lexical tokens (down from 103, after I deleted public in public class).
import java.security.Signature;

class GuessVersion {
        public static void main(String[] args) {
                String version = "Java 1.1";
                try {
                        "".getBytes("ISO8859_13");
                        version = "Java 1.3";

                        "".getBytes("ISO8859_15");
                        version = "Java 1.4";

                        Signature.getInstance("SHA256withRSA");
                        version = "Java 5";

                        "".getBytes("KOI8_U");
                        version = "Java 6";

                        Signature.getInstance("SHA256withECDSA");
                        version = "Java 7";
                } catch(Exception e) {}
                System.out.println(version);
        }
}

Java 1.1 introduced character encodings and cryptographic algorithms to Java.  Later versions added more encodings and algorithms. This program tries to use encodings and algorithms until it catches an exception. I expect a missing encoding to throw java.io.UnsupportedEncodingException and a missing algorithm to throw java.security.NoSuchAlgorithmException.
I had an old PowerPC Macintosh with four old versions of Java. My OpenBSD machine has two more versions, so I tested these six versions:

Java 1.1.8 in MRJ 2.2.6 for Mac OS 9.2.2
Java 1.3.1_16 for Mac OS X Panther
Java 1.4.2_21 for Mac OS X Tiger
Java 1.5.0_19 for Mac OS X Tiger
OpenJDK 1.6.0_32 for OpenBSD 5.5
OpenJDK 1.7.0_21 for OpenBSD 5.5

This program can also run in JamVM 1.5.4 and gcj 4.8.2 for OpenBSD, but does not identify them as different implementations. It only prints "Java 5".
Mac OS Runtime for Java
Thanks to "Write once, run everywhere!", I may write this program once, compile it once, and run one GuessVersion.class in all eight virtual machines. I need a compiler for Java 1.1, the oldest version in my collection.
My compiler is the javac tool from MRJ SDK 2.2. Because the Classic Mac OS had no command line, javac is a pretty graphical tool where I select files and options and click "Do Javac". After I edit my code, I just click "Do Javac" again.

The easiest way to run GuessVersion.class is to open it in JBindery, another tool from MRJ SDK 2.2. The runtime is MRJ 2.2.6, an implementation of Java 1.1.8.

I'm not sure what my score is, because it depends on what precisely you consider to be a lexical token, but I'm trying to abuse that counting system as much as possible with a long string...
It also depends on whether you count this as identifying 7 different versions or 16... (It could trivially be extended up to 190).
class V extends ClassLoader
{
    public static void main(String[]args)
    {
        for(byte b=60;;)
            try {
                byte[]buf="\u00ca\u00fe\u00ba\u00be\u0000\u0000\u00002\u0000\u0005\u0007\u0000\u0003\u0007\u0000\u0004\u0001\u0000\u0001A\u0001\u0000\u0010java/lang/Object\u0006\u0000\u0000\u0001\u0000\u0002\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000".getBytes("ISO-8859-1");
                buf[7]=b--;
                new V().defineClass(buf,0,53);
                System.out.println(b-43);
                break;
            }
            catch(Throwable t){}
    }
}

It works by attempting to define an interface in a custom classloader with descending major version numbers of the class format. The first one which doesn't throw a java.lang.UnsupportedClassVersionError corresponds to the VM's version.

Counted 84 tokens. Still did not tested it though.

Your answer is genial. Could trivially reduce to 83 tokens using String... args.

@Victor, that would complicate the question of whether it supports 7 different versions even more. I'm not aware of any compiler which supports Java 5 syntax and compiles to Java 1-compatible class files.

Good point. I forgot about that.

Java 1.1.8 (in MRJ 2.2.6) failed to compile this, until I added 17 more tokens: protected Class loadClass(String name, boolean resolve) { return Object.class; }. The current API docs neglect to mention how this was an abstract method before Java 1.2. I return Object.class because the method gets one call for "java.lang.Object".

class Evil {
    public static void main(String... args) {
        String s1 = "Good";
        s1 += "morning";
        int a = 7;
        if (s1 != s1.intern())
            try {
                a--;
                javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar().equals(null);
            } catch (Throwable e) {
                a--;
            }
        System.out.println(a);
    }
}

The interning algorithm changed between Java 6 and 7. See https://stackoverflow.com/a/7224864/540552
XMLGregorianCalendar.equals(null) used to throw NullPointerException in java 5, but this was fixed in java 6. See https://bugs.java.com/bugdatabase/view_bug?bug_id=6285370
100 96 92 87 85 tokens here.
Thanks to Peter Taylor for reducing 7 tokens.

You can save 3 tokens by storing the version number in s1. You can probably save a further 2 by catching Throwable directly, on the assumption that DatatypeConfigurationException won't be thrown.

Or better, keep int a but initialise it immediately, so the if block becomes empty. Negate the condition, remove the else, and use -- instead of direct assignment to a.


text:
There Was A Stream
 Challenge
Write a program that generates the song "There Was A Stream", detailed below.
 Description
The song "There Was a Stream" is a camping song. It takes N parameters and generates a song of length O(N2) lines. A sample song (first 3 verses) is given here.
 Rules

Your entry must take a list of strings and output a valid song. It may be a function (that takes an array of strings) or a program (that takes strings from ARGV or STDIN). Output may be a return value or output to STDOUT or STDERR.
It must run within 1/2 second on my machine (1.66GHz Intel Atom, 1GB RAM, Ubuntu 12.04) for all invocations with less than 15 parameters.
Verses must be separated by a blank line.
No inbuilt compression function (e.g. gzip), whether from the core or from libraries. Things like rot13, md5, base64 etc. are okay though.
You may include a data file (that is placed in the same directory and named whatever you wish), but its score will be added to the total for the program.

Scoring
Count the number of characters (if you use ASCII) or raw bytes (if you use something else).
Command-line flags (without the hyphens) are included, but not the interpreter name, for example #!/usr/bin/perl -n adds 1 to the character count. All whitespace is included.As with all code-golf, the entry with the lowest character count wins.Deadline: 14 December 2012
Example
INPUT: bank house
OUTPUT: (given above)
Reference implementation (ungolfed, very ugly code): http://pastebin.com/VeR4Qttn

That third verse looks suspicious.

I've edited it. Tell me if anything else looks weird.

Any restrictions on pre-existing compression libraries and/or character encoding?

No compression libraries, any character encoding you wish (but count bytes). More details above.

Kind of a duplicate: http://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i

@mob: That question required answers to generate a fixed, constant song. This question requires entries to dynamically generate the song based on parameters.

Perl 239 + 2 = 241 bytes
This is a mostly binary solution, so as usual, this is a program to generate it:
generator.pl
use MIME::Base64;

$data = <<EOD;
JF89bGMgcGFjayB1NjAsJ8MqbtCBITBInQmKJcpWt4c2oWhLBPwjAkyBIiUwjBI3Ql9c9GoWtJZbuTd5
ZbuWhPwjAkyBIyQjDBFXQlLpGtKJWhP2t4c2r7mhFQjAqdM2t4eTjjk2aJcpWtKJWrb77ms6Kbpc2qKZ
6E1rmtKJWo7JYcmorNZWhM6+U1LpGobLGt4c2osqZ6NGobpGp4eTk0wiTBIXQlLpGr7mtKIdGhPwjBIT
nQkyBISUwjBFXQtKJWhPxAjBLHR7KdNLJWh5r8ms9MpYbTIFQyc7eS8zLTovCkFGSUpUVyAvO2V2YWw=
EOD

print decode_base64($data);

Accepts input from STDIN, space separated, two extra bytes for the -na option. Sample usage:
$ perl generator.pl > out.pl

$ stat -c %s out.pl
239

$ echo bank house | perl -na out.pl
There was a stream
(There was a stream)
Just a teeny-weeny stream
(Just a teeny-weeny stream)
And the stream was on its way...
Where the moon shines high
In the clear blue sky
And all was bright and gay.

And on that stream
(And on that stream)
There was a little bank
(There was a little bank)
Just a teeny-weeny bank
(Just a teeny-weeny bank)
And the bank was on the stream
And the stream was on its way...
Where the moon shines high
In the clear blue sky
And all was bright and gay.

And on that bank
(And on that bank)
There was a little house
(There was a little house)
Just a teeny-weeny house
(Just a teeny-weeny house)
And the house was on the bank
And the bank was on the stream
And the stream was on its way...
Where the moon shines high
In the clear blue sky
And all was bright and gay.

Method
Consider the following UU-Encoded string:
\PRINT($A,$B="8HERE:WAS:A:$L$_","3($B)3",$C="7UST:A:TEENY-WEENY:$_","3($C)",,$5="
\4ND:THE:$_:WAS:ON:$5","ITS:WAY...39HERE:THE:MOON:SHINES:HIGH36N:THE:CLEAR:BLUE:$
\SKY34ND:ALL:WAS:BRIGHT:AND:GAY.33"),$A="4ND:ON:THAT:$_",$A.="3($A)3",$5="THE:$_$
5",$L='LITTLE:'FOR:STREAM,@5#

After applying a lc,y/3-:/\nAFIJTW / it becomes this:
\print($a,$b="There was a $l$_","
($b)
",$c="Just a teeny-weeny $_","
($c)",,$F="
\And the $_ was on $F","its way...
Where the moon shines high
In the clear blue $
\sky
And all was bright and gay.

"),$a="And on that $_",$a.="
($a)
",$F="the $_$
F",$l='little 'for stream,@F#

Which is basically the 269 byte solution below.
There's a few problems with this method, though. UU-Encoded strings are limited to characters 33-96, which excludes space, newline, and { | } ~, as well as all lower-case letters. The solution I chose, is to apply lc after the pack u, and then translate 8 characters: space, newline, and the 6 upper-cased I needed. This leaves an 18 byte footprint, which is fairly excessive, but it produces the desired result.
The other problem is that each line needs to begin with the same character (here I chose \ corresponding to a decoded length of 60 (92 - 32), which is an encoded length of 80), except for the last line, which needs to begin with the character reflecting its length. Here I ended up with 21 (padding with a # to be evenly divisible by 3), corresponding to 5. No problem, I'm replacing 5 anyway, so I chose it as one of my variables. Perl seems to be incredibly lenient about where you can place backslashes. This program even begins with one.
It is possible to instruct perl to use a other characters to begin each line, such as M (the default value), but none seem quite as flexible as a backslash. As an aside, this method should be equally as effective in Ruby. If I had any skill in the language, I might be tempted to try it.
For reference, my previous solutions remain below.

Perl 267 + 2 = 269 bytes
(print$a,$b="There was a $l$_","
($b)
",$c="Just a teeny-weeny $_","
($c)",$d="
And the $_ was on $d",'its way...
Where the moon shines high
In the clear blue sky
And all was bright and gay.

'),$a="And on that $_",$a.="
($a)
",$d="the $_$d",$l='little 'for stream,@F

Accepts input from STDIN, space separated, two extra bytes for the -na option. Sample usage:
$ echo bank house | perl -na stream-song.pl

PHP 286 bytes
No real attempt at compression, just output reusage.
<?for($w=stream;$w;$a="And on that $w",$a.="
($a)
",$l='little ',$d="the $w$d",$w=next($argv))echo$a,$b="There was a $l$w","
($b)
",$c="Just a teeny-weeny $w","
($c)",$d="
And the $w was on $d",'its way...
Where the moon shines high
In the clear blue sky
And all was bright and gay.

';

Accepts input as command line arguments. Sample usage:
$ php stream-song.php bank house

Haskell, 366 characters
t="stream"
b o="And the "++o++" was on "
p s=[s,'(':s++")"]
a(o:q@(p:_))=(b o++"a "++p):a q
a[o]=[b o++"its way..."]
v l@(o:q)=w q++p("There was a "++if o==t then o else"little "++o)++p("Just a teeny-weeny "++o)++a l++["Where the moon shines high","In the clear blue sky","And all was bright and gay.",""]
w m@(y:_)=v m++p("And on that "++y)
w[]=[]
s=v.reverse.(t:)

As permitted by the problem statement, this is a function s :: [String] -> String, where the input is the objects and the return value is a list of lines of the song.
This is nowhere near the current leader in this challenge, but it's as far as I got and I thought someone might like to see if it can be improved. I think its main failing is trying too hard to capture all of the structure of the song in the structure of the program. It also might be interesting to rewrite it to use lists of words (replace ++ with , and fewer spaces), or \ns rather than a list of lines.
Fluffy source:
stream="stream"
andthe o="And the "++o++" was on "
p s=[s,'(':s++")"]

ander :: [String] -> [String]
ander(o:os@(p:_))=(andthe o++"a "++p):ander os
ander[o]=[andthe o++"its way..."]

outerVerse :: [String] -> [String]
outerVerse l@(o:os)=recurse os++p("There was a "++if o==stream then o else"little "++o)++p("Just a teeny-weeny "++o)++ander l++["Where the moon shines high","In the clear blue sky","And all was bright and gay.",""]

recurse :: [String] -> [String]
recurse m@(y:_)=outerVerse m++p("And on that "++y)
recurse[]=[]

song=outerVerse.reverse.(stream:)
go xs = putStr $ unlines $ song xs

Defluffifier (in Perl):
#!/usr/bin/perl -wp

s/ ?\+\+ ?/++/g;
s/ander/a/g;
s/andthe/b/g;
s/iverse/i/g;
s/song/s/g;
s/stream(?!")/t/g;
s/\bos\b/q/g;
s/outerVerse/v/g;
s/recurse/w/g;
s/ends/z/g;

s/^go .*//s;
s/--.*//s;
s/^\s\Z//s;
s/^.*::.*\Z//s;

Python 2.7 352 Bytes
import urllib as u;import re,sys;v=sys.argv;f=lambda l,o,n:[re.sub(o,n,i) for i in l];n='\n';d=-1;m=re.findall('i\d.+>(.+)</d',u.urlopen('http://goo.gl/48fMV').read());a=m[:8]+[n];z=range;s='stream'
for t in z(len(v)+d):a+=f(m,s,v[t])[9:11]+f(m,s,'little '+v[t+1])[:4]+['And the '+v[i+1]+' was on a '+v[i] for i in z(t,d,d)]+m[4:8]+[n]
print n.join(a)

Example usage:
python stream bank house

Output:
There was a stream
(There was a stream)
Just a teeny-weeny stream
(Just a teeny-weeny stream)
And the stream was on its way...
Where the moon shines high
In the clear blue sky
And all was bright and gay.

And on that stream
(And on that stream)
There was a little bank
(There was a little bank)
Just a teeny-weeny little bank
(Just a teeny-weeny little bank)
And the bank was on a stream
And the stream was on its way...
Where the moon shines high
In the clear blue sky
And all was bright and gay.

And on that bank
(And on that bank)
There was a little house
(There was a little house)
Just a teeny-weeny little house
(Just a teeny-weeny little house)
And the house was on a bank
And the bank was on a stream
And the stream was on its way...
Where the moon shines high
In the clear blue sky
And all was bright and gay.

Un-golfed (also added a few a+=s):
#!/usr/bin/env python

import urllib as u
import re
import sys

v=sys.argv

f=lambda l,o,n: [re.sub(o,n,i) for i in l]

n='\n';
d=-1;
m=re.findall('i\d.+>(.+)</d',u.urlopen('http://goo.gl/48fMV').read())
a=m[:8]+[n]
z=range
s='stream'

for t in z(len(v)+d):
    a+=f(m,s,v[t])[9:11]
    a+=f(m,s,'little '+v[t+1])[:4]
    a+=['And the '+v[i+1]+' was on a '+v[i] for i in z(t,d,d)]
    a+=m[4:8]+[n]
print n.join(a)


text:
Pseudosort a list in 2*n comparisons
Write a program that takes a list of n space-separated integers, and outputs a permutation of that list using a maximum of 2*n comparisons.
It should loop this until an empty line is input.  Alternatively, it can accept inputs until an empty line is given, then output all the permutations.
Though your program only has to work on integers, it should be possible to implement your algorithm for any comparable data structures.  For example, using sign(a-b) to get extra comparisons is illegal, because the same algorithm can't be applied to data structures without numerical values.
Example session:
>0 1 2 3 4
0 1 2 3 4
>7 9 2 1
1 2 7 9
>6 7 4 5 2 3 0 1
0 2 3 1 4 5 6 7
>

or
>0 1 2 3 4
>7 9 2 1
>6 7 4 5 2 3 0 1
>
0 1 2 3 4
1 2 7 9
0 2 3 1 4 5 6 7

note: > shouldn't actually be printed, it's just being used to notate input vs output.
Scoring
Scoring is based mostly on how well sorted the permutations are, but also favours concise code.
Run your program with this file as input.  Use your program's output as input to this python script.  This script works under both python 2.7 and 3.3.  Other versions weren't tested.
import sys
def score(l):
    n = len(l)
    w = n**2 // 2
    s = sum(abs(l[i]-i)for i in range(n))
    return float(s)/w
s = 0.0
for i in range(40000):
    s += score([int(n) for n in sys.stdin.readline().split()])
print (int(s))

Your score is the output of the above script plus the length of your program
Explanation of Scoring
In the input file, there are 1000 lists for each length n in the range 10 <= n < 50.  In total, there are 40000 lists.  No two elements of a list will be equal.
To score a list, we define the unsortedness of a list as the sum of distances of each element from where it should be.  For example, for the list [0,1,4,3,2], the unsortedness is 4, because 4 and 2 are each 2 positions from where they should be, and the rest of the numbers are correct.
The worst case unsortedness of a list of length n is n^2 / 2, using integer division.
The score of a list is its unsortednes divided by the maximum unsortedness.  This is a number between 0.0 (sorted) and 1.0 (reversed).
Your total score is the sum of all scores in the input rounded down to an integer, plus the length of your program.  Because there are 40000 cases, a better pseudo-sort is likely better than shorter code, but if there is some optimal solution, then the shortest implementation of that solution will win.

Can we use bit manipulation functions? We can't assume that (x-y) is defined, but what about (x & ~y)?

"It should be possible to implement your algorithm for any comparable data structures", so no.

Well, I figured that wasn't what you wanted. But I'm pretty sure any data structure can be represented in binary. :)

Yes, but the comparison of binary representations isn't necessarily the same as how comparisons are defined for the structure.

Right. Don't know what I was thinking.

this file link is dead :(

Python, 7910 (7704 + 206)
This was inspired by shell sort.  I found relatively good coefficients for the gap sequence (g) by checking a few hundred alternatives.  The number of comparisons is limited by counting explicitly (n).
s=1
while s:
 s=map(int,raw_input().split());k=len(s);n=2*k;g=13*k/23
 while g:
  for i in range(g,k):
   n-=1
   if n<0:break
   if s[i]<s[i-g]:s[i],s[i-g]=s[i-g],s[i]
  g=3*g/5
 print' '.join(map(str,s))

I started implementing a combsort, until I realized that's exactly what your solution is. I was able to get a best score of 7428 by tweaking a few constants: http://codepad.org/mla6qDlN. The problem with using integer division for your gaps, is that it will decrease more quickly than it should.

@primo: Ok, I hadn't heard about comb sort before.  It seems that you can get a better score than my current one with integer division too...

Indeed you can. Take your code, exactly as written, and replace g=13*k/23 with g=28 for a score of 7541. This will allow it to always take the same path downwards. [28, 16, 9, 5, 3, 1], which seems to be the best for the mutliplier you're using.

Scratch that. Start with g=16 instead for 7449.

@primo: I'll leave the solution as is for now, since starting with a constant would no longer feel like a solution to the general problem.  But thanks for all the improvements!

Ruby, 10140 (9988 + 152)
def q a
  p=a.pop
  l,m=a.partition{|x|x<p}
  [l,p,m]
end
while a=gets
  a=a.split.map(&:to_i)
  l,p,m=q a
  puts (q(l)+[p]+q(m)).flatten.join(" ")
end

This simply performs two rounds of quicksort. It removes the last element, then divides the remaining array into those less than and those greater than that element (n-1 comparisons).  Then it does the same thing to those two (n-3 comparisons) and joins the result in order. Total comparisons are 2*n - 4 (worst case 2*n - 2), so there's definitely room for improvement.

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


text:
"Defragmenting" a list
A fragmented file is a file which is seperated into several parts on a harddrive, because it can't fit into a certain space.
On all harddrives, there are files called unmovable files, which are unmovable. To simulate real data on a harddrive, the input will also have unmovable files.
You are given several sequences of consecutive numbers, all scrambled into one list. The goal is to order each of these sequences so that they are placed in as little space as possible. The list can be as big as you need it to be. If there is no space for a sequence, then put a - instead.
To mark the unmovable files, another list, with the same length as the data, will be given after you recieve the data. It will contain either a 0 or a 1. Every 1 within that list means that the corresponding item in the data is unmovable.
Shortest code wins.
Test Cases
The output does not have to be exactly like this, but the length needs to be the same, and all of the sequences need to be ordered.
[ 0,  0,  1,  1,  1,  1,  0,  0,  0,  0,  0]
[25, 30, 11, 12, 13, 14, 68, 69, 31, 26, 32]
Output: [25, 26, 11, 12, 13, 14, 68, 69, 30, 31, 32]
(output length: 11)

[0, 0, 0,  0, 0,  1,  1,  1, 0, 0,  0,  0,  0,  0,  0, 0]
[2, 3, 5, 14, 8, 10, 11, 12, 4, 6, 28, 30, 29, 15, 16, 7]
Output: [14, 15, 16, -, -, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 28, 29, 30]
(output length: 18)

If some part of the challenge is not explained well, tell me! I cannot explain things well.

Yes, the rule telling how we are supposed to eliminate some sequence is not clear (why the 8 instead of the 2 in last example). Also the fact that 15 is present twice in the last array is confusing me...

@Orabîg: ! The last example has a lot of mistakes. I'll fix that.

In the 2nd example, the output length still isn't equal to the input length? Am I misunderstanding? Is the hard drive growing?

@marinus: Every small list must be fit into the big one, so it can increase in size. (you can think of it as a hard drive with infinite space, but the space alloted for the files grows)

@beary605: You might want to put that in your question. It's not obvious.

@beary605: Fixed my program to comply.

What is the correct output, given the input [0 1 0 0 0][1 3 8 2 9]?

@r.e.s.: [- 3 1 2 8 9] or [- 3 8 9 1 2]

I tried to clarify your question by illustrating the fitting with a better alignment, and only then I realized, which rule applies to unmoveable data. It means, you may write your own data to this places where there is a 1, but it must not overlap? What has it to do with unmoveable?

@userunknown: It's probably yet another error with my examples. Unmovable data cannot be touched. Unless you're referring to the one above, which is - 3 1 2 8 9, not -3 1 2 8 9.

I'm referring to example 1: 11-14 is mapped to the 4 places, occupied by ones, isn't it?

@userunknown: Yes it is. I don't see the problem, it's still in the same place.

 APL (132 126 123 147 145 143)
This was a bit harder than I thought it'd be :)
Edit: the hard drive is infinite :S. All sequences that could not fit in the original space, are now appended onto the end of the output.
F←⍬⋄{×⍴⍵:∇1↓⍵⊣{∨/P←S⍷⍨1⍴⍨⍴⍵:S[R]∘←0⊣D[R←1-⍨(⍳⍴⍵)+⌊/P/⍳⍴P]∘←⍵⋄F∘←F,⍵}⊃⍵⋄D[S/⍳⍴S]∘←'-'}G[⍒⊃∘⍴¨G←K⊂⍨1≠|-⌿K,[÷2]¯1⌽K←K[⍋K←(S←~⎕)/D←⎕]]⋄F,⍨D/⍨~⌽∧\⌽S

This is what it does to your 1st and 2nd example (the 2nd example is different, but in your example the output length is not the same as the input length and you said in a comment it was wrong, so...)

⎕:    25 30 11 12 13 14 68 69 31 26 32
⎕:    0  0  1  1  1  1  0  0  0  0  0
25 26 11 12 13 14 30 31 32 68 69

⎕:    2 3 5 14 8 10 11 12 4 6 28 30 29 15 16 7
⎕:    0 0 0 0  0 1  1  1  0 0 0  0  0  0  0  0
14 15 16 - - 10 11 12 2 3 4 5 6 7 8 28 29 30

Explanation:

F←⍬: set F to the empty list. This will hold the overflow.
K←K[⍋K←(S←~⎕)/D←⎕]: read two lists. The first list (numbers) is stored in D. The second list (whether the data is unmovable) is inverted and then stored in S. Get all movable numbers, and sort them. Store this in K.
G←K⊂⍨1≠|-⌿K,[÷2]¯1⌽K: Subtract each element of K from the next element of K. Wherever this is not 1, we found the beginning of a new sequence. Store the list of sequences in G.
G[⍒⊃∘⍴¨G...]: sort the list of sequences by descending length. This way, we place the longest sequences first.
{×⍴⍵:...}G: as long as this list of sequences is not empty...
∇1↓⍵⊣: handle the tail of the list, after...
{...}⊃⍵: doing the following with the head:
∨/P←S⍷⍨1⍴⍨⍴⍵: find, in S, a list of ones that is as long as the current sequence (⍵).
S[R]∘←0⊣D[R←1-⍨(⍳⍴⍵)+⌊/P/⍳⍴P]∘←⍵: if there is one, store ⍵ in D at the first position that it fits, and mark these positions as unmovable in S.
⋄F∘←F,⍵: if there is no room, add it to the overflow.
⋄D[S/⍳⍴S]∘←'-': when we're at the end of the list of sequences, all positions where S is still one are places where we couldn't put anything. Mark these with -.
⋄F,⍨D/⍨~⌽∧\⌽S: then, at the end, display D, with the trailing -s removed, followed by the overflow (F) per the new rules.

wow, it was still wrong. :( Thanks for pointing that out.

@marinus Above you say you place the longest sequence first. If so is this optimum. What would your code do with:[0 0 0 0 0 0 1 1 1 1 0 0 0 0 0][5 2 3 14 1 17 9 10 11 12 18 16 15 7 6]

I decided to tackle this solution in Scala, taking advantage of both functional and imperative features of the hybrid language. Here is the code for my solution.
def orderedSequences(filePieces: List[(Int,Int)]): List[List[(Int,Int)]] = {
  def orderedSequencesR(filePieces: List[(Int,Int)], currentSequence: List[(Int,Int)], sequences: List[List[(Int,Int)]]): List[List[(Int,Int)]] = {
    if(filePieces == Nil) sequences :+ currentSequence
    else if(currentSequence == List.empty) orderedSequencesR(filePieces.tail, List(filePieces.head), sequences)
    else if(filePieces.head._2 == currentSequence.last._2 + 1) orderedSequencesR(filePieces.tail, currentSequence :+ filePieces.head, sequences)
    else orderedSequencesR(filePieces, List.empty, sequences :+ currentSequence)
  }
  orderedSequencesR(filePieces, List.empty, List.empty)
}

def defragment(sequences: List[List[(Int,Int)]], filePieces: List[(Int,Int)]): List[Any] = {
  val largestSequenceLength = sequences.flatten.length
  var solution = scala.collection.mutable.ListBuffer[(Int,Int)]()

  filePieces foreach {filePiece => if(filePiece._1 == 1) solution += filePiece  else solution += ((-1,0))}

  solution ++ Iterator.fill(largestSequenceLength)((-1,0))

  sequences foreach {
      sequence =>
      var sequenceIsInserted = false
      var currentPosition = 0
      while(!sequenceIsInserted) {
        if(solution.slice(currentPosition,currentPosition + sequence.length).forall((s: (Int,Int)) => s._1 == -1)){
          solution = solution.slice(0,currentPosition) ++ sequence ++ solution.slice(currentPosition + sequence.length, solution.length)
          sequenceIsInserted = true
        }
        currentPosition += 1
      }
  }

  solution.map(_._2).toList
}

def getDefragmentedFiles(isUnmovable: List[Int], files: List[Int]) = {
    val filePieces = isUnmovable zip files
    val sequences = orderedSequences(filePieces.filter(os => os._1 == 0).sortBy(t => t._2))
    val bestSolution = defragment(sequences.permutations.toList.sortBy {b => defragment(b, filePieces).length}.head, filePieces)
    println(bestSolution map { case 0 => '-'; case x => x })
}

val isUnmovable = List(0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0)
val files = List(2,3,5,14,8,10,11,12,4,6,28,30,29,15,16,7)
getDefragmentedFiles(isUnmovable, files)

I take the list of movable/unmovable positions along with the files and zip them up. I then get the movable files, sort them in order, and pass them into orderedSequences to get a list of file sequences.
Once I get the sequences, I get all the permutations of the sequences and I brute-force defrag them, taking the solution of the shortest length. This is pretty inefficient, but I can't think of a more efficient solution right now. The defrag method takes each sequence, in order, and iterates through the memory space until a valid spot to place the sequence is found.
After getting the best solution, I prettify it and print it out as a list.

An uncryptified answer is fine, but the question is tagged 'code golf', so you should produce a radically shortened version of the answer, and count its characters.